Use color chooser to change background of controls - Java Swing

Java examples for Swing:JColorChooser

Description

Use color chooser to change background of controls

Demo Code

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

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

public class ColorChooser extends JFrame {
  public static void main(String[] args) {
    new ColorChooser();
  }// w ww. j  av a  2  s . co  m

  private JLabel sampleText;
  private JButton chooseButton;

  public ColorChooser() {
    this.setSize(300, 100);
    this.setTitle("Color Chooser");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel1 = new JPanel();

    sampleText = new JLabel("this is a test");
    sampleText.setBackground(null);
    panel1.add(sampleText);

    chooseButton = new JButton("Choose Color");
    chooseButton.addActionListener(e->{
      Color c = JColorChooser.showDialog(null, "Choose a Color", sampleText.getForeground());
      if (c != null)
        sampleText.setForeground(c);
    });

    chooseButton.setBackground(SystemColor.info);
    panel1.add(chooseButton);

    this.add(panel1);
    this.setVisible(true);
  }

}

Related Tutorials