Creating a JColorChooser Dialog - Java Swing

Java examples for Swing:JColorChooser

Description

Creating a JColorChooser Dialog

Demo Code


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

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    Color initialColor = Color.red;

    // Show the dialog; this method does not return until the dialog is closed
    Color newColor = JColorChooser.showDialog(frame, "Dialog Title",
        initialColor);/*from   ww w.  j  a  va  2  s  . co m*/

    // Create a color chooser dialog
    initialColor = Color.white;
    JColorChooser chooser = new JColorChooser(initialColor);

    // Create a button using the action
    JButton button = new JButton(new ShowColorChooserAction(frame, chooser));
  }
}

class ShowColorChooserAction extends AbstractAction {
  JColorChooser chooser;
  JDialog dialog;

  ShowColorChooserAction(JFrame frame, JColorChooser chooser) {
    super("Color Chooser...");
    this.chooser = chooser;

    // Choose whether dialog is modal or modeless
    boolean modal = false;

    // Create the dialog that contains the chooser
    dialog = JColorChooser.createDialog(frame, "Dialog Title", modal, chooser,
        null, null);
  }

  public void actionPerformed(ActionEvent evt) {
    // Show dialog
    dialog.setVisible(true);

    setEnabled(false);
  }
}

Related Tutorials