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.