
Swing
What is Swing?
So far, all the programs we've writing are console based. Hence, it gets boring and the users can only interact with the program only if they've something to compile the codes. Thus, this is where swing comes in to play, swing allows the user to interact with the program better and more playful. So what is swing??? Swing is a package that create applications which use a flashy Graphical User Interface ( or GUI ), pronounce as " gooey ." In English, simply all the application that we are using such as, Jgrasp compiler, Media player, Microsoft Word, and so on. Swing API provides many different classes for creating various types of user-interface elements. We will look at three of those classes: JFrame, JLabel, and JPanel. The swing class has more than that, lets see a brief description of the classes.
* Object: All classes derive from Object.
* Component: The component class represents an object that has visual representation that can be shown on-screen and can interact with users. This is in the
AWT class rather than the Swing class.
* Container: It builds on the basic visual capabilities of the Component class by adding the ability to hold other containers. This is in the AWT class.
* Window: It defines a window, a specialized type of container object that has a border, a title bar, and buttons that minimize, maximize, and close.
* Frame: A type of window that serves as the basis for Java GUI applications. It's also in the AWT class.
* JFrame: It's an older Frame class.
* JComponent: It's a swing class that is the basis for all other swing components except for frames.
* JPanel: It creates panels, which are containers used to organize and control the layout of the other components such as lables, buttons, textfield and so on.
* JLabel: The class creates a label that displays a simple text value.
At the moment, you might not have a clue of what all those are, but keep in mind of the descriptions as we move along in the chapter it will be more clear. Lets see a very simple graphic user interface (GUI) using JOptionPane.
/*
This is a simple GUI using JOptionPane
*
*/
import javax.swing.*;
// Needed for the swing
class
public class Name
{
public static void main(String[] args)
{
// Ask for a name
String input =
JOptionPane.showInputDialog("Enter your name");
// Outputs the input name
JOptionPane.showMessageDialog(null,
"The name you enter is " + input);
}
}
To get an input from the user, we use JOptionPane.showInputDialog(" " ); and to output to the screen we use JOptionPane.showMessageDialog(null, " "); so know the difference, and when outputting don't forget to put the null. The inputs from swing is a String, so if we want to do calculations we would have to convert the string into number, thus the Java API gives us a great method to do so.
Integer.parseInt(" ") -- Converts String into an integer
Double.parseDouble(" ") -- Converts String into a double
Float.pareseFloat(" ") -- Converts String into a float
Lets see a example on how to use them.
/*
The program demonstrate how to convert Strings into Numbers
*
*/
import javax.swing.*;
public class ConvertNum
{
public static void main(String[] args)
{
// Gets the first number
String firstnum =
JOptionPane.showInputDialog("Enter a number");
// Gets the second number
String secnum =
JOptionPane.showInputDialog("Enter another number");
double sum = 0.0;
// Convert the Strings into a Double
double num1 =
Double.parseDouble(firstnum);
double num2 =
Double.parseDouble(secnum);
// Sums up the number
sum = num1 + num2;
// Output the sum into the screen
JOptionPane.showMessageDialog(null,
"The sum of the two number is " + sum);
}
}
ClickHere to download ConvertNum.java
Now, lets get into a different kinds of swing. A window type of swing application. To help us understand the swing world better, I created a method and constructor table of swing classes in the link below. As we move along, it would be best if you first read the swing method and constructor table first and try to remember what each methods/constructors do.
The first method
Recall from the inheritance chapter, once we extends a class, we are able to use any methods that belong to the other class. It is the same thing with swing classes, if we extends any of the classes we are able to use their methods as if it were its own. It might be a little confusing from just reading it, hence lets see a example of it.
/*
The program demonstrates the use of JFrame
It sets the title to Hello World
*
*/
import javax.swing.*; // Needed for the
swing class
public class HelloWorld extends JFrame
{
public HelloWorld()
{
// Sets the size of the window
setSize(300, 200);
//
Sets the title of the window
setTitle("This is a Hello World
Frame");
// Sets the action when the user clicks on the X
of the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the window to be visible
setVisible(true);
}
public static void main(String[]
args)
{
new HelloWorld();
}
}

The above program is a very simple swing program with a title set to " This is Hello World Frame ." Since swing applications are still java applications, and all java applications need a static main method that starts the application. Hence, in order for the window to display we would need to add a main method. The above method used the inheritance style, we inherits the method from the JFrame class, thus we are allow to use all the method inside the class. Notice, the name must be the same as the class name that we created. If we look back at the program above, we have the class name as HelloWorld, follow with another method with HelloWorld. The two names has to match or else the compiler would give out an error. Then inside the main method, all we need is an instance of the class.
Here is a second method
Recall from class and objects, well! here we will use the same idea.
/*
The program demonstrates the use of JFrame
It sets the title to Hello World
*
*/
import javax.swing.*; // Needed for the
swing class
public class HelloWorld2
{
public static void main(String[] args)
{
//
Creates an object for the JFrame class
JFrame window = new JFrame();
// Sets the size of the window
window.setSize(300, 200);
// Sets the title of the window
window.setTitle("This is a Hello
World Frame");
// Sets the action when the user clicks on the X
of the window
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the window to be visible
window.setVisible(true);
}
}

The two method of creating a swing window produce the same output. It's good to know how to use both ways of creating an application, hence when we get to a more complicated application, we might have to combine the two together. The idea of the second method is basically creating an object, then use the object to allocated the methods for us, so we can use the methods inside JFrame class.
Now, using the JLabel constructor and methods, we are able to write inside the Frame. But, a label won't display until we add it to a panel. A panel is a type of container that's designed to hold a group of components so they can be displayed on a frame. A normal way to display text fields, labels, buttons, and other GUI components is to add those to a panel and then add the panel to the frame. Hence, for the JPanel constructors and methods, look at the link below " Swing Method & Constructor Table. " Lets see a example of using JPanel and JLabel.
/*
The program writes a message inside a Frame
*
*/
import javax.swing.*;
public class FrameLabel extends JFrame
{
public static void main(String[] args)
{
new FrameLabel();
}
//
Creates a new label with no text
JLabel label = new JLabel();
// Creates a new panel
JPanel panel = new JPanel();
public FrameLabel()
{
// Sets the title for the Frame
setTitle("Hello World");
// Sets the size for the Frame
setSize(400,
500);
// Creates a Message inside the frame
label.setText("Hello World");
// Adds the label to the panel
panel.add(label);
// Adds the panel to the frame
add(panel);
// Sets the action if frame is close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the window to be visible
setVisible(true);
}
}

The above example, we first create a panel, then we add the label into the panel so it would display on the frame. For all the panel and label constructors/methods, look at the link below "Swing Method & Constructor Table."
To create a Button, we would have to use the JButton class. It is very similar to JLabel class.
/*
The program demonstrate the combination of JLabel and JButton
*
*/
import javax.swing.*;
public class ButtonLabel extends JFrame
{
// Creates an empty
label
JLabel label = new JLabel();
// Creates a button with no
text
JButton button = new JButton();
// Create a panel
JPanel panel = new JPanel();
public ButtonLabel()
{
//
Sets the title of the frame
setTitle("Button & Label");
// Sets the size of the frame
setSize(300, 200);
// Sets the text of the label
label.setText("This is a button");
// Sets the text for the button
button.setText("Button");
//
Adds label and button to the panel
panel.add(label);
panel.add(button);
// adds the panel to the frame
add(panel);
//
Sets the action if the window is close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the window to be visible
setVisible(true);
}
public static void main(String[] args)
{
new ButtonLabel();
}
}

Always remember to create a panel to hold components, then add the panel to the frame.