问候,
到目前为止,我的代码已编译,但它从白色变为黑色,然后不想更改。 假设它应该从红色->橙色->绿色->粉色->蓝色->黑色改变..
public void init() {
c=new Color[] {Color.red, Color.orange, Color.green,
Color.pink, Color.blue, Color.black };
btnNext = new Button("Next Color");
btnNext.addActionListener(this);
setLayout(new BorderLayout());
add(btnNext, BorderLayout.SOUTH);
}
public void paint(Graphics g) { }
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnNext) {
for(int n=0;n<6;n++) {
setBackground(c[n]);
}
repaint();
}
}
感谢您的帮助。
最佳答案
您需要做的是保留数组中当前位置的 int
成员变量。然后每次单击按钮时都会增加该位置。
// New int keeping track of background pos
private int arrPos;
public void init() {
c=new Color[] {Color.red, Color.orange, Color.green,
Color.pink, Color.blue, Color.black };
// initialize the int
arrPos = 0;
btnNext = new Button("Next Color");
btnNext.addActionListener(this);
setLayout(new BorderLayout());
add(btnNext, BorderLayout.SOUTH);
}
public void paint(Graphics g) { }
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnNext) {
// increment the background
arrPos++;
if (arrPos >= c.length) arrPos = 0;
setBackground(c[arrPos]);
repaint();
}
}
关于java - 如何更改 Java 小程序的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1154003/