如何防止JButton在禁用时变灰?

3

我需要编写一款纸牌游戏。当点击一张纸牌时,会随机生成一张纸牌图片。但由于每张纸牌只能点击一次,所以在点击后按钮会被设置为不可用。如何防止纸牌图片在被点击后变灰,以便新生成的纸牌图片清晰可见?

//Actions performed when an event occurs
public void actionPerformed(ActionEvent e)
{

    if (e.getSource() == card1)
    {
    randomInteger();
    card1.setIcon(cardImages[randomInt]);
    card1.setEnabled(false);

    }
    else if (e.getSource() == card2)
    {
    randomInteger();
    card2.setIcon(cardImages[randomInt]);
    card2.setEnabled(false);
    }
    else if (e.getSource() == card3)
    {
    randomInteger();
    card3.setIcon(cardImages[randomInt]);
    card3.setEnabled(false);
    }
    else if (e.getSource() == card4)
    {
    randomInteger();
    card4.setIcon(cardImages[randomInt]);
    card4.setEnabled(false);
    }
    else
    {
    randomInteger();
    card5.setIcon(cardImages[randomInt]);
    card5.setEnabled(false);
    }

}

}

也许我没有完全理解你想做什么,但我认为最好使用JToggleButton来完成你的任务。 - Aliaksei Bulhak
我们需要使用一个简单的JButton,它将具有预设的卡片背景图像,然后当您点击卡片时,一个方法将生成一个随机的卡片,如国王、皇后,但一旦卡片被点击,按钮就会被禁用,因此生成的图像会变暗。我该如何阻止这种情况发生? - user1823262
2
我认为你不能这样做。所以我建议使用切换按钮,并编写监听器来检查按钮位置。 - Aliaksei Bulhak
显然,我可以在用户单击重置时删除操作监听器,然后重新应用它,但对我来说似乎没有起作用。 - user1823262
我认为从按钮中删除actionListener不是一个好主意。 - Aliaksei Bulhak
显示剩余3条评论
1个回答

14

您只需将按钮的禁用图标设置为与按钮图标相同的值即可。参见此示例:

左侧是我已经设置了图标和禁用图标的按钮。右侧我只设置了图标:

示例

import java.awt.BorderLayout;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TestDisabledButtons {

    public static final String CARD_URL = "http://assets0.wordansassets.com/wvc-1345850020/wordansfiles/images/2012/8/24/156256/156256_340.jpg";

    protected void createAndShowGUI() throws MalformedURLException {
        JFrame frame = new JFrame("Test button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ImageIcon imageIcon = new ImageIcon(new URL(CARD_URL));
        JButton button = new JButton(imageIcon);
        JButton button2 = new JButton(imageIcon);
        button.setDisabledIcon(imageIcon);
        button.setEnabled(false);
        button2.setEnabled(false);
        frame.add(button, BorderLayout.WEST);
        frame.add(button2, BorderLayout.EAST);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new TestDisabledButtons().createAndShowGUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

}

1
肯定是加1;但有没有人知道如何防止JButton上的标准文本变灰? - aaiezza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接