JButton按下时会改变颜色

时间:2018-04-18 14:36:51

标签: java colors click jbutton actionlistener

我一直得到同样的错误:“cBtn无法解析为变量”

    public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Butt1");
        JButton btn = new JButton("Change color");
        frame.add(btn);
        btn.setBackground(cBtn);
        frame.setSize(250, 100);
        frame.setVisible(true);
    }
    Color[] colors = new Color[] { Color.red, Color.orange, Color.yellow, Color.green, Color.blue,
            new Color(075, 000, 130), new Color(128, 000, 128)};
    int color;
    public void actionPerformed(ActionEvent e) {
        Color cBtn = (colors[color++ % colors.length]);
    }
}

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果您将本地变量cBtn转换为字段,可以在类中的任何位置访问,这应该可以解决问题:(我没有触及其余代码,因为它不是您当前问题的一部分)

 public class Main {
    private Color cBtn;
    public static void main(String[] args) {
        JFrame frame = new JFrame("Butt1");
        JButton btn = new JButton("Change color");
        button.addActionListener(new ActionListener() { 
            @Override 
            public void actionPerformed(ActionEvent e) { 
                cBtn = (colors[color++ % colors.length]); 
            }
        }
        frame.add(btn);
        btn.setBackground(cBtn);
        frame.setSize(250, 100);
        frame.setVisible(true);
    }
    Color[] colors = new Color[] { Color.red, Color.orange, Color.yellow,     Color.green, Color.blue,
            new Color(075, 000, 130), new Color(128, 000, 128)};
    int color;

}

答案 1 :(得分:0)

决定重做它:

public class Main extends JFrame {
        private JButton btn;
        public Main() {
        super("Butt1");
        setLayout(new FlowLayout());

        btn = new JButton("ChangeColor");
        add(btn);
        ServClass serv = new ServClass();
        btn.addActionListener(serv);
    }

    Color[] colors = new Color[] { Color.red, Color.orange, Color.yellow, Color.green, Color.blue,
            new Color(075, 000, 130), new Color(128, 000, 128) };
    int color, click1 = 0;

    private class ServClass implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            btn.setBackground(colors[color++ % colors.length]);
        }
    }

    public static void main(String[] args) {
        Main run = new Main();
        run.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        run.setSize(250, 100);
        run.setVisible(true);
    }
}

主要根据本教程: https://www.youtube.com/watch?v=3RQOikbGGUM

thx HBo for Y / help!