Adding a Custom Color Chooser Panel to a JColorChooser Dialog - Java Swing

Java examples for Swing:JColorChooser

Description

Adding a Custom Color Chooser Panel to a JColorChooser Dialog

Demo Code


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.colorchooser.AbstractColorChooserPanel;

public class Main {
  public static void main(String[] args) {
    JColorChooser chooser = new JColorChooser();
    chooser.addChooserPanel(new MyChooserPanel());
  }//www. j a va2  s .c o  m
}

class MyChooserPanel extends AbstractColorChooserPanel {
  public void buildChooser() {
    setLayout(new GridLayout(0, 3));
    makeAddButton("Red", Color.red);
    makeAddButton("Green", Color.green);
    makeAddButton("Blue", Color.blue);
  }

  public void updateChooser() {
  }

  public String getDisplayName() {
    return "MyChooserPanel";
  }

  // This method is currently not used.
  public Icon getSmallDisplayIcon() {
    return null;
  }

  // This method is currently not used.
  public Icon getLargeDisplayIcon() {
    return null;
  }

  // These are helper methods specifically for this example

  // Creates a color button and adds it to this panel.
  private void makeAddButton(String name, Color color) {
    JButton button = new JButton(name);
    button.setBackground(color);
    button.setAction(setColorAction);
    add(button);
  }

  Action setColorAction = new AbstractAction() {
    public void actionPerformed(ActionEvent evt) {
      JButton button = (JButton) evt.getSource();

      getColorSelectionModel().setSelectedColor(button.getBackground());
    }
  };

}

Related Tutorials