这是我从一本名为 Java In Easy Steps 的书中获得的 GUI 的基本示例,我按照示例实现了代码,但图像没有出现。我需要做什么才能让它出现,是因为 URL getClassLoader?
理想情况下,我希望能够将文件保存到我的工作区并将该文件用作 GUI 的一部分。
import javax.swing.*;
class Buttons extends JFrame {
JPanel pnl = new JPanel();
ImageIcon tick = new ImageIcon("tickURL");
ImageIcon cross = new ImageIcon("crossURL");
JButton btn = new JButton("Click Me");
JButton tickBtn = new JButton(tick);
JButton crossBtn = new JButton("STOP", cross);
ClassLoader ldr = this.getClass().getClassLoader();
java.net.URL tickURL = ldr.getResource("tick.png");
java.net.URL crossURL = ldr.getResource("cross.png");
public Buttons(){
super("Swing Window");
setSize( 500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
setVisible(true);
pnl.add(btn);
pnl.add(tickBtn);
pnl.add(crossBtn);
}
public static void main(String[]Args){
Buttons gui = new Buttons();
}
}
最佳答案
ClassLoader ldr = this.getClass().getClassLoader();
java.net.URL tickURL = ldr.getResource("tick.png");
java.net.URL crossURL = ldr.getResource("cross.png");
JPanel pnl = new JPanel();
ImageIcon tick = new ImageIcon(tickURL); // <-- a URL is needed here, not a string
ImageIcon cross = new ImageIcon(crossURL); // same here
JButton btn = new JButton("Click Me");
JButton tickBtn = new JButton(tick);
JButton crossBtn = new JButton("STOP", cross);
- 使用类加载器加载您的资源(如果它们位于您的类路径中),
- 使用这些资源创建您的图标,
- 使用这些图标创建按钮
就这么简单。
关于java - JPanel - 带按钮的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976626/