Java GUI (Graphical User Interface) programming
Up to this point we have focused only on Java code that runs in a command prompt and displays some text output. In this tutorial we go beyond that and enter the realm of graphical programming.
This tutorial focues on:
- Graphical programs package
- Creating a frame
- GUI components
Graphical programs package
Import the java.awt package to create graphical programs. This package contains classes for displaying several graphical components such as frames, textboxes, labels, and buttons, as well as drawing graphics and displaying images.
Creating a frame
In Java, a frame is a standard graphical window. It has minimize, maximize, and close buttons in its top right corner and can be moved and resized by default. Frames are created using the Frame class.
Frame class constructors
- Frame() - Creates a new instance of Frame that is initially invisible.
- Frame(String title) - Creates a new instance of Frame that is initially invisible with the specified title.
Frame class methods
- void setResizable(boolean resizable) - Sets whether or not a frame is resizable
- void setTitle(String title) - Sets the title of a frame
- void setVisible(boolean visible) - Sets whether or not a frame is visible
- void setSize(int width, int height) - Sets the width & height of a frame
- String getTitle() - Returns the title of a frame
Both sets of code from above produce the same frame:
NOTE: Initially, a frame will not be visible. You have to set it to be visible using the setVisible() method.
There are various graphical components you can add to frames including labels, buttons, textboxes, and textareas. Each component is created through a class and each of these classes has methods to work with the component.
In the example below you will find usage of a few different classes used to create graphical components as well as usage of some of their methods.
The layout of the frame is set to FlowLayout which means that the components in the frame will appear from left to right in the order in which they are added (GUI layout is covered in detail in the Java GUI layout tutorial).
What it will look like: