Background color wont be applied to JButton - java

I have a simple program with a jcolorchooser some textfields and a button.
When i press the button the jcolorchooser appears and then i select a color.
Now lets say i want to take the background color i choosed and apply it to my button like this:
public class Slide extends JFrame{
Color bgColor;
JButton colorButton=new JButton();
JColorChooser colorPicker=new JColorChooser();
public Slide(){
JPanel panel=new JPanel();
panel.setLayout(new MigLayout("", "[][][][][]", "[][][][][][]"));
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JColorChooser.showDialog(null, "title", null);
bgColor=colorPicker.getBackground();
colorButton.setBackground(bgColor);
}
});
colorButton.setText("Pick a color");
panel.add(colorButton, "cell 0 5");
this.setSize(400, 400);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String args[]){
new Slide();
}
}
The problem is that my bgcolor won't be applied to my colorButton.Any ideas?

The color the user has selected from the JColorChooser dialog is returned to you as the return value of the showDialog() method.
To update the JButton with the selected color from the dialog, you should change your code to:
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color color = JColorChooser.showDialog(null, "title", null);
if (color != null) {
colorButton.setBackground(color);
}
}
});
Note that the method showDialog() will return null if the user has canceled, that's why we need to check it's value before assigning the color.
The method getBackground() is a method from the Component class, so the previous code bgColor=colorPicker.getBackground() was simply returning the actual colour of the JColorChooser dialog component.

Related

JButtons MouseEvents

I want my buttons to change color when mouse is on them (hover), when they are pressed (active) and stay this way until user will choose other options. So one of them will be always choosen.
I have three buttons - with cricle, square and traingle. My code:
private static MouseListener ButtonMouseListener = new MouseAdapter () {
public void mouseEntered(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(91, 90, 90));
}
public void mouseExited(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(64, 64, 64));
}
public void mousePressed(MouseEvent evt) {
Component source = evt.getComponent();
source.setBackground(new Color(46, 46, 46));
}
};
So I want buttons to change color when hovering over them (mouseEntered), and again change color to default when someone stops hovering (that's why I have mouseExited). The next thing is that I want them to change color when they are choosen, so mousePressed . The problem is that when I move the cursor outside the button it changes to another color because of mouseExited and I don't want that. It has to stay the 'pressed color' until user chooses another of three buttons. I have no idea how to achieve that, I tried different options but nothing works the way I want.
For entry color change you need to implement the Event->Mouse->mouseEntered. Make sure you are implementing it on mouseExited
On mouse pressed color change you need to implement Event->Action. Inside actionPerformed, you can set the button color. For example :
jButton7.setBackground(new Color(11, 118, 219));
jButton1.setBackground(new Color(15,44,123));
jButton8.setBackground(new Color(15,44,123));
jButton9.setBackground(new Color(15,44,123));
You can use JToggleButton instead of JButton since they have their own UI property for selection (pressed) background. You can override it like this:
UIManager.put("ToggleButton.select", Color.GREEN);
An SSCCE of what I would do:
public class ToggleButtonsExample extends JFrame {
private static final Color PRESSED_COLOR = Color.BLUE;
private static final Color HOVER_COLOR = Color.RED;
public ToggleButtonsExample() {
super("Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
JToggleButton button1 = new JToggleButton("button1");
JToggleButton button2 = new JToggleButton("button2");
JToggleButton button3 = new JToggleButton("button3");
final Color defaultBackgroundColor = button1.getBackground();
MouseListener hoverColorMouseListener = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
component.setBackground(HOVER_COLOR);
}
#Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
component.setBackground(defaultBackgroundColor);
}
};
List<AbstractButton> buttons = Arrays.asList(button1, button2, button3);
buttons.forEach(this::add);
buttons.forEach(b -> b.addMouseListener(hoverColorMouseListener));
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
UIManager.put("ToggleButton.select", PRESSED_COLOR);
new ToggleButtonsExample().setVisible(true);
});
}
}
And a preview image:

Change JButton background color when mouse on it (not rollover)

I created a JFrame with 5 buttons, 1 of them is a play button which user could press to play an audio file, the rest of them are the choices which user are required to choose the correct one after listening to the audio.
I want the buttons to change color when the mouse is over them.
I disabled the choice buttons then play the audio file, used SwingWorker to wait until the audio file is finished then enable the buttons again.
Firstly I used ButtonModel and changeListener to set background color. Of course they worked well when mouse rollover them after the audio clip finished playing.
But I found a problem is that, if i moved my mouse to the button while the audio was playing, the button was enabled after the audio finished but it did not change its color.
Appreciate for any help!
TLDR: There are two situations
(1) I pressed the play button, did not move the mouse pointer such that the pointer stay over the play button. AFTER the 4 buttons were enabled, I moved the mouse pointer to any one of them, the changelistener works prefectly.
(2) I pressed the play button, moved the mouse pointer to any one of the 4 buttons BEFORE the 4 buttons were enabled, the color of the buttons did not change after the buttons were enabled.
The complete demo of the JFrame is attached, it could be run perfectly with MigLayout libraries.
public class demo extends JFrame {
private JPanel contentPane, panelBtn, panelWord;
private JButton btnPlay, btnStop, btnWord0, btnWord1, btnWord2, btnWord3;
public static void main (String args[]){
demo testing = new demo();
}
public demo(){
super("Demonstrating problem");
init();
setVisible(true);
}
private void init(){
customizedChangeListener clBtn = new customizedChangeListener();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100, 100, 673, 512);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panelBtn = new JPanel();
panelBtn.setLayout(new MigLayout("", "[grow][]", ""));
contentPane.add(panelBtn, BorderLayout.SOUTH);
panelWord = new JPanel();
panelWord.setLayout(new MigLayout("", "[grow,fill][grow,fill]", "[grow,fill][grow,fill]"));
contentPane.add(panelWord, BorderLayout.CENTER);
btnPlay = new JButton("Play");
btnPlay.addActionListener(new playAcitonListener());
panelBtn.add(btnPlay, "cell 0 0, align center");
btnWord0 = new JButton("A");
btnWord0.addChangeListener(clBtn);
panelWord.add(btnWord0, "cell 0 0");
btnWord1 = new JButton("B");
btnWord1.addChangeListener(clBtn);
panelWord.add(btnWord1, "cell 1 0");
btnWord2 = new JButton("C");
btnWord2.addChangeListener(clBtn);
panelWord.add(btnWord2, "cell 0 1");
btnWord3 = new JButton("D");
btnWord3.addChangeListener(clBtn);
panelWord.add(btnWord3, "cell 1 1");
enableBtn(false);
}
private class customizedChangeListener implements ChangeListener{
JButton rolledBtn;
#Override
public void stateChanged(ChangeEvent e) {
rolledBtn = (JButton)e.getSource();
if (rolledBtn.getModel().isRollover())
rolledBtn.setBackground(Color.green);
else
rolledBtn.setBackground(UIManager.getColor("Button.background"));
}
}
private class playAcitonListener implements ActionListener{
JButton pressedBtn;
#Override
public void actionPerformed(ActionEvent e) {
pressedBtn = (JButton)e.getSource();
if (pressedBtn.equals(btnPlay)){
btnPlay.setEnabled(false);
new SwingWorker<Void ,Void>(){
#Override
protected Void doInBackground() throws Exception {
Thread.sleep(2000);
return null;
}
#Override
protected void done() {
enableBtn(true);
}
}.execute();
}
}
}
private void enableBtn (boolean idx) {
if (idx == true){
btnWord0.setEnabled(true);
btnWord1.setEnabled(true);
btnWord2.setEnabled(true);
btnWord3.setEnabled(true);
}
else if (idx == false){
btnWord0.setEnabled(false);
btnWord1.setEnabled(false);
btnWord2.setEnabled(false);
btnWord3.setEnabled(false);
}
}
}
You can detect when mouse is over button or some other element with this code:
button.addMouseListener( new MouseAdapter() {
public void mouseEntered( MouseEvent e ) {
// your code here (color of button)
}
} );
And like #DebilsHnd said change color back with mouseExited().

Two buttons changing panel color to red or blue

my first post here. I'm currently in school and usually spend my time here on Stackoverflow looking for answers to homework, this time i'd thought that perhaps i'll put my code here and maybe i'll get help more precis and quicker! Anyways, my problem is that i've written a code which you can see below, and I'm new to swing, studied it for a few hours only. My problem is that I'm not quite sure how to proceed with my problem, I have 2 buttons, what i want is when you click on first button the panel will change to Red, second button the panel changes to blue, so far only Red works and I don't know how to implement it so that blue works aswell.
Would greatly appreciate your help! (Don't be shy about pointing out a few errors or help along the way that doesn't have with the buttons to do, as I said, I'm new :P)
public class FirstProgram extends JFrame {
public FirstProgram() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
getContentPane().add(panel);
panel.setLayout(null);
JButton Colorbutton = new JButton("Red");
Colorbutton.setBounds(50, 60, 80, 30);
Colorbutton.setToolTipText("Panel changes to red");
Colorbutton.setBackground(Color.green);
JButton Colorrbutton = new JButton("Blue");
Colorrbutton.setBounds(1, 30, 90, 30);
Colorrbutton.setToolTipText("Panel changes to blue");
Colorrbutton.setBackground(Color.orange);
Colorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.red);
}
});
panel.add(Colorbutton);
panel.add(Colorrbutton);
setTitle("Time to change colors");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FirstProgram ex = new FirstProgram();
ex.setVisible(true);
}
});
}
}
you need another ActionListener. right now you just have one and it has just one behavior. create another one and tie to the 'Blue" button
JButton RedColorbutton = new JButton("Red");
RedColorbutton .setBounds(50, 60, 80, 30);
RedColorbutton.setToolTipText("Panel changes to red");
RedColorbutton.setBackground(Color.green);
JButton BlueColorbutton = new JButton("Blue");
BlueColorrbutton.setBounds(1,30,90,30);
BlueColorrbutton.setToolTipText("Panel changes to blue");
BlueColorrbutton.setBackground(Color.orange);
RedColorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.red);
}
});
BlueColorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.blue);
}
});
You've set an action listener for your Colorbutton, but not for Colorrbutton
Add this next to your other ActionListener
Colorrbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
panel.setBackground(Color.blue);
}
});
You are missing an ActionListener for the blue JButtton.
Similar to how you added the ActionListener to your ColorButton, your ColorrButton needs to have one registered. By the way, you may wish to change the ColorButton to redButton and the ColorrButton to blueButton or something like that to make things stick out better.
example:
Colorrbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.blue);
}
});
For the sake of reducing duplicate code, you can simplify the logic even further by having your class implement ActionListener.
public class FirstProgram extends JFrame implements ActionListener {
Then, when you are instantiating your buttons, add a listener like so:
redButton.addActionListener(this);
blueButton.addActionListener(this);
And then in your implementation of actionPerformed you could do something like:
public void actionPerformed(ActionEvent e) {
switch (e.getSource()) {
case redButton:
panel.setBackground(Color.red);
break;
case blueButton:
panel.setBackground(Color.blue);
break;
}
}
Anytime the red or blue buttons performs an action, the actionPerformed will be triggered, and then the logic to determine which button was the source will take over from there. This will add a little bit of length to your code, but as(if?) your program grows, it will reduce complexity greatly

how do you change the color of a jbutton after it is clicked?

I am making a jFrame that represents a go board. I want a click of a given button to change the color to represent placing a piece on the board. In my code below, I show a method that should be able to change the color of a button (it only changes the background of the whole frame). First question: Why is the button color not changing (this is not my bigger problem about changing color after click occurs, my preliminary issue is that the button color will not change). I do not get any errors, the button color just never changes.
public static void showBoard()
{
JFrame frame2 = new JFrame("Go Board");
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
for(int i = 19*19; i > 0; i--)
{
JButton firstButton = new JButton("");
firstButton.setBackground(Color.blue);
firstButton.setVisible(true);
firstButton.setContentAreaFilled(true);
firstButton.setOpaque(true);
firstButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
System.out.println("ddsd");
//int[] arr = findMove(0);
}
});
}
});
frame2.getContentPane().add(firstButton);
}
frame2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame2.setLayout(new GridLayout(19,19));
frame2.pack();
frame2.setVisible(true);
}
My second problem, getting the button to change color after being clicked, is presumably affected by the fact that I am not able to even change the button color. To get the button to change color after a click, I plan to put the button color change code inside the action listener.
So in summation, how can I change the color of the button after a click?
ANSWER:
The problem was the look and feel of my mac. Look to the checked answer for how to fix this if you have similar problem on your mac.
You don't need to call SwingUtilities.invokeLater inside your ActionListener, as the actionPerformed(ActionEvent) method will be invoked on the Event Thread already.
The following example demonstrates how to change a Button's background color when it's clicked on:
public class ChangeButtonColor implements Runnable {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
System.err.println("Cannot set LookAndFeel");
}
SwingUtilities.invokeLater(new ChangeButtonColor());
}
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
JButton button1 = new JButton("click me");
JButton button2 = new JButton("click me too");
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof Component) {
((Component)source).setBackground(Color.RED);
}
}
};
button1.addActionListener(listener);
button2.addActionListener(listener);
frame.add(button1);
frame.add(button2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Please note that the ActionListener used here can be used for all buttons. There is no need to create a new instance of it for every button.

JDialog not centered over parent JFrame

I am trying to get my JDialog to popup in the center of my JFrame on a button click. I have JOptionPanel that popup correctly over the parent JFrame, but the JDialog is popping up relative to the JFrame but not in the center.
The buttons are actually JMenuItem in my code, but I wrote them here as JButton to make things easier and straight forward.
Here's my code:
call from my Parent JFrame:
JButton about = new JButton("About");
about.addActionListener(new ActionListener() { //this one IS NOT in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
new AboutDialog(MyJFrame.this);
}
});
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() { //this one IS in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(MyJFrame.this, "Are you sure you want to exit ?","",JOptionPane.YES_NO_OPTION) == 0)
System.exit(0);
}
});
AboutDialog Class
public class AboutDialog extends JDialog{
public AboutDialog(JFrame parent) {
setLocationRelativeTo(parent);
setLayout(new BorderLayout());
...
Thank you
setLocationRelativeTo(parent);
The above code needs to be executed AFTER you have added all the components to the dialog and packed the dialog and before you make the dialog visible.
In your current code the size of the dialog is (0, 0) so it can't be centered properly.

Categories

Resources