Java 如何将图像放到Jbutton上
我在想如何在java上编写这个简单的老虎机时遇到了很多麻烦,第一个最容易解决的问题是在eclipse上运行程序时将3.png图像放到JButton上。所有文件也都在源文件夹中 下面是我的代码现在的样子:Java 如何将图像放到Jbutton上,java,swing,Java,Swing,我在想如何在java上编写这个简单的老虎机时遇到了很多麻烦,第一个最容易解决的问题是在eclipse上运行程序时将3.png图像放到JButton上。所有文件也都在源文件夹中 下面是我的代码现在的样子: JButton b = new JButton("Green.png"); window.getContentPane().add(b); JButton c = new JButton("Red.png"); window.getContentPane().add(c); JButton d
JButton b = new JButton("Green.png");
window.getContentPane().add(b);
JButton c = new JButton("Red.png");
window.getContentPane().add(c);
JButton d = new JButton("Purple.png");
window.getContentPane().add(d);
JButton z = new JButton();
window.getContentPane().add(z);
JButton a = new JButton("Spin");
window.getContentPane().add(a);
JButton y = new JButton();
window.getContentPane().add(y);
Random random = new Random();
ActionListener x = new EventHandler();
a.addActionListener(x);
您对
JButton
使用了错误的构造函数。那一个只设置了标题
使用允许您设置文本和图标的构造函数
ImageIcon icon = createImageIcon("images/middle.gif",
"a pretty but meaningless splat");
label1 = new JButton("Image and Text", icon);
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
您对
JButton
使用了错误的构造函数。那一个只设置了标题
使用允许您设置文本和图标的构造函数
ImageIcon icon = createImageIcon("images/middle.gif",
"a pretty but meaningless splat");
label1 = new JButton("Image and Text", icon);
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
谢谢你的回答!在Image-Icon方法中,您将文件名放在哪里?代码从classpath加载资源,因此将其放在那里(基本上,您需要在images目录中有middle.gif)。您也可以从文件系统加载它,例如
新文件(“c:/img/img1.gif”).toUri().toul()
。谢谢您的回答!在Image-Icon方法中,您将文件名放在哪里?代码从classpath加载资源,因此将其放在那里(基本上,您需要在images目录中有middle.gif)。您也可以从文件系统加载它,例如新文件(“c:/img/img1.gif”).toUri().tour()
。