本文介绍了设置和禁用 JToggleButton 的图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个匹配的记忆游戏,我使用 JToggleButton.最重要的是,当我按下按钮时,它必须显示一张图片,我必须找到另一张相同的图片.所以问题是当我创建一个没有任何图标的按钮时,我不能使用其他其他方法,例如 .setRollOverIcon()
、.setPressedIcon()
等,所以我很感激你可以帮我 .无论如何,谢谢:)
hi there i am trying to make a matching memory game which i use JToggleButton. the main thing is when i press to button it must show a picture and i must find the other same picture. so the problem is when i create a button without any icons i cant use other other methods for example .setRollOverIcon()
, .setPressedIcon()
etc. so i appreciated if you can help me . and thanks anyway :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsIcon extends JFrame {
private static final long serialVersionUID = 1L;
private ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
private ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
private ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
setLayout(new GridLayout(1, 1, 4, 4));
final JToggleButton toggleButton = new JToggleButton();
//toggleButton.setIcon((errorIcon));
toggleButton.setRolloverIcon((infoIcon));
toggleButton.setPressedIcon(warnIcon);
toggleButton.setDisabledIcon(warnIcon);
toggleButton.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton.isSelected()) {
} else {
}
}
});
add(toggleButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
推荐答案
一种方法是执行以下操作:
One approach is to do the following:
- 使用选中状态指示是显示还是隐藏
图标
. - 使用启用状态来指示已匹配一对.
代码大纲:
/** Handle ItemEvents. */
@Override
public void itemStateChanged(ItemEvent e) {
GameButton gb = (GameButton) e.getItem();
gb.setState();
}
/** Remove a and b from play. */
private void retirePair(GameButton a, GameButton b) {
a.setSelected(true);
a.setEnabled(false);
b.setSelected(true);
b.setEnabled(false);
}
class GameButton extends JToggleButton {
...
public void setState() {
if (this.isSelected() || !this.isEnabled()) {
this.setIcon(icon);
} else {
this.setIcon(hidden);
}
}
}
这篇关于设置和禁用 JToggleButton 的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!