Java examples for Swing:JColorChooser
Choosing colors with JColorChooser.
import java.awt.BorderLayout; 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.JColorChooser; import javax.swing.JPanel; class ShowColors2JFrame extends JFrame { private final JButton changeColorJButton; private Color color = Color.LIGHT_GRAY; private final JPanel colorJPanel; // set up GUI//from w ww .j a v a 2 s . c om public ShowColors2JFrame() { super("Using JColorChooser"); // create JPanel for display color colorJPanel = new JPanel(); colorJPanel.setBackground(color); // set up changeColorJButton and register its event handler changeColorJButton = new JButton("Change Color"); changeColorJButton.addActionListener(e -> { color = JColorChooser.showDialog(ShowColors2JFrame.this, "Choose a color", color); // set default color, if no color is returned if (color == null) color = Color.LIGHT_GRAY; // change content pane's background color colorJPanel.setBackground(color); }); add(colorJPanel, BorderLayout.CENTER); add(changeColorJButton, BorderLayout.SOUTH); setSize(400, 130); setVisible(true); } } public class Main { // execute application public static void main(String[] args) { ShowColors2JFrame application = new ShowColors2JFrame(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }