Java Reference
In-Depth Information
The JColorChooser component (package javax.swing ) enables application users to
select colors. Figures 13.7-13.8 demonstrate a JColorChooser dialog. When you click the
Change Color button, a JColorChooser dialog appears. When you select a color and press
the dialog's OK button, the background color of the application window changes.
1
// Fig. 13.7: ShowColors2JFrame.java
2
// Choosing colors with JColorChooser.
3
import java.awt.BorderLayout;
4
import java.awt.Color;
5
import java.awt.event.ActionEvent;
6
import java.awt.event.ActionListener;
7
import javax.swing.JButton;
8
import javax.swing.JFrame;
9
10
import javax.swing.JColorChooser;
import javax.swing.JPanel;
11
12
public class ShowColors2JFrame extends JFrame
13
{
14
private final JButton changeColorJButton;
15
private Color color = Color.LIGHT_GRAY ;
16
private final JPanel colorJPanel;
17
18
// set up GUI
19
public ShowColors2JFrame()
20
{
21
super( "Using JColorChooser" );
22
23
// create JPanel for display color
24
colorJPanel = new JPanel();
25
colorJPanel.setBackground(color);
26
27
// set up changeColorJButton and register its event handler
28
changeColorJButton = new JButton( "Change Color" );
29
changeColorJButton.addActionListener(
30
new ActionListener() // anonymous inner class
31
{
32
// display JColorChooser when user clicks button
33
@Override
34
public void actionPerformed(ActionEvent event)
35
{
36
color = JColorChooser.showDialog(
ShowColors2JFrame. this , "Choose a color" , color);
37
38
39
// set default color, if no color is returned
40
if (color == null )
41
color = Color.LIGHT_GRAY ;
42
43
// change content pane's background color
44
colorJPanel.setBackground(color);
45
} // end method actionPerformed
46
} // end anonymous inner class
47
); // end call to addActionListener
Fig. 13.7 | Choosing colors with JColorChooser . (Part 1 of 2.)
 
Search WWH ::




Custom Search