Academic Java    Java Tutorial  >  Swing  >  JColorChooser

JColorChooser Example

Java JColorChooser EXAMPLE output Java JColorChooser EXAMPLE output This JColorChooser example displays a panel containing a button that when selected initiates a JColorChooser dialog.

When the user hits "OK" the background of the content pane is set to the chosen color.

The three stages of this are shown left to right.
// JColorChooser Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class JColorChooserExample {

   static Container cp;
   public static void main(String[] args) {

      final JFrame frame = new JFrame("Color Chooser");
      cp = frame.getContentPane( );
      cp.setLayout(new GridBagLayout());

      JButton button = new JButton("select color");
      cp.add(button);

      button.addActionListener(new ActionListener( ) {
         public void actionPerformed(ActionEvent e) {
            Color c = JColorChooser.showDialog(frame,"Choose a color", Color.red);
            cp.setBackground(c);
         }
      });

      frame.setSize(200, 300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}