如何更改JButton的图像?

时间:2009-03-10 21:33:27

标签: java swing jbutton

我正在开发一个记忆游戏程序。我在JPanel上有30个JButton。当用户点击并找到匹配项(意味着具有相同图像的两个按钮)时,我想将JButton上的图像更改为其他图像。但是,在程序运行时不会发生这种情况。

我该怎么做?

我这样做:

cards[i].setIcon(cardBack);

其中cardBack是我已经拥有的ImageIcon。

2 个答案:

答案 0 :(得分:5)

您可以使用此代码:

Icon i=new ImageIcon("image.jpg"); jButton1.setIcon(i);

将图像(image.jpg)复制到项目文件夹中!

答案 1 :(得分:1)

使用JToggleButton。更具体地说,使用setIcon和setSelectedIcon方法。使用这种方法,你将避免重新发明轮子。

示例:

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

final class JToggleButtonDemo {
    public static final void main(final String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
            createAndShowGUI();
        }
    });
}
private static final void createAndShowGUI(){
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new FlowLayout()); // For presentation purposes only.
    final JToggleButton button = new JToggleButton(UIManager.getIcon("OptionPane.informationIcon"));
    button.setSelectedIcon(UIManager.getIcon("OptionPane.errorIcon"));
    frame.add(button);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
 }
}
相关问题