Java 在 JFrame 中显示 .png 图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4160904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show .png image in a JFrame?
提问by djangofan
I am a little stuck. Why wont this work? I just get a error saying:
我有点卡住了。为什么这行不通?我只是收到一条错误消息:
java.lang.NoSuchMethodError: main
Exception in thread "main"
java.lang.NoSuchMethodError: 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);
}
}
采纳答案by Leo Izen
main needs to be static, and must have an argument of String[], not String.
main 需要是静态的,并且必须有一个 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);
}
}
回答by robert_x44
Your main method should be:
你的主要方法应该是:
public static void main(String[] args)
回答by djangofan
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);
}
}