JPanel - 带按钮的窗口
这是我从一本名为 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();
}
}
this is basic example I got for a GUI from a book called Java In Easy Steps, I implemented the code as per the example but the imagery does not appear. What do I need to do in order to make it appear, is because of the URL getClassLoader?
Ideally I would like to be able to save a file to my workspace and use that file as a part of the 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就这么简单。
As simple as that.
我是一名 Java 新手,正在研究同一本书中的相同代码,但结果却同样糟糕(任何代码块都没有出现图标)。对于无知的人(比如我)来说,这本书似乎在说这两个图标是作为 Java 默认包的一部分提供的,这当然不是真的。
答案是,这两个 .png 文件包含在本书的下载中,作者假设您已将这些文件下载到当前目录中,因此代码会看到它们。
因此,当图标可用时,上述两种方法确实有效。
下载地址:http://ineasysteps.com/resource-centre/downloads/
I'm a Java newbie and was plowing through the same code from the same book, with the same bad results (no icons appear for either block of code). For the clueless (like moi) the book seemed to be saying that these two icons were available as part of a Java default package, which of course is not true.
The answer is that these two .png files were included in a download available for the book and the author assumed you had downloaded the files into the current directory, so the code would see them.
So both methods described above do indeed work when the icons are available.
The downloads are available here: http://ineasysteps.com/resource-centre/downloads/