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!
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!
When button is clicked, I want the button background to change
Before button is pressed:
after button is pressed:
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;
}
}
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);