JavaK

 

presents

 

Graphical User Interface (GUI) Primer

 

1st Edition, updated 7 March 2012

 

 

 

 

Table of Contents

Introduction        1

About Me and how this tutorial came to be        2

Let's dive right in        3

First things first – What is a JFrame() ?        3

Building your first JFrame()        4

Adding a JButton        6

Adding several items to the container        7

Introducing FlowLayout        9

Making a button work        11

Putting Action Listeners to work        13

What about asking for user input?        14

Playing with GUI components        18

Setting background and foreground colours        18

Changing the font attributes of a component        19

Changing mouse cursors        20

Adding borders to your components        21

Wait, this can't be it? Right?        21

Grouping your components together        22

Grouping components using JPanel        22

Putting it all together        23

Copyright Notice and Disclaimer        27

Copyright         27

Disclaimer        27

 

Introduction

 

If you are a beginner Java programmer, or have never used Swing before, you will find this a useful primer indeed. We will start with the simplest of Graphical User Interface (GUI) concepts and end up building a solid foundation for your future GUI adventures.

 

Each chapter builds on the previous chapters, so I would recommend that you follow the book in the order it was written. That being said, I did try to split the tutorial into related sections, so you can start at the chapter that interests you if you have some previous GUI experience.

 

Tools used to create this ebook:

 

All source code for this PDF book is availabe on the website www.javak.co.za/tutorials/guiprimer

and you are welcome to download it if you do not wish to type out every example yourself.

 

If you have any comments, suggestions, corrections or proposed mini-tutorial ideas, you are welcome to email me, Ewald Horn, directly at info@javak.co.za

 

 

 

 

 

 

 

 

 

 

 

 

 

 

About Me and how this tutorial came to be

 

I've been programming in Java since 1997, and have been involved in the lecturing and training world since 1999. During this time I have developed a significant amount of training material, especially in the Java world. Some of this information has been released on the internet, but I have never been happy with the material and only used it in my classes. My goal was always to supplement the textbooks I had in classes and never to write a tutorial from scratch.

 

In 2008 I released a Java SQL mini-tutorial in PDF format that went on to become a very popular download even though it was created in record time when I needed something for an extra class. Feedback from students, teachers and Java enthuasists led me to realise that there is a demand for more such small, dedicated tutorials.  Late 2009 I decided to release another small tutorial and opted to go for a basic GUI tutorial as that was what most people were asking for.

 

I hope that this tutorial will be as successful as the SQL tutorial and that it will be of use to Java students around the world, but, more specifically, in South Africa. I believe that we have many passionate and dedicated educators in South Africa, that, with the right resources, can help us catch up to the rest of the world in technology matters.

 

A BIG thank you to the IT teachers that are committed to empowering our youth with IT knowledge and helping them to become global competitors. Over the past four years, I have had the honour of being part of this community and I am overjoyed to be presented with an opportunity to give something back.

 

Let's dive right in

 

The traditional approach followed in almost any programming example is, of course, the famous "Hello, World!" program. I'm going to do this a little bit differently and show you how to do this using a graphical interface.

 

At the end of this chapter, you will be able to:

 

 

First things first – What is a JFrame() ?

 

Simply put, the JFrame() object that we will be using is the primary container for our GUI components. Think of it this way: Each GUI object (button, label, picture etc.) needs to be stored in some kind of container, and JFrame() is such a container.

 

In the example below, you see a frame with a few graphics components in it. The surrounding frame is the JFrame(), with the buttons and labels being the GUI components.

 

 

 

 

Building your first JFrame()

 

Let's get down to the code. In this example, we will be building a blank JFrame object that we will display on the screen.

 

This simple JFrame will form the foundation for the rest of our work with JFrames. The source is below, or you can download it : JFrameOne.java

import javax.swing.*;

public class JFrameOne extends JFrame {

    public JFrameOne()

    {

        setTitle("JFrameOne");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

    }

    public static void main(String args[])

    {

        JFrameOne jfo = new JFrameOne();

        jfo.setVisible(true);

    }

}

 

So what exactly is going on here? Probably the only thing you recognise right now is the main() method! Let's go through the code, line by line:

 

First, we need to tell the Java compiler that we will need to import the Java Swing libraries. A shortcut is to import the javax.swing.* which includes all the Swing components. The javax part is the Java extensions package. Swing was not originally part of Java and is an extension to the initial releases.

 

Now we get to an interesting part : public class JFrameOne extends JFrame { :

The extends JFrame is a great example of OOP development. OOP stands for Object Orientated Programming and makes your life a lot easier. Instead of having to write your own JFrame object, which can be a very difficult exercise, you get to piggy-back on the work done for you by the developers of Java. You will find many examples of how OOP saves you time when you start working with Swing, in fact, it would be a whole lot more difficult if Java was not OOP!

 

The extends keyword allows us to inherit all the methods and attributes of the JFrame() object. In the constructor for the JFrameOne class, you will see that I call the setTitle() method, but there is no such method in my class! Yet it compiles and runs perfectly? The explanation is that this particular method exists in the JFrame class, the one we are extending. So, we get all the code from the JFrame class without doing any of the hard work.

 

Next up, we have the JFrameOne() constructor, where we call three methods. The first one sets the title of the window that we will be displaying. Next is a very important method call. The default close operation is used to tell Java what to do when the window is closed. In this case, we want the program to exit when the main container is closed. Later on, you will run into situations where you want the window to remain availabel, even after it has been closed by the user. Lastly, we set the size of the window, in pixels.

 

The main method creates a new instance of our JFrameOne class and then calls the setVisible() method to display it on the screen. We have to create a new instance of our class, because defining a class is simply creating a blueprint of what you want the object to look like. Why on earth would we do this? Consider the following modified example: JFrameTwo.java

import javax.swing.*;

public class JFrameTwo extends JFrame {

    public JFrameTwo()

    {

        setTitle("JFrameTwo");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

    }

    public static void main(String args[])

    {

        JFrameTwo jfa = new JFrameTwo();

        jfa.setVisible(true);

        JFrameTwo jfb = new JFrameTwo();

        jfb.setVisible(true);

    }

}

 

Instead of closing the window, drag it away. You will now see TWO windows! This is because we created two objects of the type JFrameTwo and displayed both on the desktop. What's interesting here is that BOTH windows close when we close either of them. That's because we set the default close operation for both of them to be EXIT_ON_CLOSE, forcing the application to quit if either window is closed.

 
 

Adding a JButton

 

Being able to display a blank window is, well, quite boring. How about we add a button to the mix? We will be creating the following window in this section:

 

It doesn't look like much, but this window has a button in the centre, which takes up all the space in the window! We will sort out that a bit later, but first, let's see how we got the button there.

As usual, the source code is available online: FirstButton.java

import javax.swing.*;

public class FirstButton extends JFrame {

    private JButton closeButton;

    public FirstButton()

    {

        setTitle("FirstButton");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

        closeButton = new JButton("Close");

        add(closeButton);

    }

    public static void main(String args[])

    {

        FirstButton btn = new FirstButton();

        btn.setVisible(true);

    }

}

 

Not a lot has changed, right? The first thing is we added a new private variable called closeButton that is of the type JButton. Just like JFrame, we reuse object types that are included in the Swing libraries in Java.

 

In the constructor, after doing the usual things to get the window ready to be displayed on the screen, we add two new lines. First, we initialise the button object and give the constructor a String parameter. This is the text we wish to have appear on the button when it is displayed. Secondly, we add it to the JFrame object. We will dive into this in just a while. For now, I just want you to see how easy it is to add a button to a frame.

 

Let's move on and see how we can add more items to the container.

Adding several items to the container

 

In our previous example, we saw how to add a single button to a window. This might be a good exercise to start with, but it doesn't really have any real-world application, right? Adding several items to a container though, could have a potential problem. We need a way to tell Java where to put these items on the container.

 

The basic Java layout, used by most containers be default, is the BorderLayout. It has five basic positions, as highlighted by the next example. Notice the American spelling.

 

 

NORTH

 

WEST

 

CENTER

 

EAST

 

SOUTH

 

 

 

Let's put this into practice with some source code. In our next example, we are going to build the following window. Just to really mix things up, we are also going to add a JLabel to the mix.

 

 

So in this example, we add two buttons and a label to the window. We also specify where we want these components to go.

 

Button A is CENTER.

Button B is EAST.

A Label is SOUTH.

 

 

 

The source code can be found at BorderLayoutTest.java

import java.awt.*;

import javax.swing.*;

public class BorderLayoutTest extends JFrame {

    private JButton aButton, bButton;

    private JLabel aLabel;

    public BorderLayoutTest()

    {

        setTitle("BorderLayoutTest");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

        setupComponents();

    }

    private void setupComponents()

    {

        aButton = new JButton("Button A");

        bButton = new JButton("Button B");

        aLabel = new JLabel("A Label");

        add(aButton, BorderLayout.CENTER);

        add(bButton, BorderLayout.EAST);

        add(aLabel, BorderLayout.SOUTH);

    }

    public static void main(String args[])

    {

        BorderLayoutTest blt = new BorderLayoutTest();

        blt.setVisible(true);

    }

}

 

To use BorderLayout, we need to import the java.awt.* package. This package is the predecessor to the Swing package and contains many utility classes we will use later.

 

In the constructor, I opted to move the creation of the components to a seperate method. This cleans up the constructor and makes the code easier to read. First, we create the buttons and the label. Once the objects exist, we add them to the JFrame container. This time, when we add the components, we specify where we wish them to go.

The basic locations for BorderLayout are:

 

Introducing FlowLayout

 

BorderLayout is not the only layout option you have. Another one that you will be using frequently is FlowLayout. Unlike BorderLayout, FlowLayout lays out components in a row, "flowing" with the shape of the container you are using. Let's start of with our previous example modified to use FlowLayout instead of BorderLayout. This is what it will look like:

 

We reuse almost all of our previous code, with a few exceptions, highlighted here. The source code can be downloaded from the JavaK website : FlowLayoutTest.java

import java.awt.*;

import javax.swing.*;

public class FlowLayoutTest extends JFrame {

    private JButton aButton, bButton;

    private JLabel aLabel;

    public FlowLayoutTest()

    {

        setTitle("FlowLayoutTest");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

       

        setLayout(new FlowLayout());

        setupComponents();

    }

    private void setupComponents()

    {

        aButton = new JButton("Button A");

        bButton = new JButton("Button B");

        aLabel = new JLabel("A Label");

        add(aButton);

        add(bButton);

        add(aLabel);

    }

    public static void main(String args[])

    {

        FlowLayoutTest flt = new FlowLayoutTest();

        flt.setVisible(true);

    }

}

 

In this example, we specify the layout we want using the setLayout() method. We then change the add() method calls to NOT include a specific position as the layout manager will handle the positioning of the components.

The FlowLayout manager can also be customised to put larger gaps between the components or change the layout direction, using different parameters during initialisation.

 

Let's change our example to now place all components towards the CENTER of the container. For this we will also need a larger container to illustrate the effect better. Instead of retyping all the code, simply change your constructor in FlowLayoutTest.java to look like this:

    public FlowLayoutTest()

    {

        setTitle("FlowLayoutTest");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(400,100);

       

        setLayout(new FlowLayout(FlowLayout.CENTER));

        setupComponents();

    }

 

When you run this example, you should see a window like this:

 

There are several other layout managers that you should explore as well. We will be concentrating on the BorderLayout and FlowLayout managers in this guide, but you are free to expirement with the other ones included in the Java Runtime Environment:

 

Layout Managers

 

Making a button work

 

It's all good and well to be able to display a button, but it's quite boring if it doesn't do anything!

 

In this section, we take a look at responding to button events. The first event we look at is a simple click on the button. We are going to reuse our first button example and modify it to look like this:

 

Not much difference, is there? But when you run the program, and click on the Close button, you will see that the program now behaves as expected and closes. So something must have happened in the background.

 

Now it's time for a little bit of theory, yuck. GUI applications usually respond to different user events. These events are called actions in Java. So, in order for us to listen for a click on a button, we need to listen if a user performed an action on the button. This can be quite a complicated procedure to program, but, as usual, the Java creators have come to our rescue and included a bunch of classed we can use for this purpose in the java.awt.event.* package. So we simply import this package into our application and then we can start using something called an ActionListener.

 

We can add an ActionListener to a button and then tell it what to do when an action is performed. Java allows us to distinguish between different types of actions, but for this example we will respond to any action.

 

Any action performed on the Close button will call a method specified by us. In this case, I opted to call my action method doSomethingHere() and all it does is call the System.exit(0) method, closing the application down.

 

There is of course more than one way to add an action event to a button, but for now, this is the simplest way to do it. In later examples we will examine other techniques and even take a look at how these events can be monitored on other components. For example, you can even check if someone has clicked on a JLabel, not something you do very often, but at times it is fun to use JLabels or even images as buttons instead of standard buttons.

 

The source code for this example is on the next page.

Here's the source code, with the important changes highlighted. The full source code for this example can be downloaded from the website : SecondButton.java

import java.awt.event.*;

import javax.swing.*;

public class SecondButton extends JFrame {

    private JButton closeButton;

    public SecondButton()

    {

        setTitle("SecondButton");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

        closeButton = new JButton("Close");

        closeButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent evt){

                doSomethingHere();

            }

        });

        add(closeButton);

    }

    private void doSomethingHere()

    {

        System.exit(0);

    }

    public static void main(String args[])

    {

        SecondButton btn = new SecondButton();

        btn.setVisible(true);

    }

}

 

The highlighted sections are the most important in this example. First, we tell Java that we want to import the java.awt.event.* package so that we can use action listeners.

 

Then, after we have created the closeButton, we add an ActionListener to the button.  We tell Java that we'd like the doSomethingHere() to be called whenever an action is performed on the button.

 

Finally, we declare what the doSomethingHere() method should do when it is called. In this case, we simply wish to exit the program.

 

That's it. Now you can add action listeners to buttons and make them do something. I think it's time we put all of this knowledge together and write a little program that will actually do something usefull.

 

Putting Action Listeners to work

 

By now, we can create a window, add a button to it and respond to clicks on the button. It sounds as if we have most of the basic components needed to create functional little program. Now, finally, we get to the "Hello, World!" program.

 

Let's create something like this:

 

And when you click on the Say Something button, the following window appears:

 

There we go!

 

Now we have created a top-level container, in this case, a JFrame object, set the layout to FlowLayout and added two buttons. Each button listens for an action event and then performs a particular action when clicked. We even have the program display a message.

 

In this example we not only mix up some of what we have learned up untill now, but we also introduce the JOptionPane.showMessage() method. This handy utility class makes it a lot easier for you to display messages in simple dialog boxes. Later on, we will take a look at how you can ask the user for input or ask for a particular response, all using this handy utility class. It is little short-cuts like this that can make your life a lot easier when you are writing Java programs and you should make time to read the official Java documentation about JOptionPane if you want to take full advantage of it.

 

Experiment with the program by changing the message being displayed and also by adding your own button that displays a seperate message. The best way to learn about GUI development is to alter existing code and observing the changes. GUI developmenr is a very visual experience and it takes a lot of experimentation to get the right look and feel for your programs.

 

The source code for the application follows, and, as usual, is available online : HelloWorld.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class HelloWorld extends JFrame {

    private JButton goButton,closeButton;

    private HelloWorld()

    {

        setTitle("HelloWorld");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

        setLayout(new FlowLayout());

        closeButton = new JButton("Close");

        goButton = new JButton("Say something");

        closeButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent evt){

                closeProgram();

            }

        });

        goButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent evt){

                sayHello();

            }

        });

        add(goButton);

        add(closeButton);

    }

    private void sayHello()

    {

        JOptionPane.showMessageDialog(this, "Hello, World!");

    }

    private void closeProgram()

    {

        System.exit(0);

    }

    public static void main(String args[])

    {

        HelloWorld hello = new HelloWorld();

        hello.setVisible(true);

    }

}

 

The only new thing is the JOptionPane.showMessageDialog() bit. It takes two parameters, the first is the parent container (which is this, our JFrame object) and the message to display. Easy, hey?

 

What about asking for user input?

 

So responding to a user clicking a button is one thing, but what do you do if you want the user to give you an answer that is not predictable? Let's change our program slightly to ask the user for their name and then have the program greet the user, using this new information.

 

First, we have our standard looking window:

 

Then, when you click on Custom Greeting:

 

And finally:

 

This simple little program asks for input, handles possible problems with the input string and then finally uses this information to display a custom message. Using these techniques you can quickly ask a user to input some text and then process it.

 

Remember that when you ask the user for an input string that they might click OK on a blank string, or click the Cancel button, which will return a Null string. In our application, we test for both of these conditions and handle them. If the user clicks Cancel, the input name is changed from Null to "Goodfella" and if the user clicks OK on an empty string, it is changed to "Shorty".

If you don't do this, you can end up running into some nasty exceptions later on when you try to use the string and it is not initialised.

 

The source code for HelloWorldAdvanced.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class HelloWorldAdvanced extends JFrame {

    private JButton goButton,closeButton;

    private HelloWorldAdvanced()

    {

        setTitle("HelloWorldAdvanced");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setSize(240,100);

        setLayout(new FlowLayout());

        closeButton = new JButton("Close");

        goButton = new JButton("Custom Greeting");

        closeButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent evt){

                closeProgram();

            }

        });

        goButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent evt){

                sayHello();

            }

        });

        add(goButton);

        add(closeButton);

    }

    private void sayHello()

    {

        String theName = "";

        theName = JOptionPane.showInputDialog("Who goes there?");

        if (theName == null)

        {

            theName = "Goodfella";

        }

        else

        {

            if (theName.isEmpty())

            {

                theName = "Shorty";

            }

        }

        JOptionPane.showMessageDialog(this, "Hello, " + theName);

    }

    private void closeProgram()

    {

        System.exit(0);

    }

    public static void main(String args[])

    {

        HelloWorldAdvanced hello = new HelloWorldAdvanced();

        hello.setVisible(true);

    }

}

 

In the highlighted section, we first create a variable called theName of the type String. We then use the JOptionPane.showInputDialog() method and assigned the returned value to theName. We then test for a null string, or, if it's not null, whether the string is empty. We finally output the value using the showMesssageDialog() method in JOptionPane.

 

So what to do if you want a simple Yes/No answer from the user? The Java designers anticipated this as well and they included a neat little method in JOptionPane to do just that. Consider the following code : AreYouSure.java

Import...

public class AreYouSure extends JFrame {

    private JButton closeButton;

    private AreYouSure() {

        setTitle...

    }

    private void closeProgram() {

        int result = JOptionPane.showConfirmDialog(this,

                                              "Really quit this program?",

                                              "Please Confirm",

                                              JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {

            System.exit(0);

        }

    }

    public static void main(...

}

 

I cut out some of the standard code, and you can view the full source code at the website. The section we are interested in is highlighted.

 

The showConfirmDialog() method returns an integer value that contains the value of the selected option. To test for the response, we save it in a local variable called result. Then we test if the result was the YES option, if so, we exit the program.

Playing with GUI components

 

Now that we can actually do something with buttons, we should start to have some fun with them, don't you think?

 

We will be learning how to :

 

Setting background and foreground colours

 

First, we are going to create a little window that looks like this:

 

Since you should be able to create this entire window on your own by now, I will only show you the single line of code you need to include to set the button background color to orange.

 

        closeButton.setBackground(Color.ORANGE);

 

That's quite easy, isn't it? All that you need to do is call the setBackground() method on the button that you have created, specify the colour you want and Java does the rest. This is of course not limited to buttons, but you can change other components this way as well. We will be taken a closer look at JLabels soon, that becomes quite interesting.

 

Java has a couple of predefined colours that you can use, just remember that Java follows the American spelling convention, so colour is "color" in American English.

 

Here are some of the more popular colours:

BLACK

 

MAGENTA

 

BLUE

 

ORANGE

 

CYAN

 

PINK

 

DARK GRAY

 

RED

 

GRAY

 

YELLOW

 

GREEN

 

WHITE

 

LIGHT GRAY

 

 

 

 

Colours on your monitor might differ, but these are the basic colours you can rely on in Java. You can also create your own specific colour using the Color class. More on that later.

 

If you can set the background colour, then surely you can change the text color on a button, right? Well, let's see how that gets done in Java. The following effect can be obtained by adding another line to the program you just wrote:

 

        closeButton.setForeground(Color.RED);

 

This line sets the text color to RED, so now you have red text on an orange background.

 

 

 

Changing the font attributes of a component

 

GUI components that display text have some font attributes that you can manipulate. Let's see how we can create the following look:

 

In this example, we reused the Colours example and simply changed the font attributes for the closeButton.

 

Let's take a look at the source line we changed:

        closeButton.setFont(new Font("Arial", Font.ITALIC, 20));

 

As you can see, GUI components have a setFont() method you can use to change the font used to display text. The method takes three parameters:

  1. 1.The name of the font you wish to use 

  2. 2.The style of the font (Bold, Italic,Plain) 

  3. 3.The size of the font 

 

To display a particular font, it has to be installed on your system.

 

 

Changing mouse cursors

 

Most GUI components allow you to change the mouse cursor associated with them. Try adding the following line of code to your program:

closeButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

 

When you run your program again, and move the mouse over the closeButton, you will see the cursor changes to a hand cursor. This happens because we told Java to not use the standard cursor, but rather the new cursor object we created. We specified that we want to use a HAND_CURSOR using the parameter of the Cursor object constructor.

 

The more popular cursor options are:

 

 

Adding borders to your components

 

Before we get into the more advanced GUI design concepts, we have one more little thing to learn.  Java allows you to add different borders to you components.

 

        yourComponent.setBorder(BorderFactory.createEtchedBorder());

        yourComponent.setBorder(BorderFactory.createLineBorder(Color.RED));

 

That's it. It's quite a simple process and we will see it in action in the next section.

 

 

Wait, this can't be it? Right?

 

Don't worry. All I wanted to do up until now was to make sure you have a basic understanding of the most common GUI components before we really get into GUI development.

 

You should now be able to:

 

That's quite a bit you have learned up untill now! So now that you have all this knowledge, we should put it all together and create our first proper program. From here on the examples will become more complicated, but with the knowledge gained through the previous chapters, this should not be much of a challenge for you.

Grouping your components together

 

This chapter puts all of your knowledge together to create a more complete GUI than what we have previously looked at. At the end of this chapter you will know how to:

 

 

Grouping components using JPanel

 

When you are designing a GUI layout, you will often want to group different components together and make use of several layout managers.

 

We are going to take a look at a different container now. In all our previous examples, we made use of the top-level container (JFrame) for our layout needs. What do you do if you want to use both the BorderLayout and FlowLayout on one GUI window? Java gives you the option of splitting your display area into different sections called Panels. Consider the following example:

 

 

Here we have three sections, each with a couple of buttons. As you can see, we combined several layout managers to get this look. The buttons were all done with FlowLayouts, and the different coloured panels using BorderLayout. This can be done, because each section is actually an individual JPanel component, another type of container.

 

That's not the only way to use JPanels either. Remember those borders? In the next example, we add some borders to the panels.

 

 

In this example, we added an EmptyBorder to the top panel, a LineBorder to the left panel and a TitledBorder to the right panel.

 

 

Putting it all together

 

Let's put all of this together, creating a simple GUI that combines most of what we have learned throughout the previous chapters.

 

We will be creating the following application:

 

It has two working buttons, two labels, a few panels and even a couple of empty borders to make it look just a bit more presentable. When the user clicks on the "What is 5 + 1" button, they are presented with a dialog box that asks them to enter the question. Depending on the answer, they will be presented with a different message. This example also includes some basic error handling, nothing fancy, but it does make the program a bit more robust.

 

The source code for : SimpleMath.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SimpleMath extends JFrame {

    private JPanel topPanel, centerPanel, buttonPanel;

    private JButton closeButton, askButton;

    private JLabel answerLabel, nameLabel;

    public SimpleMath() {

        setTitle("SimpleMath");

        setSize(320, 140);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

        setupComponents();

        addActionListeners();

    }

    private void setupComponents() {

        topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        centerPanel = new JPanel(new BorderLayout());

        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        topPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        centerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        closeButton = new JButton("Close");

        askButton = new JButton("What is 5 + 1?");

        answerLabel = new JLabel("Tip : It's between 5 and 7...");

        nameLabel = new JLabel("Welcome to SimpleMath!");

        topPanel.add(nameLabel);

        buttonPanel.add(closeButton);

        buttonPanel.add(askButton);

        centerPanel.add(buttonPanel, BorderLayout.CENTER);

        centerPanel.add(answerLabel, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);

        add(centerPanel, BorderLayout.CENTER);

    }

    private void addActionListeners() {

        closeButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {

                handleCloseButton();

            }

        });

        askButton.addActionListener(new ActionListener() {

           public void actionPerformed(ActionEvent event) {

               handleAskButton();

           }

        });

    }

    private void handleCloseButton() {

        System.exit(0);

    }

    private void handleAskButton()

    {

        String inputText = JOptionPane.showInputDialog("So what is 5 + 1?");

        if (inputText != null)

        {

            if (inputText.isEmpty() == false)

            {

                if (inputText.compareTo("6") == 0)

                {

                    JOptionPane.showMessageDialog(this, "Excellent!");

                }

                else

                {

                    JOptionPane.showMessageDialog(this, "Oops! Try again!");

                }

            }

            else

            {

                JOptionPane.showMessageDialog(this, "The answer is not blank!");

            }

        }

        else

        {

            JOptionPane.showMessageDialog(this, "Chicken!");

        }

    }

    public static void main(String args[]) {

        SimpleMath mathApp = new SimpleMath();

        mathApp.setVisible(true);

    }

}

 

This is our longest program yet, just under a hundred lines of Java! Yet, by now, it should be fairly easy for you to go through the program and figure out what it does. I've added a short explanation of some methods below, but see if you can figure it out on your own before looking at it.

 

Try to summarise each section of code and figure what happens where. This is a great opportunity for you to play around with the code and try to change things around. How about adding a button that displays the hint in a seperate dialog instead of on the hint label. Or how about changing some of the fonts on the GUI components?

 

Here's my description of some of the important sections of code.

 

Short description of some code sections:

 

There you have it, a complete example of a basic, but functional GUI application.

Copyright Notice and Disclaimer

 

The legal speak. No ebook is complete without it, it would seem.

 

Copyright

This work is copyrighted by Ewald Horn and you are free to use it for educational purposes only. Copies (electronic or print) may be made as you see fit, as long as the author is credited for his work in your derived work or copy.

 

 

Disclaimer

As this guide is released free of charge, the author accepts to responsibility for any damages that might be incurred through the direct or indirect use of the document.