单击时使JButton交替显示颜色

时间:2015-11-29 23:14:29

标签: java swing user-interface

所以我想要一个JButton在点击时在两种颜色之间交替。所以说它原本是黄色的。单击它时会变为红色,再次单击它时,它会变回黄色,然后单击=红色,依此类推。

请在此块之间填写我的代码: 假设JButton变量是btn并使用Color.RED和Color.YELLOW

        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
             ...
            }
        }

2 个答案:

答案 0 :(得分:0)

试试这个:

    btnSearch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){

                //create pressed as a global boolean
                if(pressed){

                        buttonExample.setBackground(Color.yellow); 
                        pressed = false;

                }else{

                        buttonExample.setBackground(Color.red);
                        pressed = true;
                }
        }
    }

不是100%确定这是否可行,如果没有,则从侦听器类创建一个函数(在您的用户界面类中)并添加完全相同的代码,然后从侦听器调用该函数。

更新:更改了错误的来电:

JButton.setBackground(Color.yellow);
JButton.setBackground(COlor.red);

于:     buttonExample.setBackground(Color.yellow);     buttonExample.setBackground(Color.red);

答案 1 :(得分:0)

我讨厌直接回答。然而,这是一个例子,如果你真的再考虑一下,它将引导你找到你的解决方案:

btnSearch.addActionListener(new ActionListener() {
    @Override public void actionPerformed(ActionEvent e){
        btnSearch.setText(btnSearch.getText() + "!");
    }
}

上面的示例将在您点击时附加!来更新按钮上的文字。

您的工作是弄清楚如何确定按钮的现有状态,并相应地设置新的背景。