Java JColorChooser choose color

Description

Java JColorChooser choose color


// Choosing colors with JColorChooser.
import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
  private final JButton changeColorJButton = new JButton("Change Color");
  private Color color = Color.LIGHT_GRAY;
  private final JPanel colorJPanel = new JPanel();

  // set up GUI//from  w  w  w  .j  a  v  a2 s.  c  o  m
  public Main() {
    super("Using JColorChooser");
    colorJPanel.setBackground(color);
    changeColorJButton.addActionListener(e -> {
      color = JColorChooser.showDialog(Main.this, "Choose a color", color);

      // set default color, if no color is returned
      if (color == null)
        color = Color.LIGHT_GRAY;

      // change content pane's background color
      colorJPanel.setBackground(color);
    });

    add(colorJPanel, BorderLayout.CENTER);
    add(changeColorJButton, BorderLayout.SOUTH);

    setSize(400, 130);
    setVisible(true);
  }

  public static void main(String[] args) {
    Main application = new Main();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}



PreviousNext

Related