Removing a Color Chooser Panel from a JColorChooser Dialog - Java Swing

Java examples for Swing:JColorChooser

Description

Removing a Color Chooser Panel from 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.AbstractColorChooserPanel;
import javax.swing.colorchooser.ColorSelectionModel;

public class Main {
  public static void main(String[] argv) throws Exception {
    JColorChooser chooser = new JColorChooser();

    // Retrieve the current set of panels
    AbstractColorChooserPanel[] oldPanels = chooser.getChooserPanels();

    // Remove panels
    for (int i = 0; i < oldPanels.length; i++) {
      String clsName = oldPanels[i].getClass().getName();
      if (clsName.equals("javax.swing.colorchooser.DefaultSwatchChooserPanel")) {
        // Remove swatch chooser if desired
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName
          .equals("javax.swing.colorchooser.DefaultRGBChooserPanel")) {
        // Remove rgb chooser if desired
        chooser.removeChooserPanel(oldPanels[i]);
      } else if (clsName
          .equals("javax.swing.colorchooser.DefaultHSBChooserPanel")) {
        // Remove hsb chooser if desired
        chooser.removeChooserPanel(oldPanels[i]);
      }// ww w .j av  a  2 s  . c om
    }

  }
}

class MyPreviewPane extends JComponent {
  Color curColor;

  public MyPreviewPane(JColorChooser chooser) {
    curColor = chooser.getColor();

    ColorSelectionModel model = chooser.getSelectionModel();
    model.addChangeListener(evt -> {
      ColorSelectionModel m = (ColorSelectionModel) evt.getSource();
        curColor = m.getSelectedColor();
      });
    setPreferredSize(new Dimension(50, 50));
  }
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}

Related Tutorials