JAVA点击JButton出现特定颜色时增加计数器

JAVA Increment Counter When A Specific Color Appears When Clicking JButton

我正在制作一个程序,用户可以在其中单击默认背景颜色为蓝色的 JButton。每次用户单击 JButton 时,背景都会随机循环显示颜色数组。每次背景为红色时,JLabel 都会打印出一个递增的计数器。 我可以让 JButton 在颜色数组中随机循环。当第一个 RED 出现时,计数器递增 1。但是每次出现 RED 时,计数器都不会递增。我无法让计数器在初始计数后继续递增。 这是按钮的代码:

        //label for counter
        JLabel lblRedCounter = new JLabel("Red Counter: 00");
        lblRedCounter.setBorder(new EmptyBorder(31, 3, 31, 3));
        lblRedCounter.setFont(new Font("Tahoma", Font.PLAIN, 30));
        lblRedCounter.setOpaque(true);
        lblRedCounter.setBackground(Color.LIGHT_GRAY);
        panel.add(lblRedCounter);

        //button to change background and initiate counter
        JButton btnClickMe = new JButton("Click Me");
        btnClickMe.setFocusable(false);
        btnClickMe.setBorder(new EmptyBorder(33, 47, 33, 47));
        btnClickMe.setFont(new Font("Tahoma", Font.PLAIN, 30));
        btnClickMe.setBackground(Color.BLUE);
        btnClickMe.setForeground(Color.WHITE);
        btnClickMe.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) 
            {               
                //create arraylist of colors
                colors = new ArrayList<>();
                colors.add(Color.BLUE);
                colors.add(Color.RED);
                colors.add(Color.GREEN);
                colors.add(Color.ORANGE);
                colors.add(Color.MAGENTA);

                //creates random object
                Random rand = new Random();
                //random object cycles through 5 places to match array length
                int num = rand.nextInt(5);

                //cycles randomly through array of colors
                btnClickMe.setBackground(colors.get(num));

                //default for counter to be used when RED is background
                int counter = 0;
                /**
                 * This only seems to cycle once
                 * Checks if background is RED, increments counter
                 * Changes output of JLabel lblRedCounter
                 */
                if (btnClickMe.getBackground() == Color.RED)
                {
                    counter++;
                    lblRedCounter.setText("Red Counter: " + counter);
                }
            }
        });
        panel.add(btnClickMe);

您需要将 int 变量移到 actionPerfomed 方法之外,并将其设为实例变量(或静态变量,尽管通常不推荐这样做)。现在,每次调用 actionPerformed 时,您都会用 0 初始化一个新变量。