Title: Gui Component Basics
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

GUI Component Basics

BasicComponents.java

1. The AWT contains an abstract class called Component. A lot of useful classes are derived from Component ( JButton, JTextField, JTextArea, JLabel, etc). There is a lot of useful common software buried in the Component class. We will start out using some of these higher level classes.
2. I would strongly recommend that you get familiar with navigating the java.awt & javax.swing packages, because we will only be scratching the surface of the capabilities.
3. Another key class to understand is the notion of a Container. A JFrame and and JApplet are both instances of a Container. A Container has all of the properties of Component in addition to the capability of being able to hold other Components inside of it. For example on your JFrame or your JApplet, you may want to add several buttons, textFields, etc. You can do this because the JApplet class has Container capabilities.
4. Student Clock - example of using Applet code, paint and a thread for animation.
5. JTextField, and JTextArea - To have an online text field, use the JTextField class. If you want a multi-line input area, use the JTextArea class. Both of these classes are derived from JTextComponent. Keep this in mind, because if you don't find what you want in online help under JTextField, or JTextArea, you might want to consider looking under the JTextComponent class which has a lot of the basic functionality for both of these classes.
6. For the time being we will use the FlowLayout class for a LayoutManager. It places components on the screen from left to right. When it gets all the way to the right it starts a new "line" of components. We will cover better layout approaches later.
7. In this example, we are also adding a JLabel class. A JLabel has no capability to receive user input. A JLabel merely holds onto static text.


import java.awt.*;
import javax.swing.*;

public class BasicComponents extends JFrame {

	BasicComponents(String name){
        super(name);
        setSize(600,400);
        // Construct a Label and add it with one command
        setLayout(new FlowLayout());
        add(new JLabel("This is a long label ........."));

        // Single Line Input/Output Field
        JTextField t = new JTextField(40);
        add(t);

        // Button
        JButton b = new JButton("Click here to get something done");
        add(b);

        // Multple Line Input/Output Field
        JTextArea toutput = new JTextArea(4,40);
        add(toutput);

        // Print out the Java Version you are using

         String javaVersion = System.getProperty("java.version");
        toutput.append(javaVersion);

        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
     }

  public static void main(String[] args) {
    BasicComponents basic = new BasicComponents("basic components");
  } // end of main
}



BasicAction.java and the ActionListern interface

JButtons and many other Components use the ActionListener interface. We discussed user inputs in the drawing area when we discussed MouseListener, etc. I have a link that contains a big list of Listener interfaces can be found in:

More Listeners

The way you do it is as follows:

1. You need a class that implements the ActionListener interface. We are going to take the easy approach here and claim that our BasicAction class implements ActionListener. Like before, we can take other approaches: Inner Class, Anonymous classes.
2. The ActionListener interface only has one routine in it, so we just add it to our BasicAction class:
public void actionPerformed(ActionEvent e)
3. Lastly, after we create our JButton, we pass a pointer to a class that implements the ActionListener interface. In our program it happens to be the BasicAction class itself, so we just pass the keyword this. We do this by taking the JButton instance b and issuing the command:
b.addActionListener(this);
4. In our actionPerformed routine we are going to fetch the text typed into the TextField class (tinput) and append it to the end of our TextArea class (toutput). To do this we used the setText and getText methods.
5. So you type input into either a TextField or TextArea. If you want to set either of these classes to have a certain string, use
setText(String text);
6. If you want to append text to the end of the buffer use:
append(String text);
7. getSelectedText() - this routine will return the selected text in a text component.
8. If you want to fetch the text currently in one of these classes use the routine:
String getText();
9. When using JTextArea, you need to explicitly enter in your newline (OS specific) string. So instead of using '\n' on Linux or '\r' '\n' on Windows, you can use System.getProperties to fetch the end of line separator.



import java.awt.*;
import javax.swing.*;
import java.awt.event.*; // New Import for Events

public class BasicAction extends JFrame
    implements ActionListener
{
   JTextField tinput = new JTextField("Hi", 60);
   String endline= System.getProperty("line.separator");
   JTextArea toutput = new JTextArea("TextArea class"+endline, 4, 60);


   public BasicAction(String name) {
        super(name);
        setSize(800,400);
		
        // Construct a Label and add it with one command

        setLayout(new FlowLayout());
        add(new JLabel("This is a long label ........."));

        add(tinput);

        JButton b = new JButton("Click here to get something done");
        add(b);
        add(toutput);

        b.addActionListener(this);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
     }

    public void actionPerformed(ActionEvent e) {
        String str = tinput.getText();

        toutput.append(str + endline);

        System.out.println(str);
       }


  public static void main(String[] args) {
    BasicAction basicAction = new BasicAction("Basic Action");
  } // end of main
}




Exercises

1. In the above example, see the effect of the FlowLayout manager as you resize the screen.
2. Notice what happens in the JTextArea class when we add a lot of lines or make a line that is extra long.
3. Rework the last example to use an inner class.
4. Why does ActionListener not have an ActionAdapter class?
5. Add another JButton to the BasicAction.java class. Add ActionListener events for both JButtons and the JTextField. Note that hitting the Enter key invokes the ActionListener event for a JTextField. Now the question is how can I tell which object caused the ActionEvent to occur? If you go to online help and look under ActionEvent, see if you can find a method called
getSource( ) or getActionCommand( ) and figure out how to use it.
6. See if you can add an ActionListener to the JTextField or the JTextArea class.
7. Rework this example so that your JTextField will have its own actionPerformed routine.
8. If the JTextField is the only user of the second actionPerformed routine, consider using an anonymous class.

Code from Video after doing the exercises above:


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;



public class BasicAction extends JFrame

{
   JTextField tinput = new JTextField("Hi", 60);
   JButton firstButton, secondButton;
   String endline= System.getProperty("line.separator");
   JTextArea toutput = new JTextArea("TextArea class"+endline, 4, 60);

   // ***** Inner class
   class MyAction implements ActionListener
   {
       public void actionPerformed(ActionEvent e) {
            String str = tinput.getText();

            //String buttonLabel = e.getActionCommand();
            Object source = e.getSource();
            String label="";
            if (source == firstButton)
                label="firstButton";
            else if (source == secondButton)
                label = "secondButton";
            else if (source == tinput)
                label = "TextField";

            toutput.append(label + " " +str + endline);


            System.out.println(str);
           }
   }

   // **** end Inner Class


   public BasicAction(String name) {
        super(name);
        setSize(800,400);

        // Construct a Label and add it with one command
        MyAction myAction = new MyAction();

        setLayout(new FlowLayout());
        add(new JLabel("This is a long label ........."));

        add(tinput);
        tinput.addActionListener( new ActionListener()
        {
             public void actionPerformed(ActionEvent e) {
                 toutput.append("Anonymous class code " + endline);
             }
        }

        );

        firstButton = new JButton("Click here to get something done");
        add(firstButton);
        add(toutput);

        firstButton.addActionListener(myAction);

        secondButton = new JButton("Another Button");
        add(secondButton);
        secondButton.addActionListener(myAction);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
     }




  public static void main(String[] args) {
    BasicAction basicAction = new BasicAction("Basic Action");
  } // end of main
}



Last Updated: July 22, 2014 8:32 PM