【问题标题】:JAVA Increment Counter When A Specific Color Appears When Clicking JButton单击JButton时出现特定颜色时的JAVA增量计数器
【发布时间】:2018-10-13 20:32:16
【问题描述】:

我正在制作一个程序,用户单击具有默认背景颜色蓝色的 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);

【问题讨论】:

    标签: java arrays swing counter jbutton


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多