Customizing the Preview Panel of a JColorChooser Dialog - Java Swing

Java examples for Swing:JColorChooser

Description

Customizing the Preview Panel of a JColorChooser Dialog

Demo Code

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.colorchooser.ColorSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
  public void m() throws Exception {
    JColorChooser chooser = new JColorChooser();
    chooser.setPreviewPanel(new MyPreviewPanel(chooser));

  }/*w ww  .  j a va  2  s  .co m*/
}
class MyPreviewPanel extends JComponent {
  Color curColor;

  public MyPreviewPanel(JColorChooser chooser) {
    curColor = chooser.getColor();
    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent evt) {
        ColorSelectionModel model = (ColorSelectionModel) evt.getSource();
        // Get the new color value
        curColor = model.getSelectedColor();
      }
    });
    // Set a preferred size
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}

Related Tutorials