我试图让容器显示我的数组中的每种颜色。它会编译,但是只会显示我假设的Cyan。我以为我的for循环将使用ActionEvent / Listener遍历数组中的所有颜色。看到我做错了吗?谢谢。
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Four extends JFrame implements ActionListener {
private final int SIZE = 180;
Color colors[] = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
Color.CYAN};
int i;
private Container con = getContentPane();
private JButton button = new JButton("Press Me");
public Four()
{
super("Frame");
setSize(SIZE, SIZE);
con.setLayout(new FlowLayout());
con.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
for(i=0; i < colors.length; i++) {
con.setBackground(colors[i]);
}
}
public static void main(String[] args) {
Four frame = new Four();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
最佳答案
您将i重新初始化为0,然后每次在actionPerformed中通过循环到colors.length进行操作,因此得到最后一项。像这样使用sth:
public class Four extends JFrame implements ActionListener {
private final int SIZE = 180;
Color colors[] = {Color.RED, Color.ORANGE, Color.YELLOW,
Color.GREEN, Color.BLUE, Color.CYAN};
int i = 0;
private Container con = getContentPane();
private JButton button = new JButton("Press Me");
public Four() {
super("Frame");
setSize(SIZE, SIZE);
con.setLayout(new FlowLayout());
con.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
con.setBackground(colors[i++ % colors.length]);
}
public static void main(String[] args) {
Four frame = new Four();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}