在JFrame中显示.png图像?

5
我有些困惑,为什么这个代码无法运行?我收到了一个错误消息:

java.lang.NoSuchMethodError: main

Exception in thread "main"

import java.awt.*; 
import javax.swing.*; 

@SuppressWarnings("serial")
public class ShowPNG extends JFrame
{    

  public void main(String arg) 
  { 
    if (arg == null ) {
        arg = "C:/Eclipse/workspace/ShowPNG/bin/a.png";
    }      
    JPanel panel = new JPanel(); 
    panel.setSize(500,640);
    panel.setBackground(Color.CYAN); 
    ImageIcon icon = new ImageIcon(arg); 
    JLabel label = new JLabel(); 
    label.setIcon(icon); 
    panel.add(label);
    this.getContentPane().add(panel); 
    this.setVisible(true);
  }
  
}

2
public void main(String arg) 转换为 public static void main(String [] arg) - OscarRyz
3个回答

11

你的主方法应该是:

public static void main(String[] args)

10

main方法需要被声明为静态的,并且参数类型应该是String[],而不是String。 为了解决这个问题,可以将所有代码放在一个构造函数中,例如:

import java.awt.*; 
import javax.swing.*; 

@SuppressWarnings("serial")
public class ShowPNG extends JFrame
{    
  private ShowPNG(String arg){
      if (arg == null ) {
        arg = "C:/Eclipse/workspace/ShowPNG/bin/a.png";
    }      
    JPanel panel = new JPanel(); 
    panel.setSize(500,640);
    panel.setBackground(Color.CYAN); 
    ImageIcon icon = new ImageIcon(arg); 
    JLabel label = new JLabel(); 
    label.setIcon(icon); 
    panel.add(label);
    this.getContentPane().add(panel); 
  }
  public static void main(String[] args) {
      new ShowPNG(args.length == 0 ? null : args[0]).setVisible(true); 
  }
}

RD是正确的,主方法是错误的,但Leo Izen得到了这个答案,因为他提供了所有的代码。不过这段代码并没有完全起作用...你必须在JFrame上使用this.setSize才能正确地调整大小。无论如何感谢你!请查看下面的帖子获取实际答案。 - djangofan
1
你可以随时使用 Frame.pack(); - Leo Izen

4
这是最终的代码:

这是最终的代码:

import java.awt.*;  
import javax.swing.*;  

@SuppressWarnings("serial") 
public class ShowPNG extends JFrame {   

  public ShowPNG(String argx) { 
    if ( argx == null ) {
      argx = "a.png";
 }   
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 this.setSize(500,640);
    JPanel panel = new JPanel();  
    //panel.setSize(500,640);
    panel.setBackground(Color.CYAN);  
    ImageIcon icon = new ImageIcon(argx);  
    JLabel label = new JLabel();  
    label.setIcon(icon);  
    panel.add(label); 
    this.getContentPane().add(panel);    
  } 

  public static void main(String[] args) { 
      new ShowPNG(args.length == 0 ? null : args[0]).setVisible(true);
  } 

}

1
this.setSize(500,640); .. this.getContentPane().add(panel); 更改为 .. this.getContentPane().add(panel); this.pack(); - Andrew Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接