- Example - Home
- Example - Environment Setup
- Example - Borders
- Example - Buttons
- Example - CheckBoxes
- Example - Combo Boxes
- Example - Color Choosers
- Example - Dialogs
- Example - Editor Panes
- Example - File Choosers
- Example - Formatted TextFields
- Example - Frames
- Example - Lists
- Example - Layouts
- Example - Menus
- Example - Password Fields
- Example - Progress Bars
- Example - Scroll Panes
- Example - Sliders
- Example - Spinners
- Example - Tables
- Example - Toolbars
- Example - Tree
Swing Examples - Using Color Choosers in a dialog
Following example showcase how to create and use a Color Chooser in a dialog in swing based application.
We are using the following APIs.
JColorChooser − To create a standard color chooser which allows user to choose colors from a pallete.
JColorChooser.showDialog(); − To show the Color Chooser as a dialog box.
Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
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;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
final JLabel colorLabel = new JLabel("Color Chooser Example");
JButton button = new JButton("Choose Color");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(frame,
"Select Color of Label", Color.black);
colorLabel.setForeground(color);
}
});
panel.add(colorLabel);
panel.add(button);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Output
swingexamples_colorchoosers.htm
Advertisements