Building a Java GUI - Containers
Written by Ian Elliot   
Wednesday, 07 November 2012
Article Index
Building a Java GUI - Containers
Using Swing GUI Builder
Obtaining User Input

The Designer Way

The point of the previous example is that you don't need the drag-and-drop editor to create a user interface. Every component and every container is defined by a class and you can create instances of components and add them to instances of containers. In the early days of Java this was the only way to create a user interface.

The drag-and-drop editor makes it much easier but it is important to know that all it is doing is generating the code that you would have written if you didn't use it When you drop a button onto a container it generates the Java that creates an instance of the button and adds it to the containers. It also generates instructions to change the button's position or size or its caption.

You may think that you are using a drag-and-drop designer but you are using it to generate Java.

Let's see how this works.

Creating a new project with a frame object is nothing new - it was how you got started with Java in chapter 1 but this time let's see how it all really works in terms of objects.

Win the project you started earlier add a JFrame Form - right click and select New, JFrame Form. Call the new JFrame MyFrame2.  When the JFrame has been created you will see it open in the designer.  You can add a button in the usual way and change the caption etc just as you have done in previous projects.

 

Frame2

Dropping a button on the form generates the code we used earlier.

 

However now you need to take a look at the code that is being generated. If you click on the Source tab you will see that there is a lot of generated code.

 

editor

Generated code is usually hidden but you can display it by clicking on the + symbols

 

The designer is much more sophisticated and generates code that can detect all sorts or errors and layout situations -hence it is usually longer than what you would write. However, if you look carefully at the start you will see the line:

public class MyFrame2
         extends javax.swing.JFrame {

Yes, that's correct, the designer doesn't simply create an instance of the JFrame class it creates a new class called MyFrame2 which inherits from JFrame.

All of the the components that you drag-and-drop on the frame are added within the class. There is an initComponents method defined which creates instances of all of the components that you added to the frame.

For example, the button that you dropped is created using:

jButton1 = new javax.swing.JButton();

and later on in initComponents it is added to the JFrame.

Don't worry too much about the details. If you did worry about the details there would be little point in using the designer - but you do need to have an idea how it all works.

If you attempt to run the JFrame's file, in this case MyFrame2.java, then there is a main method defined that the program will start of with and this simply creates an instance of MyFrame2 and displays it. Sometimes this is all you need and it is what we have been using in previous projects with a UI.

However MyFrame2 has been created by the designer as a class and this mean we can create instances of the class. So returning to the main program in Container.java i.e. the original project file, we can add a line that creates and instance and shows the new frame:

MyFrame2 frame2=new MyFrame2();
frame2.setVisible(true);

Notice that there is a common problem with the name of the class and the name of the instance i.e. we call the class MyFrame2 and the instance frame2 even though we might want to call it MyFrame2 as well!

If you now run the original program you will see the original frame that we created manually and the new frame that has been created with the help of the designer.

You can have as many windows open at a time as you like - assuming the operating system allows it, Android for example doesn't. You can even have multiple instances of the same JFrame class open at the same time - this is one of the advantages of using and object oriented method.

Dialogs

To illustrate how the designer can be used to create custom containers let's create a small dialog box that does some simple arithmetic - adding two numbers together might not be very useful but it is easy to follow. It also creates a lot of detail that we have to delve into to make it all work.

Working with the same project we started we need to add a dialog box. To do this right click on container under Source Packages and select New,Other and from the dialog box that appears select Swing Gui Forms and JDialog Form. Call the new dialog MyDialog. In the designer add three jTextFields and one button. Use the property inspector to set the initial values and captions to what ever you want to call them. In fact this is a good example to try out your layout skills on - add labels and generally attempt to make the dialog box look good, but do it after you have the program working. 

 

dialog1

Feell free to modify the layout, add labels and generally make it all look better.

 

Next we need to add an event handler that will respond to the button being clicked. To do this the simplest way is to double click on the button in the designer. The designer then adds the code needed to create the event handler and transfers you to the code editor so you can type in some Java.

The idea is that the user will type in a number to the first and second textfields and these are added together and the result displayed in the final textfield. Easy! But there are some irritating details. The first is that the value in the textfield is a string - that is text and not a number that you can add. So first we have to retrieve the text as as string:

String s1=jTextField1.getText();

Next we have to convert it to a number, an integer:

int n1=Integer.parseInt(s1);

How do we know how to convert a string to an integer? You simply have to look it up in the documentation - and knowing such things is what makes the difference between a new and seasoned programmer.

Now we have the contents of the first textfield in a numeric form. Time to get the contents of the second textfield in the same way however instead of writing this out as two lines lets combine the expression into one:

int n2=Integer.parseInt(jTextField2.getText());

This is the way a seasoned programmer attempts to confuse the beginner but we all did this sort of thing as two easier to understand steps the first time around.

Now we can create the sum of n1 and n2:

int n3=n1+n2;

and store this back in the textfield so that the user can see the result. The problem is that n3 is a number and a textfield needs a string to work properly. The solution is once again to use a conversion method:

jTextField3.setText(Integer.toString(n3));

How did we know how to convert an integer to a string? The only way is to look it up in the documentation.

Notice that there is no attempt at catching any errors in the above program. If the user doesn't enter a number then things go wrong. A realistic program would have to check that all input values were reasonable and of the correct type.

The entire button event handler is:

private void jButton1ActionPerformed(
          java.awt.event.ActionEvent evt) {
String s1=jTextField1.getText();
int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(jTextField2.getText());
int n3=n1+n2;
jTextField3.setText(Integer.toString(n3));            
}

 

Now we have a complete dialog box class that does everything we need. All we need to do is display it.

You might think that this was just a matter of creating an instance as with the frame but no. A dialog has to belong to a frame it has to be the child of a parent frame. So what we need is an instance of a jFrame which has a button that the user clicks to create a dialog.  If you go back to MyFrame2 in the designer and add a button you can add an event handler by double clicking on it.

The event handler simply has to create and instance of the dialog box class. It has to supply the name of the frame that is the parent of the dialog and a boolean true/false value to indicate that the dialog is modal or not.

private void jButton1ActionPerformed(
            java.awt.event.ActionEvent evt) {
  MyDialog dialog=new MyDialog(this,true);
  dialog.setVisible(true);    
}

Notice the use of 'this' in the creation of the dialog instance. We need to pass the dialog the jFrame instance that it is the child of and this always refers to the current instance of the class. So when the MyDialog constructor is called 'this' is the name of the instance of jFrame that is creating the dialog.

This is a general idea. Anywhere within a class definition you can use 'this' to refer to the particular instance that the code is running in.

Also notice that the dialog box is set to be modal by the use of true in the constructor. In Java 6 there are four types of ways that a dialog box can be modal rather than just modal v non-modal. - see the documentation.

Finally we need to return to the main program and create an instance of the jFrame class:

public static void main(String[] args) {
  MyFrame2 frame2=new MyFrame2();
  frame2.setVisible(true);
}

Now if you run the project the main method creates frame2 and if the user clicks on the button the dialog box opens and some arithmetic can be done. If the user closed the dialog box then another can be created by clicking the button again. If the dialog box was non-modal and the user closed the jFrame object then the dialog box object would be closed as well.

 

dialog2

 

In a real dialog box it is usually to provide buttons to allow the user to dismiss the dialog box when they have entered some values but for this simple example use the close box in the corner of the window. Dialog boxes usually have OK and Cancel buttons or something similar.



Last Updated ( Wednesday, 07 November 2012 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.