Home arrow Java arrow Page 8 - Graphical User Interface
JAVA

Graphical User Interface


Graphical user interfaces allow end users to interact with applications in a more or less intuitive manner. This article explains how to use these components in your own Java programs. It is taken from chapter 12 of the book Java DeMYSTiFieD, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548).

Author Info:
By: McGraw-Hill/Osborne
Rating: 5 stars5 stars5 stars5 stars5 stars / 45
September 01, 2005
TABLE OF CONTENTS:
  1. · Graphical User Interface
  2. · A Simple GUI
  3. · Content Container
  4. · Grid Layout Manager and the Gridbag Layout Manager
  5. · Labels and Text Fields
  6. · Combo Boxes
  7. · Getting Data from GUI Components
  8. · Reading Radio Buttons and Check Boxes

print this article
SEARCH DEVARTICLES

Graphical User Interface - Reading Radio Buttons and Check Boxes
(Page 8 of 8 )

Radio buttons and check boxes are read using the ItemListener, which you’ll need to implement in the class that reacts to these GUI elements. An ItemListener is very similar to an ActionListener in that a radio button and a check box button have an addItemListener()method that is called to associate the button with the ItemListener. Also, as with the addActionListener() method, you must pass the ItemListener() method the this keyword.

Radio buttons and check boxes are read using the , which you’ll need to implement in the class that reacts to these GUI elements. An is very similar to an in that a radio button and a check box button have an method that is called to associate the button with the . Also, as with the method, you must pass themethod the this keyword.

The ItemListener calls the itemStateChanged() method each time the status of the radio button or check box changes. Therefore, you need to define an itemStateChanged() method into your program in order to react to these changes. The itemStateChanged() method must have one argument—an ItemEvent object.

The following example shows how to react to a check box, which is the same technique used to react to a radio button, only a reference is made to the radio button inside of the check box. You change a check box by either selecting the check box or deselecting the check box. This is referred to as a state change. You can determine what changed by calling the getStateChange() method. The getStateChange() method returns an integer that is compared to two ItemEvent constants. These are ItemEvent.SELECTED and ItemEvent.DESELECTED.

Let’s take a look inside the itemStateChanged() method to see how the getStateChange() method is used. The first statement calls the getStateChange() method and assigns the return value to the state integer. The value of the state integer is compared to both ItemEvent constants using an if statement. Each if statement has a nested if that is used to determine which check box generated the event. The getItem() method is called to retrieve a reference to the check box, which is then compared to references of check boxes that we created in the program. When there is a match, an appropriate message is displayed in the text area through a call to the setText() method. Figure 12-13 shows the window created by this example.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Demo {
    
public static void main(String[] args)
     
{
         
Window win = new Window();
     
}
}
class Window extends JFrame implements ItemListener {
   JTextArea ta = new JTextArea(2, 25);
   JCheckBox cb1 = new JCheckBox("Test 1");
   JCheckBox cb2 = new JCheckBox("Test 2");
   public Window ()
   {
      
super ("Hello world!");
       setSize(400,200);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setVisible(true);
        
Container ca = getContentPane();
         ca.setBackground(Color.lightGray);
         FlowLayout flm = new FlowLayout();
         ca.setLayout(flm);
         cb1.addItemListener(this);
         cb2.addItemListener(this);
         ca.add(cb1);
         ca.add(cb2);
         ca.add(ta);
         setContentPane(ca);
  
}
  
public void itemStateChanged(ItemEvent event) {
          int state = event.getStateChange();
          if (state == ItemEvent.SELECTED) {
           
if(event.getItem() == cb1)
            ta.setText("Test 1 Selected");
            if(event.getItem() == cb2)
                
ta.setText("Test 2 Selected");
        }
        if (state == ItemEvent.DESELECTED) {
          
if(event.getItem() == cb1)
         ta.setText("Test 1 Deselected");
     if(event.getItem() == cb2)
   
ta.setText("Test 2 Deselected");
   }
   }
}

 
Figure 12-13.  The status of the check box is read through a call to
                      the
getStateChange()
method, which is then used to
                      determine the appropriate message to display in the 
                      text area.

Reading a Combo Box

A combo box also uses the ItemListener; therefore, you use the same technique for associating a combo box with the ItemListener as you use to associate a check box with the ItemListener.

A combo box also uses the ; therefore, you use the same technique for associating a combo box with the as you use to associate a check box with the .

You’ll also need to define an itemStateChanged() method. Within the itemStateChanged() method, you need to call the getItem() method in order to retrieve the text displayed in the combo box. You’ll need to convert the return value to a string by using the following statement (note that the getItem() method is prefaced by a reference to the ItemEvent):

String pick = event.getItem().toString();

The following example shows how to read the contents of a combo box. This example displays a combo box and a text area. Whenever someone selects a different item from the drop-down list, the ItemListener calls the itemStateChanged() method, where the text appearing in the combo box is retrieved through a call to the getItem() method and then displayed in the text area. Figure 12-14 shows what you’ll see when you run this example.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Demo {
     public static void main(String[] args)
     
{
          Window win = new Window();
     
}
}
class Window extends JFrame implements ItemListener {
  
JTextArea ta = new JTextArea(2, 25);
      
JComboBox combo1 = new JComboBox();
   public Window ()
   {
     
super ("Hello world!");
      setSize(400,200);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      Container ca = getContentPane();
      ca.setBackground(Color.lightGray);
      FlowLayout flm = new FlowLayout();
      ca.setLayout(flm);
      combo1.addItemListener(this);
      combo1.addItem("Test 1");
       
combo1.addItem("Test 2");
      ca.add(combo1);
      ca.add(ta);
      setContentPane(ca);
  
}
  
public void itemStateChanged(ItemEvent event) {
       String pick = event.getItem().toString();
       ta.setText(pick);
  
}
}

 
Figure 12-14.  Each time text in the combo box changes, the event
                      triggers the program to copy the text into the text  
                      area.

Disabling and Enabling GUI Elements

You’ve probably noticed when using a GUI application that some GUI elements are grayed out and inaccessible to you. Programmers call these disabled GUI elements. GUI elements are disabled whenever they shouldn’t be used or do not apply to the current process.

You’ve probably noticed when using a GUI application that some GUI elements are grayed out and inaccessible to you. Programmers call these GUI elements. GUI elements are disabled whenever they shouldn’t be used or do not apply to the current process.

For example, you’ll recall in a previous section that we used a push button to copy text from one text area to another text area. We could disable the push button until the user enters text into the first text area because we cannot copy something that isn’t there. Once text is entered into the first text area, we would then enable the push button.

You can enable and disable a GUI element by calling the setEnabled() method and passing it a Boolean true to enable the element or a Boolean false to disable the element. Here’s a statement that enables button 1 (bt1 is a reference to a button):

bt1.setEnabled(true);

Quiz
  1. What is the purpose of an event listener?
  2. What is an event handler?
  3. Can you display GUI elements in a window?
  4. What is the purpose of a content pane?
  5. Why would you want to disable a GUI element?
  6. Can a window be created but not shown?
  7. How do you place a content pane in a container?
  8. What is the purpose of a layout manager?
  9. Can you explicitly specify the location of a GUI element in a window?
  10. What is a major difference between creating a GUI in Java as opposed to creating a GUI in another programming language such as C++?

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials