Java Tutorial: Java Swing GUIs


Posted 2020/06/01

Swing is a lightweight GUI widget toolkit for Java. The toolkit is cross-platform and contains GUI components like buttons, textbox, labels, etc that the developer doesn’t have to create from scratch.

Containers

Containers are classes that contain other components in it. To create a GUI, the program needs at least one container object. The simplest container is JFrame as it is a fully functioning window with a title and icon

JFrame Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import javax.swing.*; //import Java Swing
public class FrameDemo{
    public Window(){ //class constructor
        JFrame frame = new JFrame("Window"); //create new window with the window title "Window"
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make closing the window exit the program
        frame.setSize(400,300); //set window size
        frame.setVisible(true); //make window visible
    }
    public static void main(String[] args){ //code runner method
        new FrameDemo();
    }
}

FrameDemo.java

If you ran the code above correctly you should see a window similar to the image on the right. The window may look different depending on the platform that it is run on. This screenshot was taken on Ubuntu so it will look different depending on your operating system. This example code will be the base for any GUI that you will create in this tutorial

JComponents

JComponents are the parts of your GUI that take input, show data, or instructions. Some JComponents are JButton, JLabel, JTextField, etc. Below you can find a list of different JComponents and their constructors

Adding Components

Components can be added to frames or layout managers using the JFrame.add(Component comp) method. This method is a part of the frame or layout manager object and takes a single JComponent object as an argument. For example, to add a button to our example window add frame.add(new JButton("Button")) just after line 6 in the JFrame example above

Layout Managers

If you have tried adding any of the JComponents above, you will realize that you want the components in a certain layout to decide on where components are located in the JFrame. This can be done with Swing’s layout managers

Java Swing has 8 built-in Layout Manager classes; BorderLayout, BoxLayout, CardLayout, FlowLayout, GridBagLayout, GridLayout, GroupLayout, and Spring Layout. The simplest and most common layouts are GridLayout, BorderLayout, and FlowLayout. The layout of a frame can be set with JFrame.setLayout(LayoutManager manager)

FlowLayout

flow layout

FlowLayout places JComponents in a row from left to right, top to bottom. Each successive component added to the frame will be added to the end of the row if possible or create a new row below.

FlowDemo.java

GridLayout

grid layout

GridLayout places JComponents in a grid format. The size of the grid is set in the layout constructor: new GridLayout(int rows, int columns). Components are added left to right top to bottom with each component having the same size

GridDemo.java

BorderLayout

border layout

BorderLayout has 5 regions to place JComponents. BorderLayout uses a modified JFrame.add() method which has a second argument that specifies the region to place the component. For example to add a button to the CENTER region use frame.add(new JButton("Center Button"),BorderLayout.CENTER). The layout can be set using frame.setLayout(new FrameLayout())

BorderDemo.java

Combining Layouts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
JFrame frame = new JFrame("MixedLayouts"); //create window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
frame.setLayout(new GridLayout(2,2)); //set parent grid layout

JPanel flow = new JPanel(); //create flow layout panel
flow.setLayout(new FlowLayout()); //set panel layout
flow.add(new JButton("Flow1"));
flow.add(new JButton("Flow2"));
flow.add(new JButton("Flow3"));
frame.add(flow); //add panel to frame

JPanel border = new JPanel(); //create border layout panel
border.setLayout(new BorderLayout()); //set panel layout
border.add(new JButton("Border NORTH"), BorderLayout.NORTH);
border.add(new JButton("Border SOUTH"), BorderLayout.SOUTH);
border.add(new JButton("Border EAST"), BorderLayout.EAST);
border.add(new JButton("Border WEST"), BorderLayout.WEST);
border.add(new JButton("Border CENTER"), BorderLayout.CENTER);
frame.add(border); //add panel to frame

JPanel grid = new JPanel(); //create grid layout panel
grid.setLayout(new GridLayout(2,2)); //set panel layout
grid.add(new JButton("Grid 1,1"));
grid.add(new JButton("Grid 1,2"));
grid.add(new JButton("Grid 2,1"));
grid.add(new JButton("Grid 2,2"));
frame.add(grid); //add panel to frame

frame.setVisible(true); //show window

Multiple layouts can be combined by placing layouts inside of each other. In the example to the right Flow, Border, and Grid layouts are placed inside of a 2x2 GridLayout. Using a combination of multiple layouts lets you place your components in a layout that you want. To make this happen the parent layout which in this case is a 2x2 grid is set up in the JFrame like normal. Each layout that we are adding to this grid goes in its own JPanel. We then set the layout of each JPanel, add components to the panel, and add the JPanel to the parent JFrame.

MixedLayouts.java

Actions

Actions are what make your GUI program actually do stuff. Up until now, we have been using buttons that don’t do anything when clicked. To make actions we have to make our class implements the ActionListener interface. Unlike previous examples we assign the components to class variables so that we can pass the buttons to ActionListener. In the constructor we set up the window like normal but add hello.addActionListener(this); to tell ActionListener to monitor events from that button. To set up actions for the buttons we use the actionPerformed method and have it take ActionEvents as an argument. Our method then finds the source of the event and performs the action for that button.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Actions implements ActionListener{
    JButton hello = new JButton("Hello"); //buttons
    JButton bye = new JButton("Bye");
    JFrame frame = new JFrame("Window"); //window

    public Actions(){
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set program to exit when window closed
        hello.addActionListener(this); //tell ActionListener to monitor buttons
        bye.addActionListener(this);
        frame.setSize(300,150); //window size
        frame.setLayout(new FlowLayout()); //layout
        frame.add(hello); //add buttons to window
        frame.add(bye);
        frame.setVisible(true); //show window
    }

    public void actionPerformed(ActionEvent e){ //actions
        if(e.getSource()==hello) System.out.println("Hello!"); //check what button and pefrom print
        if(e.getSource()==bye) System.out.println("Bye!");
    }

    public static void main(String[] args){
        new Actions();
    }
}

Actions.java