首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >单击JButton时出现特定颜色时的JAVA增量计数器

单击JButton时出现特定颜色时的JAVA增量计数器
EN

Stack Overflow用户
提问于 2018-10-14 04:32:17
回答 1查看 234关注 0票数 0

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

代码语言:javascript
复制
        //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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-14 04:44:50

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52797055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档