Inside Collection (Course): Object-Oriented Programming (OOP) with Java
Summary: Learn how to handle document events on text fields containing color values. Also learn how to create a color swatch.
This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP) using Java.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
In this module, I will show you how to handle document events on text fields containing color values.
I will also show you how to create a color swatch that displays the color indicated by the color values in the Red, Green, and Blue text fields.
Program output at startup
Figure 1 shows the program output at startup.
Note that the color values in the Red, Green, and Blue text fields are all zero, the color of the square at the right end of the Green panel is black.
Recall that black is represented by Red, Green, and Blue color values of zero.
| Program output at startup. |
|---|
![]() |
Program output after clicking the button
Figure 2 shows the program output after clicking the button labeled "Set Green Color."
| Program output after clicking the button. |
|---|
![]() |
Note that in Figure 2 ,
Recall that pure green is represented by Red and Blue color values of zero, with a Green color value of 255.
Program output after entering color values
Figure 3 shows the program output after manually entering a value of 255 in the Red text field.
Note that
| Program output after entering color values. |
|---|
![]() |
Recall that pure yellow is represented by Red and Green color values of 255, with a Blue color value of zero.
Color of square tracks color values in text fields
The square (color swatch) always has a black outline as shown in Figure 3 .
The color in the swatch always tracks the color values in the text fields regardless of whether those values are changed manually, or they are changed by program code.
A complete listing of the program discussed in this module is provided in Listing 10 .
Will explain in fragments
I will break this program down and explain it in fragments.
The driver class
The driver class named Prob13 is shown in Listing 1 . There is nothing new here.
public class Prob13{
public static void main(String[] args){
new Prob13Runner();
}//end main method
}//end class Prob13
Beginning of the class named Prob13Runner
The class named Prob13Runner begins in Listing 2 , which declares several instance variables and initializes some of them.
class Prob13Runner extends JFrame{
private JPanel controlPanel = new JPanel();
private JPanel colorPanel = new JPanel();
private JPanel buttonPanel = new JPanel();
private JPanel colorIndicatorPanel = new JPanel();
private JTextField redField = new JTextField("000000");
private JTextField greenField =
new JTextField("000000");
private JTextField blueField = new JTextField("000000");
private int redInt = 0;
private int greenInt = 0;
private int blueInt = 0;
private JButton setColorButton =
new JButton("Set Green Color");
Beginning of constructor for Prob13Runner
The constructor begins in Listing 3 . The last two statements in Listing 3 may be new to you.
The JPanel referred to by colorIndicatorPanel is the color swatch shown in Figure 3 .
The last two statements in Listing 3 control the border color, and the size of the JPanel (color swatch) object.
public Prob13Runner(){//constructor
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
The constructor continues in Listing 4 .
There is nothing new in Listing 4 with the possible exception of the call to the method named paintColorSwatch .
I will explain the method named paintColorSwatch later.
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(setColorButton);
//Color the swatch for the first time.
paintColorSwatch();
//Add the controlPanel to the content pane, adjust to
// the correct size, and set the title.
getContentPane().add(controlPanel);
pack();
setTitle("Dick Baldwin");
//Make the GUI visible
setVisible(true);
Register listeners on the user input components
This program registers event listener objects on four input components:
One component is the button at the bottom of Figure 3 labeled Set Green Color.
The other three components are the three text fields labeled Red , Green , and Blue shown in Figure 3 .
The three event listeners that are registered on the text fields are very similar. Therefore, I will explain only one of them. You can view the code for the other two in Listing 10 .
Register a listener object on the button
Listing 5 registers an ActionListener object on the JButton object referred to by setColorButton .
You have seen code like this in numerous previous modules. Therefore, a detailed explanation of Listing 5 should not be required here.
setColorButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set the color to green.
redInt = 0;
greenInt = 255;
blueInt = 0;
//Show the color values in the text fields.
redField.setText("" + redInt);
greenField.setText("" + greenInt);
blueField.setText("" + blueInt);
}//end action performed
}//end new ActionListener
);//end addActionListener
The DocumentListener interface
The DocumentListener interface can be described briefly as follows:
"Interface for an observer to register to receive notifications of changes to a text document."
This interface is implemented by numerous classes including the JTextField class. As mentioned earlier, the Red , Green , and Blue text fields in Figure 3 are objects of the JTextField class and therefore implement the DocumentListener interface.
DocumentListener methods
The DocumentListener interface declares the follow three methods:
Only the insertUpdate and removeUpdate methods are of interest in this program. Therefore, the changedUpdate method will be implemented as an empty method.
Beginning of DocumentListener
Listing 6 shows the beginning of the definition, instantiation, and registration of a DocumentListener object on the object of type Document that is encapsulated in the Red text field.
redField.getDocument().addDocumentListener(
new DocumentListener(){
public void changedUpdate(DocumentEvent e){
//Empty method - not needed
}//end changedUpdate
Note that registration of the listener object in this case has an additional level of indirection (getDocument) as compared to the registration of the listener on the JButton in Listing 5 . In other words, the listener is not registered on the text field. Instead, it is registered on the document encapsulated in the text field.
This listener will respond when the contents of the text field are modified, either by the program, or by the user.
(As explained earlier, the changedUpdate method is defined as an empty method.)
The removeUpdate method
Listing 7 shows the removeUpdate method in its entirety.
public void removeUpdate(DocumentEvent e){
try{
redInt = Integer.parseInt(
redField.getText());
if((redInt >= 0) && (redInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end removeUpdate
Behavior of the removeUpdate method
Listing 7 calls the static parseInt method of the Integer class to convert the String contents of the Red text field into a value of type int .
The parseInt method can throw a NumberFormatException if the string does not contain a parsable integer.
The possibility of a NumberFormatException , (which is a checked exception) requires that the call to the parseInt method be enclosed in a try-catch block.
In this program, the catch block causes the removeUpdate method to do nothing if the contents of the text field cannot be converted into an int , which causes a NumberFormatException to be thrown
If a NumberFormatException exception is not thrown, the return value from the parseInt method is stored in an instance variable named redInt .
If the value of redInt is between 0 and 255 inclusive, Listing 7 calls the method named paintColorSwatch , causing the color swatch to be repainted, using the Red value, along with the Green and Blue values computed elsewhere.
The insertUpdate method
The insertUpdate method is shown in Listing 8 .
The behavior of the insertUpdate method is essentially the same as the behavior of the removeUpdate method explained earlier. Therefore, an explanation of the insertUpdate method should not be needed.
public void insertUpdate(DocumentEvent e){
try{
redInt = Integer.parseInt(
redField.getText());
if((redInt >= 0) && (redInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
//-------------------------------------------//
}//end new DocumentListener
);//end addDocumentListener
The end of the class definition
Listing 8 also signals the end of the anonymous class definition that began in Listing 6 .
The Green and Blue text fields
The Green and Blue text fields are processed using very similar DocumentListener objects as used for the Red text field. You can view that code in Listing 10 .
That ends the discussion of the constructor for the class named Prob13Runner .
The method named paintColorSwatch
There were earlier references to a method named paintColorSwatch . The code for the paintColorSwatch method is shown in Listing 9 .
private void paintColorSwatch(){
colorIndicatorPanel.setBackground(
new Color(redInt,greenInt,blueInt));
}//end paintColorSwatch
//----------------------------------------------------//
}//end class Prob13Runner
The paintColorSwatch method sets the background color for the JPanel object that represents the color swatch, using values of red, green, and blue that are computed elsewhere in the program.
The end of the program
Listing 9 also signals the end of the class named Prob13Runner and the end of the program.
I encourage you to copy the code from Listing 10 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.
In this lesson, you learned how to handle document events on text fields containing color values. You also learned how to create a color swatch.
In the next module, you will learn how to use a JColorChooser object to specify a color in any one of five different ways.
This section contains a variety of miscellaneous information.
Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.
I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.
Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.
A complete listing of the source code discussed in this module is shown in Listing 10 .
/*File Prob13 Copyright 2012 R.G.Baldwin
This program handles document events on the contents of
text fields containing color values.
The values are used to create a color swatch that displays
the color indicated by the color values in the red, green,
and blue text fields.
*********************************************************/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Dimension;
public class Prob13{
public static void main(String[] args){
new Prob13Runner();
}//end main method
}//end class Prob13
//======================================================//
class Prob13Runner extends JFrame{
private JPanel controlPanel = new JPanel();
private JPanel colorPanel = new JPanel();
private JPanel buttonPanel = new JPanel();
private JPanel colorIndicatorPanel = new JPanel();
private JTextField redField = new JTextField("000000");
private JTextField greenField =
new JTextField("000000");
private JTextField blueField = new JTextField("000000");
private int redInt = 0;
private int greenInt = 0;
private int blueInt = 0;
private JButton setColorButton =
new JButton("Set Green Color");
//----------------------------------------------------//
public Prob13Runner(){//constructor
setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE);
controlPanel.setLayout(new GridLayout(2,1));
controlPanel.add(colorPanel);
controlPanel.add(buttonPanel);
colorPanel.setBackground(Color.GREEN);
colorPanel.add(new JLabel("Red = "));
colorPanel.add(redField);
colorPanel.add(new JLabel(" Green = "));
colorPanel.add(greenField);
colorPanel.add(new JLabel(" Blue = "));
colorPanel.add(blueField);
colorPanel.add(colorIndicatorPanel);
colorIndicatorPanel.setBorder(
new LineBorder(Color.black,1));
colorIndicatorPanel.setPreferredSize(
new Dimension(20,20));
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(setColorButton);
//Color the swatch for the first time.
paintColorSwatch();
//Add the controlPanel to the content pane, adjust to
// the correct size, and set the title.
getContentPane().add(controlPanel);
pack();
setTitle("Dick Baldwin");
//Make the GUI visible
setVisible(true);
//--------------------------------------------------//
//Register listeners on the user input components.
//--------------------------------------------------//
setColorButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
//Set the color to green.
redInt = 0;
greenInt = 255;
blueInt = 0;
//Show the color values in the text fields.
redField.setText("" + redInt);
greenField.setText("" + greenInt);
blueField.setText("" + blueInt);
}//end action performed
}//end new ActionListener
);//end addActionListener
//--------------------------------------------------//
//Register a document listener on the red text field.
// This listener will respond when the contents of
// the text field are modified either by the program
// or by the user.
redField.getDocument().addDocumentListener(
new DocumentListener(){
public void changedUpdate(DocumentEvent e){
//Empty method - not needed
}//end changedUpdate
public void removeUpdate(DocumentEvent e){
try{
redInt = Integer.parseInt(
redField.getText());
if((redInt >= 0) && (redInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end removeUpdate
public void insertUpdate(DocumentEvent e){
try{
redInt = Integer.parseInt(
redField.getText());
if((redInt >= 0) && (redInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
}//end new DocumentListener
);//end addDocumentListener
//--------------------------------------------------//
//Register a document listener on the green text
// field. Essentially the same as the above.
greenField.getDocument().addDocumentListener(
new DocumentListener(){
public void changedUpdate(DocumentEvent e){}
public void removeUpdate(DocumentEvent e){
try{
greenInt = Integer.parseInt(
greenField.getText());
if((greenInt >= 0) && (greenInt <= 255))
{
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end removeUpdate
public void insertUpdate(DocumentEvent e){
try{
greenInt = Integer.parseInt(
greenField.getText());
if((greenInt >= 0) && (greenInt <= 255))
{
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
}//end new DocumentListener
);//end addDocumentListener
//--------------------------------------------------//
//Register a document listener on the blue text
// field. Essentially the same as the above.
blueField.getDocument().addDocumentListener(
new DocumentListener(){
public void changedUpdate(DocumentEvent e){}
public void removeUpdate(DocumentEvent e){
try{
blueInt = Integer.parseInt(
blueField.getText());
if((blueInt >= 0) && (blueInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end removeUpdate
public void insertUpdate(DocumentEvent e){
try{
blueInt = Integer.parseInt(
blueField.getText());
if((blueInt >= 0) && (blueInt <= 255)){
paintColorSwatch();
}//end if
}catch(Exception ex){
//do nothing on exception
}//end catch
}//end insertUpdate
}//end new DocumentListener
);//end addDocumentListener
//--------------------------------------------------//
}//end constructor
//----------------------------------------------------//
//The purpose of this method is to color a swatch
// located next to the RGB color values.
private void paintColorSwatch(){
colorIndicatorPanel.setBackground(
new Color(redInt,greenInt,blueInt));
}//end paintColorSwatch
//----------------------------------------------------//
}//end class Prob13Runner
-end-