Creating a simple window application using Java Swing
A simple window application using Java Swing
Swing is a toolkit API that makes it easy to build user interfaces using Java. The Swing API has about 18 public packages containing various Swing components which can enable us to create all sorts of GUI features. The interface components work the same on most platforms.
In this article, we will be setting up a basic GUI application window. This will enable one to build more complex applications in the future.
Before proceeding ahead, let us try to wrap our heads around the concept of packages in Java.
Packages
Relationship between a package and its underlying classes
The above-given diagram illustrates what a package is and how its child classes can be accessed from outside. A package can be seen as a directory (or a folder) that contains some source files defining useful classes. The diagram describes the way to import the classes from a package.
Now to import the Swing API classes you must add the following line to your code:
import javax.swing.*;
This line gives your program access to all the Java Swing classes.
Source Code:
The code is relatively straightforward.
import javax.swing.*; public class basic { public basic() { //constructor for the window object JFrame window = new JFrame(); JLabel label = new JLabel("This is a label."); window.add(label); window.setTitle("Basic Window"); //displaying the window window.pack(); window.setVisible(true); } public static void main(String[] args) { new basic(); //window object created } }
A constructor is created inside the class. This constructor loads all the UI elements( Swing components) onto the screen. The JFrame class object builds a basic window onto which other Swing components are added. The JLabel class object is only a text holder. We add the Jlabel object to the JFrame object. We then display the JFrame object, which contains all of the components we added to it. As we can see, the constructor is called inside the main method of the class.
A file named "basic.java" is created with this code inside of it.
We then open the folder where the file was created inside a terminal. There we type "javac basic.java" to compile the file and then after the compilation has taken place, we type "java basic" to run the compiled "basic.class" file.
The output looks like this:
This tutorial was just to give one an introduction to how to set up a UI environment with Java using the Swing API. As one implements other Swing components, they are able to build more interactive applications.
Comments
Post a Comment