将图像添加到JButton
我想将图像添加到JButton
。 按钮的背景设置为黑色。 我试图在它上面添加图像,但没有显示任何内容。 背景颜色为黑色但图像缺失。
码
public class Test extends JFrame { JButton b; JPanel p; Test() { p = new JPanel(new BorderLayout()); b = new JButton(); b.setBackground(Color.black); ImageIcon img = new ImageIcon("C:\\Users\\Aksi\\Documents\\NetBeansProjects\\test'\\src\\test\\Black_B.ico"); b.setIcon(img); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(400, 400); p.add(b); add(p); validate(); } public static void main(String args[]) throws IOException { Test ob = new Test(); ob.setVisible(true); } }
两件事情
- 路径看起来不对
- Java本身并不支持
ico
格式
看看路径,路径中有引号
C:\\Users\\Aksi\\Documents\\NetBeansProjects\\test'\\src\\test\\Black_B.ico
只要确定它是否存在
请注意,您应该使用一些Java支持的图像格式,例如.gif,.png。
这是我用文字添加图片的方式:
Icon a=new ImageIcon(getClass().getResource("a.png")); buttonname=new JButton("ButtonTittle",a);