2016-11-09 63 views
0

我很难搞清楚如何在Java上编写这个简单的老虎机,第一个应该是最容易解决的问题是把3个.png图像放到JButton上我在eclipse上运行程序。所有文件也都在源文件夹中。如何把图像放到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); 

回答

2

你使用错误的构造函数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; 
    } 
} 
+0

感谢您的回答!你会把文件名放在Image Icon方法中? – Cactus

+0

代码从_classpath_加载资源,所以放在那里(基本上你需要在images目录中有middle.gif)。您也可以从文件系统加载它,例如'new File(“c:/img/img1.gif”)。toUri()。toUrl()'。 –

+0

也许,如果答案适合你,你能否将其标记为已接受? –