gpt4 book ai didi

java - JButton 的图标没有改变(UNO 纸牌游戏)

转载 作者:行者123 更新时间:2023-12-01 13:52:14 26 4
gpt4 key购买 nike

我正在使用套接字和其他东西来实现 UNO 游戏。到目前为止,我一直在为每个客户端开发 GUI,当我为每个玩家获取一组随机卡牌和一张随机中央卡牌时,我已经成功,但陷入了以下困境:我使用一个按钮来代表手上的每张牌,假设我想选择一张红牌(因为中央牌也是红色的)我已经完成了所有允许您放置或不放置牌的验证方法。但中央按钮的图标没有改变(中央卡片变量改变,但代表它的按钮图标不变)。

我读了这个问题并尝试使用 SwingUtilities.invokeLater 但图标没有改变( Dynamically change jButton icon )。

这是我更改 JButton 图标的代码:

public void setBtnIcon( final javax.swing.JButton btn,  final modelo.Card c) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
btn.updateUI();
Color color = c.getColor();
btn.setBackground(color);
if (c instanceof modelo.NumberCard) {
short value = ((modelo.NumberCard) c).getValue();


String str = Short.toString(value);
btn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jugadoruno/vista/" + str + ".png")));

} else if (c instanceof modelo.ActionCard) {
modelo.ActionType t = ((modelo.ActionCard) c).getActionType();
String str = t.toString();

btn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jugadoruno/vista/" + str + ".png")));

}

}
});
}

它接收一张卡片(以获取其颜色、值/actionType),将 JButton 的背景更改为相同的颜色,并搜索正确的图标(如果卡片是红色且值为 1,它将更改按钮的背景)背景为红色并搜索1.png,这是一个带有数字1的透明图像)

如果有更好的方法来做到这一点,我会很高兴知道。现在它只是在执行开始时设置图标。感谢您的宝贵时间!

GUI

最佳答案

需要检查两件事:

  1. 确保您在某种事件监听器内调用 setBtnIcon,以便它在您需要时触发。从您最初的问题中我无法判断“它只是在执行开始时设置图标”是否意味着该方法仅被调用一次。
  2. 使用调试器运行代码(或添加一两个打印语句),以确保 getClass().getResource(...) 的结果不为 null 。获取位于同一位置的资源可能是一件棘手的事情,尤其是当您在 JAR 文件中分发应用时。

关于java - JButton 的图标没有改变(UNO 纸牌游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19880155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com