java 如何更改 JButton 的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/632376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:08:42  来源:igfitidea点击:

How to change the image of a JButton?

javaswingjbutton

提问by user69514

I'm working on a memory game program. I have 30 JButtons on a JPanel. When the user is clicking and finds a match (meaning two buttons with the same image) I want to change the image on the JButton to a different image. However this does not happen while the program is running.

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

How can I do this?

我怎样才能做到这一点?

I was doing this:

我是这样做的:

cards[i].setIcon(cardBack);

where cardBack is an ImageIcon that I already have.

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

回答by Ahmad Vatani

you can use this code:

您可以使用此代码:

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

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

and copy your image (image.jpg) to your project folder!

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

回答by Bluedevil678

Use a JToggleButton. More specifically, use the setIcon and setSelectedIcon methods. Using this approach, you'll avoid reinventing the wheel.

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

Example:

例子:

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);
 }
}