-2

So I when I click on a button on my JFrame, I want the button to change it's background as long as it clicked. Can someone please help?

Thanks!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
WhiplashOne
  • 321
  • 1
  • 4
  • 11

2 Answers2

2

When button is clicked, I want the button background to change

Before button is pressed:

enter image description here

after button is pressed:

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;
    }
}
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • @WhiplashOne see [JButton.getModel.addChangeListener](http://stackoverflow.com/a/5755124/714968), or the same method is implemented in JButton API, isPressed – mKorbel Jun 28 '13 at 12:28
2

You can achieve this by multiple ways. The following is the sample snippet for apply a button select color for all buttons.

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);
vels4j
  • 11,208
  • 5
  • 38
  • 63
  • 1) Swing components should be created and manipulated on EDT. 2) calling `setSize` of `JFrame` is not recommended practice, use `LayoutManager` instead and call `pack()` in place of `setSize`. 3) Rather `JFrame.DISPOSE_ON_CLOSE` or it will completely exit the app regardless of other windows or threads open. 4) OP does not say for all buttons (but of course he/she might have just ommitted that) – David Kroukamp Jun 28 '13 at 11:47
  • +1 though as Im not sure if OP wants button to change after click, or only while button is held down – David Kroukamp Jun 28 '13 at 12:18