所以我有一个名为 Safe25 的 GUI 程序。基本上,如果您按正确的顺序按下按钮,即“15032018”,程序将自行关闭。
如果您输入正确的数字,假设您在开始时按 1,按钮应将其背景颜色更改为绿色,例如this:
如果按错按钮,按钮的颜色应更改为红色。
但我的代码逻辑与我的问题无关。
正如我所说,我想更改按钮背景颜色,如链接图像中所示。我的问题是它改变了框架的背景颜色,就像this
重要的一行是75,我评论了这一行。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Safe25 extends Frame implements ActionListener {
JButton[] buttons;
Safe25() { // Konstruktor
setSize(250, 300);
setLocation(300, 300);
setTitle("Safe25");
buttons = new JButton[10];
for (int i = 0; i < 10; i++) { // 10 Knöpfe im Array
buttons[i] = new JButton("" + i);
buttons[i].setFont(new Font("Courier", Font.BOLD, 34));
buttons[i].addActionListener(this); //
}
Panel panel0 = new Panel();
panel0.setLayout(new GridLayout(1, 1));
panel0.add(buttons[0]);
Panel panelRest = new Panel();
panelRest.setLayout(new GridLayout(3, 3));
setLayout(new GridLayout(2, 1));
for (int i = 1; i < 10; i++) {
panelRest.add(buttons[i]);
}
add(panel0); // Panel mit 0-Knopf
add(panelRest);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent wv) {
System.exit(0);
}
});
setVisible(true);
}
int s = 0;
public void actionPerformed(ActionEvent evt) {
// 0 1 2 3 4 5 6 7 8 Zustände ...
// 1-5-0-3-2-0-1-8 ist richtige Kombination
switch (Integer.parseInt(evt.getActionCommand())) {
case 0:
s = (s == 2 || s == 5) ? s + 1 : 0;
break;
case 1:
s = (s == 0 || s == 6) ? s + 1 : 1;
break;
case 2:
s = (s == 4) ? s + 1 : 0;
break;
case 3:
s = (s == 3) ? s + 1 : 0;
break;
case 5:
s = (s == 1) ? s + 1 : s == 7 ? 2 : 0;
break;
case 8:
s = (s == 7) ? s + 1 : 0;
break;
default:
s = 0;
}
Color col;
if (s == 0) {
col = Color.red;
} else { // richtiger Weg
col = Color.green;
}
if (s == 8) {
System.exit(0);
}
for (Component c : getComponents()) // line 75, i want this one
c.setBackground(col); // to change the buttons backgroundcolor
repaint(); // but it changes the frames backgroundcolor instead
}
public static void main(String[] args) {
Safe25 we = new Safe25();
}
}
你红色了吗javadoc对于 JButton?
edit:
抱歉,我很快就查看了您的代码。您现在要做的就是设置当前容器中每个组件的背景颜色。
虽然您的按钮数组是全局的,但您可以简单地再次循环该集合以获取正确的组件“按钮”并设置背景颜色,如下所示:
for (JButton b : buttons) // line 75, i want this one
b.setBackground(col); // to change the buttons backgroundcolor
repaint(); // but it changes the frames backgroundcolor instead
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)