Swing Examples - Using Color Choosers



Following example showcase how to create and use a Color Chooser in swing based application.

We are using the following APIs.

  • JColorChooser − To create a standard color chooser which allows user to choose colors from a pallete.

  • JColorChooser.getColor(); − To get the selected color of the Color Chooser.

  • JColorChooser.getSelectionModel().addChangeListener() − To handle event when user select any color from Color Chooser.

Example

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;

import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(650, 400);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      final JLabel colorLabel = new JLabel("Color Chooser Example");     
      final JColorChooser colorChooser = new JColorChooser();
      colorChooser.getSelectionModel().addChangeListener(new ChangeListener() {
         @Override
         public void stateChanged(ChangeEvent e) {
            Color color = colorChooser.getColor();
            colorLabel.setForeground(color);
         }
      });
      panel.add(colorLabel);
      panel.add(colorChooser);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}

Output

Using Color Chooser
swingexamples_colorchoosers.htm
Advertisements