Skip to content Skip to navigation Skip to collection information

Connexions

You are here: Home » Content » Object-Oriented Programming (OOP) with Java » Java OOP: Handling document events on a text field and creating a color swatch

Navigation

Table of Contents

Recently Viewed

This feature requires Javascript to be enabled.
 

Java OOP: Handling document events on a text field and creating a color swatch

Module by: Richard Baldwin. E-mail the author

Summary: Learn how to handle document events on text fields containing color values. Also learn how to create a color swatch.

Preface

This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP) using Java.

Viewing tip

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.

Figures

Listings

Preview

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.

Figure 1: Program output at startup.
Program output at startup.
Missing image.

Program output after clicking the button

Figure 2 shows the program output after clicking the button labeled "Set Green Color."

Figure 2: Program output after clicking the button.
Program output after clicking the button.
Missing image.

Note that in Figure 2 ,

  • the color values in the Red and Blue text fields are zero,
  • the color value in the Green text field is 255,
  • the square (color swatch) at the right end of the green panel is green with a black outline
  • the square is not transparent.

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

  • the color values in the Red and Green text fields are 255,
  • the color value in the Blue text field is 0, and
  • the square at the right end of the green panel is yellow with a black outline.
Figure 3: Program output after entering color values.
Program output after entering color values.
Missing image.

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.

Discussion and sample 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.

Listing 1: The driver class.

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.

Listing 2: Beginning of the class named Prob13Runner .

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.

Listing 3: Beginning of constructor for Prob13Runner.

  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.

Listing 4: Continue the constructor.

    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.

Listing 5: Register a listener object on the button.

    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:

  • changedUpdate
    • Gives notification that an attribute or set of attributes changed.
  • insertUpdate
    • Gives notification that there was an insert into the document.
  • removeUpdate
    • Gives notification that a portion of the document has been removed.

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.

Listing 6: Beginning of DocumentListener on 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.

Listing 7: The removeUpdate method.

        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.

Listing 8: The insertUpdate method.

        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 .

Listing 9: The paintColorSwatch method.

  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.

Run 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.

Summary

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.

What's next?

In the next module, you will learn how to use a JColorChooser object to specify a color in any one of five different ways.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Handling document events on a text field and creating a color swatch
  • File: Java1326.htm
  • Published: 09/11/12

Note:

Disclaimers:

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.

Complete program listing

A complete listing of the source code discussed in this module is shown in Listing 10 .

Listing 10: Complete program listing.

/*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-

Collection Navigation

Content actions

Download:

Collection as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add:

Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks