QuestionQuestion

Creating Graphical User Interfaces can be complex and ridden with little nuances that often escape the new GUI developer. Especially when using an IDE to develop code, the ease of point and click graphics and widgets can appear simple to the user but in fact, behind the scenes, the IDE is actually generating a lot of support code. Netbeans has an awesome built in GUI editor that is WYSIWYG but the code it generates is hard to read and even harder to maintain. However, it does make generating a GUI fairly quick and painless once you know a few little tricks. So this week, you are going to use the class notes which will walk you through generating one small piece of your application using the built in GUI editor and one other small piece without the editor. After you complete both of these exercises, you will have the beginning of a user interface for your application. Once you have had a chance to try both methods of generating user interface code, you can decide which method you will use to complete the user interface. You can use just one or a combination of both. Since both methods generate Java class files, they will all be able to work together, regardless of the method you used to generate them. Although it takes more time to generate code by hand, one big advantage to creating your classes without the use of the WYSIWYG editor is that you have written all the code yourself so it will be easier to read, understand and maintain.
Attached to this lecture is a link to a video tutorial that demonstrates using the Netbeans built in GUI editor to generate a class that will be used for a user interface. This tutorial will walk through creating an input form for adding classrooms and a report form for viewing available classrooms. I suggest tackling one method for generating GUI code at a time, to completion before trying the second method. I will leave it up to you to decide which method you will try first.

Chapter 11 in the text book describes how to design a graphical user interface using the built in Java classes in the the library known as "Swing". There are hundreds of third party libraries that can be used to generate a user interface. I have chosen the Swing library because it is built into the language and there is a lot of support for it. Also, the built in Netbeans GUI editor provides a toolkit of all the widgets and controls in the Swing library. Chapter 11 also goes into great detail regarding the event handling in the UI. We won't be tackling event handling this week so you are welcome to skip over those sections for now and focus on generating the windows.
There's a lot to learn in Swing. Don't worry if you feel a bit overwhelmed by it. You aren't expected to become a Swing expert in six weeks. But you will become familiar with the basic Swing classes you will need to develop a simple GUI application that you can build on later.
The online notes are intended to supplement the text book and provide another example in addtion to the source code from the text book.
Attached to this week's homework assignment is a sample application which you can use to get started. This starter code will have the input and report windows implemented for a single class type, both using the Netbeans GUI editor as well as created manually

A Little GUI History


Java was first released with a set a classes that allowed a programmer to create portable GUI applications. This set of classes is called the Abstract Windowing Toolkit (AWT). The AWT was not well received by the developer community because it was buggy and did not allow the development of a rich graphical interface.

AWT uses the current operating system's native set of graphical components. Since all platforms did not support the same set of GUI components, the AWT could only support a subset of all of the graphical components available. As a result many of the fancy and powerful graphical widgets were left out of AWT. It was clear that a better graphical framework was needed. As a result, the Java Foundation Classes (JFC), better known as Swing, was created and included as part of the JDK (starting with version 1.2).

Swing was implemented differently than AWT. Instead of relying on the underlying operating system to provide the graphical widgets, Swing creates all of its widgets from scratch. This allowed Swing to support a full set of widgets because it did not have to restrict itself to the least common set. In addition, the look and feel of its widgets could be the same on all platforms. The drawback to this approach is performance. Since Swing is responsible for drawing all of its components, it is slower then AWT. However, many recent improvements and faster hardware are making Swing faster each and every day.

So which GUI framework should you use? Until recently, applets written using Swing were almost guaranteed not to run properly in web browsers.    Because of this, applets continued to be developed using AWT which limited their look and feel. Today, this is not usually a factor since most web browsers can support Swing and since applications written in Swing are much richer visually, it makes sense to program in Swing. One caveat, the underlying event handling mechanism which Swing uses is still based on the original event handling classes in the AWT. The developers of Swing didn't implement a new set of event handling classes. Therefore, it is imperative that you learn about the AWT even if you aren't planning on implementing AWT graphical components.

Let's get started with the concept of Containers by learning about the most important one, the JFrame


Report Card Application


The best way to learn GUI programming is by looking at examples. So let's get started with an example. If you remember back in the collection lecture we created some code that would generate a grade for a student and print their grade. What if we were to create a graphical front end for this code so that we could add the grades via an input window and then display the grades in a report window? The goal of this lecture is to build a graphical user interface for this report card program. Download the source code here.


The first step in building a GUI application is to create a main window. In Swing, a main window is called a frame. The Swing class we will use is the JFrame. To build a main window for our report card application we need to import the associated Swing packages, and then create a class that extends the Swing JFrame. Let's get started by creating a class called ReportCard.

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

public class ReportCard extends JFrame {



public static void main(String args[]) {
ReportCard frame = new ReportCard();
}

public ReportCard() {

// Initially set the frame to 400x400 pixels wide.
// The user can resize the frame later if they like.
setSize(400,400);

// Set the title of the frame
setTitle("Report Card Maker - UML Java Course");

// make the frame visible
setVisible(true);
}
}



As you can see most of the interesting code that generates the window is in the constructor. The constructor sets the initial size for the frame, sets the frame's title, addes visual elements to the windows, and finally it displays it. All of this is done by calling methods that were inherited from the JFrame class. The class above doesn't have any visual elements yet. If you were to run this class, all you would see is an empty window. The next section will demonstrate adding elements to the window.


It is now time to add some user interface Components to our main frame. In Swing, Frames are Containers and Containers "contain" Components. There are many user interface Components that are part of the Swing library. The Components we will need for our report card depend on the program's input and output requirements.

The report card program takes two inputs: the name of a student, and a set of grades. Well, technically, the set of grades is actually 5 individual text inputs for the sake of simplicity, we will think of the grades as a single set. In our user interface, we can allow the user to specify these inputs using the Swing library JTextField class. In addition, we can add a button that the user can click on in order to generate the final grade. Finally, our report card program can display the final grade in the main window. Here is a mock up of what our application will look like:



In summary, we will need the following user interface Components:

    Name input field - this will contain the name of the student. It will be represented using a Swing JTextField.
    Grade input fields - these will contain the input grades. They will also be represented using a Swing JTextField.
    Button - the user can click on this button to generate the final grade. It will be represented using a Swing JButton.

The window will initially display with a default size but the user can make the window larger or smaller. Although your Components may move around, their relative locations always remain the same. This is the result of using layout managers to manage window sizing events. Layout managers are Java classes that are created and attached to JFrame and JPanel objects and are used to manage their display properties.

This functionality was added to Swing in order to make Java applications more portable. LayoutManagers make it easier to build screens that adjust based on the current screen resolution. Much like HTML, a Java interface screen can adjust on the fly based the current platform's display properties. In addition to making applications more portable, LayoutManagers can also make it easier to create well organized interface screens.

LayoutManagers are another good example of how Design Patterns are used in Swing. LayoutManagers are an excellent example of the Strategy pattern. In the Strategy pattern a family of algorithms can vary independently from the clients that use them. By plugging in different strategies for laying out a container's contents, you can change the layout without affecting the rest of the code.

Java comes with several different types of LayoutManagers. In this lecture we will be looking at the BorderLayout. BorderLayouts allow you to add Components to the north, south, east, west, and center regions of a Container. As the Container resizes the Components remain "glued" to the specified region. The BorderLayout is my favorite layout manager becuase it is powerful and easy to use.

You can specify a Container's LayoutManager by calling the setLayout() method. In order to get our main window to use a BorderLayout all we have to do is add one line to the constructor.

    public ReportCard {
       addWindowListener(new FrameExitHandler());
       setSize(400,400);
       setTitle("Report Card Maker - UML Java Course");
      
       setLayout(new BorderLayout());
      
       setVisible(true);
    }

The real power of layout managers can be achieved when you combine them with JPanels. JPanels can be used to split a Container into sections just like our report card program contains a panel for the output and a panel for the input. This can be done by adding a JPanel to a specific region of a Container. The best way to demonstrate this is with an example. Let's start by dividing our main window into two sections, a center section and a bottom section. We can do this by adding two JPanels to our main window.

       // Create the input panel that will contain the student name and the grades
       // and the button
       JPanel inputPanel = new JPanel();

       // Set the layout of the panel to be a grid with one column and 7 rows
       inputPanel.setLayout(new GridLayout(7, 1));

       // Add the panel to the window
       getContentPane().add(inputPanel, BorderLayout.CENTER);

       // Create the panel that will contain the final grade output
       JPanel finalGradePanel = new JPanel();

       // Set the layout of the panel to be a grid with one row, 1 column
       finalGradePanel.setLayout(new GridLayout(1, 1));

       getContentPane().add(finalGradePanel, BorderLayout.SOUTH);

Notice that we create the JPanel, set its layout manager and then we add the JPanel to the appropriate region of the main window. These methods should be called from the constructor.

Notice how we created two new JPanels and we added them to the northern and southern regions of the topPanel. This essentially divides the top red panel into two sub-sections, a green one to the north and a yellow one to the south.

Adding Elements


Now that we have the JPanels added to our window, it's time to add the elements. The input and ouput text fields and the button.


As I mentioned in the last section, the report card program takes 2 inputs, a student name, and a set of grades and outputs a final grade. The first thing we need to do is to declare all the elements that will be on the form. We do this at the top of the class file with the following:

    JTextField name;
    JTextField grade1;
    JTextField grade2;
    JTextField grade3;
    JTextField grade4;
    JTextField grade5;
    JTextField finalGrade;
    JButton generateGradesButton;

Notice that the elements are declared along with their data type but unlike our backend classes, these elements don't get created (instantiated) until the constructor method is called. The code snippet below from the constructor method demonstrates how to create and add the input elements to the input panel. As you can see, each element contains some starting default text that can be replaced by the user:

       name = new JTextField("Student Name");
       inputPanel.add(name);

       grade1 = new JTextField("Grade 1");
       inputPanel.add(grade1);

       grade2 = new JTextField("Grade 2");
       inputPanel.add(grade2);

       grade3 = new JTextField("Grade 3");
       inputPanel.add(grade3);

       grade4 = new JTextField("Grade 4");
       inputPanel.add(grade4);

       grade5 = new JTextField("Grade 5");
       inputPanel.add(grade5);      

Next will add the input button. Notice that the input button is also added to a row in the input panel grid:

       generateGradesButton = new JButton("Generate Grade");
       inputPanel.add(generateGradesButton);

The last element we will add is the output text field to the output panel.


       finalGrade = new JTextField("Final Grade");
       finalGradePanel.add(finalGrade);

Notice an additional line of code for the final grade field which makes this field uneditable by the user:

       finalGrade.setEditable(false);

Once again, our final application window looks like this:
ReportCardWindow

In the next section, we will look at how the grades are read from the form and the final grade is computed and displayed.


Handling Events


The final step in the creation of our application is to write the event handling code. Our application only has to handle one Event, we need to know when the user clicks on the "Generate Grade" Button. When this event occurs, we need to read the grades from the form and generate a final grade. As we learned earlier in this lecture, Events are handled using listeners. If you link a listener object with a control object - like a button, the listener will be notified when an something happens (i.e the buttonis clicked). In our case we need to know when the "Generate Grade" Button is clicked. As a result, we need to create a listener and link it with the generateGradesButton we defined in our class. Below is the code that create an instance of the ButtonHandler class and it with the button.

ButtonHandler buttonHandler = new ButtonHandler();

generateGradesButton.addActionListener(buttonHandler);

Now we need to define the button handler. The button handler will be a private internal class in the ReportCard class and will look like this:

private class ButtonHandler implements java.awt.event.ActionListener {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                // Retrieve all the grades from the input form
                // The grades on the form are text fields so we have to convert
                // them to float data type
                String grade1Text = grade1.getText();
                float grade1Value = Float.parseFloat(grade1Text);
                String grade2Text = grade2.getText();
                float grade2Value = Float.parseFloat(grade2Text);
                String grade3Text = grade3.getText();
                float grade3Value = Float.parseFloat(grade3Text);
                String grade4Text = grade4.getText();
                float grade4Value = Float.parseFloat(grade4Text);
                String grade5Text = grade5.getText();
                float grade5Value = Float.parseFloat(grade5Text);

                // Calculate the average grade
                float result = (grade1Value + grade2Value + grade3Value + grade4Value + grade5Value) / 5;
               
                // Convert the result to a string and display in the final grade field on the form
                finalGrade.setText(String.valueOf(result));
            }
   }

Notice that this class implements an interface. Just like your some of your backend classes! If you look at this interface in the Java documentation you will see that it contains a single method - actionPerformed. Here we provide the method definition - the same way you provided the method definitions for your backend classes.

And that's it, our report card program with graphical user interface is done!

Solution PreviewSolution Preview

This material may consist of step-by-step explanations on how to solve a problem or examples of proper writing, including the use of citations, references, bibliographies, and formatting. This material is made available for the sole purpose of studying and learning - misuse is strictly forbidden.

package Test;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
import view.*;

/**
*
* @author
*/
public class TestClass extends JFrame {
   
    private JLabel inputForms = new JLabel("            INPUT FORMS");
    private JLabel reportForms = new JLabel("          REPORT FORMS");
    private JButton stInputFormButton = new JButton("Student Input Form");
    private JButton stReportFormButton = new JButton("Student Report Form");
    private JButton facInputFormButton = new JButton("Faculty Input Form");
    private JButton facReportFormButton = new JButton("Faculty Report Form");
    private JButton classInputFormButton = new JButton("Clasroom Input Form");
    private JButton classReportFormButton = new JButton("Clasroom Report Form");
    private JButton courseInputFormButton = new JButton("Course Input Form");
    private JButton courseReportFormButton = new JButton("Course Report Form");

    public TestClass() {

       // set the window to 800x500 pixels wide and location (100,100).
       setSize(1000, 600);
       setLocation(50, 50);

       // Close window when exit button clicked
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       // Panel to house the buttons
       JPanel mainPanel = new JPanel();
       mainPanel.setLayout(new GridLayout(6,2,10,10));
       // Set the title of the window
       setTitle("Test CLass");

       // Set the layout of the window
       setLayout(new BorderLayout());

       // Create a listener object and add it to the buttons
       // Notice how we refer to this inner class
       TestClass.ButtonHandler listener = new TestClass.ButtonHandler();
       stInputFormButton.addActionListener(listener);
       stReportFormButton.addActionListener(listener);
       facInputFormButton.addActionListener(listener);
       facReportFormButton.addActionListener(listener);
       classInputFormButton.addActionListener(listener);
       classReportFormButton.addActionListener(listener);
       courseInputFormButton.addActionListener(listener);
       courseReportFormButton...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

$15.00
for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available IT Computer Support Services - Other Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats