Java:颜色数组不会循环遍历

标签 java arrays swing for-loop actionevent

我试图让容器显示数组中的每种颜色。它可以编译,但只会显示我所假设的青色。我认为我的 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);
     }
  }

最佳答案

Swing 是单线程环境,这意味着任何阻止或停止该线程执行的操作都将阻止它处理事件队列中的新事件,包括重绘请求。

Swing (在大多数情况下)也不是线程安全的,这意味着尝试从事件调度线程外部更新任何 UI 组件的状态都是不安全的。

您代码中的问题就在这里......

public void actionPerformed(ActionEvent event) {
    for(i=0; i < colors.length; i++) {
        con.setBackground(colors[i]);
    }
}

这意味着仅显示最后一种颜色。

在这种情况下,我建议使用 Swing Timer,它允许您定期安排回调,该回调将在事件调度线程的上下文中执行

看看Concurrency in SwingHow to use Swing Timers了解更多详情

已更新示例

Colors

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Four extends JFrame {

    public static void main(String[] args) {
        new Four();
    }

    public Four() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new FourPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class FourPane extends JPanel {

        Color colors[] = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
            Color.CYAN};
        int i;
        private JButton button = new JButton("Press Me");
        private Timer timer;

        public FourPane() {

            add(button);
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (!timer.isRunning()) {
                        timer.start();
                    }
                }
            });

            timer = new Timer(500, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (i < colors.length) {
                        setBackground(colors[i]);
                    } else {
                        ((Timer) e.getSource()).stop();
                    }
                    i++;
                }
            });

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(180, 180);
        }
    }
}

关于Java:颜色数组不会循环遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25111632/

相关文章:

java - 查找 Maven 插件中主要 Artifact 的路径

java - 如何为线程run方法编写junit测试用例

c - C 中的数组、字符串、指针操作

mysql - 将 MySQL JSON 列数组读取为行

java - 我怎样才能提高 Java 中这个 n 次根算法的精度?

java - 是否可以通过代理使用 Spring Cloud Azure Stream Binder?

java - 如何检查数组是否已经排序

java - 将 ScrollPane 添加到 JTextArea

java - 我们可以在面板内添加面板来创建嵌套选项卡式菜单吗?

java - 如何检测 JComboBox 是否为空?