Java Article 9 - Swing Windowed Applications

Welcome to another exciting episode of our Java articles!

Today we will take a quick look at another way to create a windowed application. In article 8 we used the AWT library to create a windowed java app. Here we will use the Swing library.

There are a lot of differences between Swing and AWT. For now just remember Swing has more fancy interface controls (components) like list boxes and Swing lets you do more things with those controls (the controls have more behaviors / functionality).

AWT is not useless: there are times when you would want to use AWT, however swing is newer and you can do more with it.

We are also going to look at controlling the logic of our program with a control structure. Here we will use the mighty if statement.

The syntax for an if statement is as follows:

	//do something

When Java comes to an if statement it evaluates the condition. Conditions evaluate to either true or false. If the condition is true then it executes the code in the braces. If it evaluates false then it skips what is in the braces. So a simple example would be:

If(4 == 5)
	System.out.println("This will only print if the condition is true");

So why the "==" in the condition? Well, one equals sign is used to assign or set things. Such as:

Int myInt = 5;

Two equal signs are a type of comparison operator. So when you see "4 == 5" it is like you are asking "is 4 equal to 5?" 4 is being compared to 5.

The other comparison operators are:

  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
  • != not equal to
So going back to our example when Java reads the first line of

if(4 == 5)
	System.out.println("This will only print if the condition is true");

Java will evaluate the condition inside the parenthesis. In this case 4 is not equal to 5 so this if condition will evaluate to false. Java will skip the println statement and nothing will be printed.

If you wrote:

if(4 < 5)
	System.out.println("This will only print if the condition is true");

The println statement would execute and be printed because 4 is less than 5 (the condition evaluates to true). We will cover some more examples of if statements in the next article so don't worry if you don't understand it all. In today's example we create a simple windowed app with Swing and use if statements to compare the names of buttons to determine which action to take based on which button was clicked.

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

//Swing uses JFrame vs. AWT's Frame
public class SwingExample extends JFrame implements ActionListener

	//here we create two buttons and a label
	//We have to create these here because of how scope works.
	//Since these are not in a method, they are said to be of
	//"class scope" or "instance variables" and these objects can be used
        // or referenced anywhere in this class.
	JButton buttonOne = new JButton("ButttonOne");
	JButton buttonTwo = new JButton("ButttonTwo");
	JLabel label = new JLabel();
	//If you declared these in a method, they would be a method variable
        //or of method scope.
	//If declared in a method they can only be used in that method.
        //That is their "scope"
	//This takes a while to get used to and can be confusing.

	//This is our constructor method it builds the window object
        // and adds the buttons and label to it.
	public SwingExample()

		//setActionCommand allows us to set some text to send to the
		//action listener when the button is clicked. Here each button
		//has its own text so we can later tell them apart with if
                // statements.
		buttonOne.setActionCommand("Buttton 1");
		//Below we tell our Button objects, to link (register)
                // themselves to the action listener.
		//"this" means me or self, and refers to this object.
		//we repeat the process for each button:
		buttonTwo.setActionCommand("Buttton 2");
		//Here we create a Panel. The panel is a invisible 
                //container for our buttons and label
		//later on we add the panel to the window so all 
                //of our button appear in the window.
		JPanel panel = new JPanel();

		//Here we actually add the buttons and label to 
                //the panel container we named "panel"
		//setLayout(new DefaultMenuLayout(LINE_AXIS));
		//setLayout(new BorderLayout(10, 10));
		//setLayout(new FlowLayout());
		//BoxLayout looks interesting

		//This is where the panel is added to the window. 
                //This is done with layout managers
		//which arrange things for us. Here we use a Borderlayout.
		//There are different types of layouts . They get confusing 
                //so dont worrry about them much for now.
		add(panel, BorderLayout.WEST);


	//When we click our buttons, the buttons send their
        // action command text (and a bunch of other information) here.
	public void actionPerformed(ActionEvent e)
		//look at your console when you click a button.
		//This is all the information being passed to the parameter e
		//Look at the data. Depending on which button yon push you
                // should see "cmd=Buttton 2"
		//or "cmd=Buttton 1". This is the text we set with 
		//Here we get the action command (Buttton 1 or Buttton 2)
                // out of all that data that makes up e.
		//Then we put this action command into a string we call cmd.
		String cmd = e.getActionCommand();

		//Here are our if statements. If ButtonOne was pressed, 
                //cmd = "Buttton 1". if ButtonTwo
		//was pressed this first if statement will be skipped, 
                //and the second if statement will then be evaluated.
		if (cmd == "Buttton 1")
                        //This sets the label's text
                        label.setText("ButttonOne Was Clicked");

		if (cmd == "Buttton 2")
			label.setText("ButttonTwo Was Clicked");
		//If neither buttonOne or ButtonTwo were clicked then 
                //nothing happens here and our object will
		//just sit and wait and listen for us do do something.

	//Remember, main is run first when we run this class.
	//Main creates our object swingExampleObject from our
        //class, SwingExample.
	public static void main(String[] args)
		SwingExample swingExampleObject = new SwingExample();
		//This is our window size in pixles: 400 wide by 75 high.
		swingExampleObject.setSize(400, 75);
		//This makes the window visible. If you don't include 
                //this you will have an invisible/unusable window!

Compile and run this. Now is your chance to do what programmers spend a lot of time doing: Looking at a program and trying to figure out what is going on.

Launching the application creates an instance of SwingExample. The instance is an object we interact with. Clicking either button triggers actionPerformed(), and then our two if statements determine what text to display in the label.

Not too complex is it? In the next article we will do more with Swing, and experiment with more if statements.