So I'm writing a program in which I would eventually like a JButton to change color when pressed. So far, here is my dilemma:
-I cannot get the JButton I currently have set up to show the background color, despite toggling the true/false of setOpaque() and setContentAreaFilled(). I would like to be able to do this before even attempting to add an ActionListener.
-I would like to use something similar to JToggleButton() to change the color, however I would like to do this with just a background instead of an icon.
I am using a mac, and I'm wondering if it has something to do with the default button settings, but I don't know how to change/override these.
I would post a screenshot, but unfortunately my reputation isn't high enough yet.
Here is an example of what I am getting:
import java.awt.*;
import javax.swing.*;
public class Example extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame main = new JFrame("Example");
JPanel content = new JPanel();
JButton button = new JButton("Press");
button.setBackground(Color.orange);
button.setContentAreaFilled(false);
button.setOpaque(true);
content.add(button);
main.setContentPane(content);
main.setVisible(true);
main.setSize(40,60);
main.setLocation(500, 200);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For those (maybe on a windows or linux platform) who can't see what I'm talking about, the button appears and the layout behind the button (not the border or the JPanel, just a small rectangle around the button) is colored to what was specified.
Thank you in advance for your time.
Also, I know that inside the ActionListener the getSource() method will return the text associated with the button. Is there any way to use something similar to change the color of the button from inside the ActionListener or is this idea just a redundancy for something that can be done in a much simpler fashion.
Much appreciated.