[英]Show .png image in a JFrame?
I am a little stuck. 我有点卡住了。 Why wont this work?
为什么不这样做? I just get a error saying:
我只是得到一个错误说:
java.lang.NoSuchMethodError: main
java.lang.NoSuchMethodError:main
Exception in thread "main"
线程“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);
}
}
你的主要方法应该是:
public static void main(String[] args)
main needs to be static, and must have an argument of String[], not String. main需要是static,并且必须有String []的参数,而不是String。
To fix this stick everything in a constructor, such as 要在构造函数中修复这个东西,例如
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);
}
}
This was the finished code: 这是完成的代码:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.