gpt4 book ai didi

java - 如何将图像放到 Jbutton 上

转载 作者:行者123 更新时间:2023-12-02 03:14:26 25 4
gpt4 key购买 nike

我在弄清楚如何在 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 = 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;
}
}

关于java - 如何将图像放到 Jbutton 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com