所以这个程序的目的是创建一个椭圆和一个按钮,当你点击它时,椭圆会改变颜色。颜色的顺序应该是红色,然后是绿色,然后是蓝色。我该如何创建这个循环?我是否使用for循环?这是我没有循环的代码:
public class ButtonButton implements java.awt.event.ActionListener{
private NscWindow win;
private NscEllipse oval;
public ButtonButton() {
win = new NscWindow();
win.setTitle("ButtonButton");
oval = new NscEllipse(100, 70, 200, 150);
oval.setFilled(true);
oval.setBackground(java.awt.Color.blue);
javax.swing.JButton btn;
btn = new javax.swing.JButton("click me");
win.add(oval);
btn.setSize(170, 35);
btn.setLocation(110, 10);
win.add(btn);
win.repaint();
btn.addActionListener(this);
}
public void actionPerformed(java.awt.event.ActionEvent e) {
win.setTitle("Thanks, I needed that");
javax.swing.JButton btn;
btn = (javax.swing.JButton)e.getSource();
btn.setText("Thanks, I needed that");
oval.setBackground(java.awt.Color.green);
win.repaint();
}
public static void main(String[] args) {
new ButtonButton();
}
}
答案 0 :(得分:2)
为了循环每个,做这样的事情:
public void actionPerformed(java.awt.event.ActionEvent e) {
win.setTitle("Thanks, I needed that");
javax.swing.JButton btn;
btn = (javax.swing.JButton)e.getSource();
btn.setText("Thanks, I needed that");
if (oval.getBackground().equals(java.awt.Color.red))
oval.setBackground(java.awt.Color.green);
else if (oval.getBackground().equals(java.awt.Color.green))
oval.setBackground(java.awt.Color.blue);
else if (oval.getBackground().equals(java.awt.Color.blue))
oval.setBackground(java.awt.Color.red);
win.repaint();
}
答案 1 :(得分:1)
首先创建一个颜色数组......
public static final Color COLORS[] = new Color[]{Color.RED, Color.GREEN, Color.BLUE};
提供某种价值来追踪你最喜欢的颜色......
private int colorIndex = -1;
添加一种方便的方法来改变颜色......
public void applyNextColor() {
colorIndex++;
if (colorIndex >= COLORS.length) {
colorIndex = 0;
}
oval.setBackground(COLORS[colorIndex]);
}
然后在构造函数中初始化初始颜色......
public ButtonButton() {
win = new NscWindow();
win.setTitle("ButtonButton");
oval = new NscEllipse(100, 70, 200, 150);
oval.setFilled(true);
nextColor();
//...
}
然后在你的动作监听器中,只需应用下一个颜色......
public void actionPerformed(java.awt.event.ActionEvent e) {
win.setTitle("Thanks, I needed that");
// This is a NullPointerException waiting to happen...
//javax.swing.JButton btn;
btn = (javax.swing.JButton)e.getSource();
btn.setText("Thanks, I needed that");
applyNextColor();
win.repaint();
}
您可以使用enum
和/或模块化数学执行相同的操作,但这样可以保持简单;)