单击按钮时,我希望按钮背景更改

时间:2013-06-28 11:27:57

标签: java swing jframe jbutton

所以当我点击JFrame上的按钮时,我希望按钮只要点击它就可以改变它的背景。有人可以帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

单击按钮时,我希望按钮背景更改

按下按钮前:

enter image description here

按下按钮后:

enter image description here

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        createAndShowJFrame();
    }

    public static void createAndShowJFrame() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                JFrame frame = createJFrame();
                frame.setVisible(true);

            }
        });
    }

    private static JFrame createJFrame() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        ActionListener al = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {

                JButton btn = ((JButton) ae.getSource());//get the button that was clicked

                //set its background and foreground
                btn.setBackground(Color.RED);
                btn.setForeground(Color.GREEN);
            }
        };

        JButton b = new JButton("Test");
        b.addActionListener(al);

        frame.add(b);

        frame.pack();

        return frame;
    }
}

答案 1 :(得分:2)

您可以通过多种方式实现这一目标。以下是为所有按钮应用按钮选择颜色的示例代码段。

UIManager.put("Button.select", new ColorUIResource(255, 0, 0));
JButton button = new JButton("Submit");
JFrame frame = new JFrame("JButton select color");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 80);
frame.setVisible(true);

答案 2 :(得分:2)

JToggleButton可能是理想的,如Swing JToolbarButton pressing 所示。请注意,您需要添加一些代码以确保按钮只能被点击一次。

或者,您可以使用标准JButton并致电AbstractButton.setDisabledIcon(Icon). 点击时停用该按钮,它将翻转到备用图标。

相关问题