[英]How to change the color of a specific JButton
如果您只有一个按钮,我非常了解如何执行此操作,但是对于计算机科学项目,我正在制作Keno游戏GUI。 为了制作JButton,我做了一个for循环,如下所示:
for(int i=1 ; i <= 80; i++)
{
num.add(1) ;
btn = new JButton(String.valueOf(i)) ;
btn.setBackground(Color.BLUE);
btn.setForeground(Color.YELLOW);
btn.setActionCommand(String.valueOf(i));
btn.addActionListener(new ButtonHandler());
panel.add(btn);
}
public class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
//Button Code if I click one button it goes here. I have set ID's via ActionCommand
}
}
https://i.gyazo.com/637f74422de5f4bf6e52155dcdfbd482.png [JButton输出]
所以我想做的是,当我单击一个特定的数字时,它变成红色,表示它已被单击。 为此,是否需要定义每个按钮? 或者我可以通过这种方式仅调整一个按钮! 任何信息将不胜感激!
如果您希望它在单击后变为红色(并保持红色),则可以将其添加到ButtonHandler中。
public class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
JButton b = (JButton)event.getSource();
b.setBackground(Color.RED);
}
//Button Code if I click one button it goes here. I have set ID's via ActionCommand
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.