0

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

我怎样才能做到这一点?

我正在这样做:

cards[i].setIcon(cardBack);

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

4

2 回答 2

6

您可以使用以下代码:

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

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

于 2014-08-11T07:59:04.767 回答
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);
 }
}
于 2014-03-08T15:43:40.173 回答