Home » Desktop Java » swing » Java Swing Tutorial for Beginners

About Jun Wu

Jun Wu
Jun (Steven) Wu is a current Master student in Computer Science & Engineering department of University of Nebraska Lincoln (Lincoln, NE, USA). His current interests focus on Programming Languages (Java, Python), Relational Database (MySQL), NoSQL Database (Apache Cassandra, MongoDB), and Computer Networks.

Java Swing Tutorial for Beginners

1. Introduction

In Java, it provides a rich set of libraries to create Graphical User Interface (GUI), to make it work independently on different platforms. Swing is definitely the one which is most popular used, because its properties of light-weight, rich-control, easy-customizable.

Before Java Swing, Abstract Windowing Toolkit (AWT) is the one to create different GUIs. However, because of its disadvantages on platform-dependent, heavy-weight, few-components, it has been replaced by Java Swing, which is built on top to the AWT package. Note that some AWT components remain in Java and in some situations it must be used. In the following part, you’ll see some AWT package to be imported by our examples.

In this article, we focus on Java Swing, which has large set of components, such as JFrame, JButton, JMenu, etc. we’ll cover the most-often-used components in Java Swing and each component will be explained with example. Finally we’ll combine all these components to create a small GUI project.

For the following examples, Java 8 and Eclipse IDE (version Mars 4.5.0) are used.

2. Java Swing Components

2.1 JFrame

In Java Swing, most application will be built inside a basic component JFrame, which creates a window to hold other components.

JFrameExample.java

package javaCodeGeeks;

import javax.swing.JFrame;

/*
 * A basic swing example with JFrame
 */

public class JFrameExample {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello Swing");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(350, 250);
		frame.setVisible(true);
	}

}

Note that we can initialize the frame with string “Hello Swing”, which creates a blank frame with title “Hello Swing” like the figure below. The function setDefaultCloseOperation tells the frame what to do when user close the frame and JFrame.EXIT_ON_CLOSE reforms exit when user close the frame. The size of the frame could be set by setSize with width and height parameters. Notice that without the setVisible function with parameter true, you won’t see anything on the screen. In order to see the GUI part, we need this function and set it to be true.

JFrame

JFrame

2.2 JLabel

JLabel is a area to display a short string or an image or both. Normally we can add the JLabel into the JFrame we’ve built in previous part and show different displays. With the following java code added following the creation of JFrame, a label with text “I’m a JLabel” is created.

JLabel label = new JLabel("I'm a JLabel", JLabel.CENTER);
frame.add(label);

For the position of the label, it could be specified by JLabel.LEFT, JLabel.CENTER, JLabel.RIGHT, of which the position could set to be left, center and right correspondently. The figure below shows that a label is set in the center of the window.

JLabel

JLabel

2.3 JPanel

JPanel is a popular container to hold different components. It could be set and added by using the code similar to following:

JPanel panel = new JPanel();
frame.add(panel);

2.4 JButton

JButton is an implementation of a “push” button. It can be pressed and configured to have different actions, using the event listener. For this part we’ll discuss it in the last. In the following code, we added three buttons into the panel with different name on them: Button 1, Button 2, Button 3.

ButtonExample.java

package javaCodeGeeks;

import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

/*
 * A basic swing example with JButton
 */

public class ButtonExample {

	public static void main(String[] args) {
		// Define frame, label and panel
		JFrame frame = new JFrame("Hello Swing");
		JLabel label = new JLabel("I'm a JLabel", JLabel.CENTER);
		JPanel panel = new JPanel();
		
		// Setting for the panel
		BoxLayout boxlayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
		panel.setLayout(boxlayout);
		panel.setBorder(new EmptyBorder(new Insets(45, 70, 45, 70)));
		
		// Define new buttons
		JButton jb1 = new JButton("Button 1");
		JButton jb2 = new JButton("Button 2");		
		JButton jb3 = new JButton("Button 3");
		
		// Add buttons to the frame (and spaces between buttons)
		panel.add(jb1);	
		panel.add(jb2);
		panel.add(jb3);
		
		// Add the label and panel to the frame
		frame.setLayout(new GridLayout(2, 1));
		frame.add(label);
		frame.add(panel);
		
		// Settings for the frame
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

}

In the example above, we set a label to be in the up side and a panel containing three buttons in the bottom. The result is shown in the figure below. Note that we have a BoxLayout function, which is used to set the layout of the components. Further inflammation can be found in my another article about BoxLayout, which used the JButton a lot.

JButton

JButton

2.5 JRadioButton

Here, JRadioButton is quite different from JButton. It’s a radio button that can be selected or deselected. Use with the ButtonGroup object to create a group of buttons,in which only one button can be selected at a time.

RadioButtonExample.java

package javaCodeGeeks;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

/*
 * A basic swing example with JFrame
 */

public class RadioButtonExample {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello Swing");
		JPanel panel = new JPanel();
		
		// Create Radio buttons
		ButtonGroup bg = new ButtonGroup();		
		JRadioButton rb1 = new JRadioButton("Male", true);
		JRadioButton rb2 = new JRadioButton("Female", false);
		JRadioButton rb3 = new JRadioButton("Not specified", false);

		// Add the radio buttons to the button group
		bg.add(rb1);
		bg.add(rb2);
		bg.add(rb3);
		
		// Add to the panel and frame
		panel.add(rb1);
		panel.add(rb2);
		panel.add(rb3);
		frame.add(panel);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

}

The code above creates a button group and have there radio button inside. We set the “Male” button to be chosen by default, by setting it to be true initially. And we can see figures below, showing that each time, only one button can be chosen.

JRadioButton1

JRadioButton1

JRadioButton2

JRadioButton2

2.6 JCheckBox

JCheckBox is used to create checkbox, of which multiple checkbox could be selected at the same time. That’s the main difference between JRadioButton. For JCheckBox, I’ve written another article on it with detailed example, you can check it here.

2.7 JSlider

JSlider is a component that lets the users select a value by sliding a knob within a specified interval. For the knob, it always points to the point which matches the integer values within the interval. You can check my article on JSlider here.

2.8 JTable

JTable is used to create a regular two-dimensional tables. The table can display data inside of it. In addition, the user can also edit the data. The following example shows that we created three columns: ID, Name, Age. In each column, we have set the data/information inside.

JTableExample.java

package javaCodeGeeks;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/*
 * A basic swing example with JTable
 */

public class JTableExample {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello Swing");
		
		// Set data inside the table
		String[][] data = {{"01", "Alex", "18"}, {"02", "Brandon", "20"}, {"03", "Cassie", "18"}, {"04", "Steve", "25"}};
		String[] column = {"ID", "Name", "Age"};
		
		// Create JTable
		JTable jt = new JTable(data, column);
		JScrollPane sp = new JScrollPane(jt);		
		
		frame.add(sp);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

}

The table is shown below:

JTable

JTable

2.9 JComboBox

JComboBox is a component to select value from a drop-down list. You can choose one and only one element from the list. The following example shows how to create the drop-down list, from which different countries can be chosen: “Australia”, “China”, “England”, “Russia”, “United States”.

JComboBoxExample.java

package javaCodeGeeks;

import javax.swing.JComboBox;
import javax.swing.JFrame;

/*
 * A basic swing example with JComboBox
 */

public class ComboBoxExample {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello Swing");
		
		// Set data in the drop-down list
		String[] country = {"Australia", "China", "England", "Russia", "United States"};
		
		// Create combobox
		JComboBox cb = new JComboBox(country);
		
		frame.add(cb);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

}

The two figures below shows that we can choose different countries.

JComboBox1

JComboBox1

JComboBox2

JComboBox2

2.10 JMenu

In this example, we have different settings on menu. We have File menu, which includes of save, quit submenu, and Edit menu, including copy, cut, paste submenu, and Help menu, containing try your best:)

The code below is to generate the menus:

JMenuExample.java

package javaCodeGeeks;

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/*
 * A basic swing example with JMenu
 */

public class JMenuExample {

	public static void main(String[] args) {
		JFrame frame = new JFrame("Hello Swing");
		JPanel panel = new JPanel();
		JTextArea ta = new JTextArea();
		
		// Define the main menu
		JMenuBar mb = new JMenuBar();
		JMenu file = new JMenu("File");
		JMenu edit = new JMenu("Edit");
		JMenu help = new JMenu("Help");
		
		// Define submenue for file
		JMenuItem save = new JMenuItem("Save");
		JMenuItem quit = new JMenuItem("Quit");
		
		// Define submenue for edit
		JMenuItem cut = new JMenuItem("Cut");
		JMenuItem copy = new JMenuItem("Copy");
		JMenuItem paste = new JMenuItem("Paste");

		// Define submenue for help
		JMenuItem tryYourBest = new JMenuItem("Try your best:)");

		file.add(save);
		file.add(quit);
		edit.add(cut);
		edit.add(copy);
		edit.add(paste);
		help.add(tryYourBest);
		
		mb.add(file);
		mb.add(edit);
		mb.add(help);
		
		// Define new buttons
		JButton jb1 = new JButton("Button 1");
		JButton jb2 = new JButton("Button 2");		
		JButton jb3 = new JButton("Button 3");
		
		// Add buttons to the frame (and spaces between buttons)
		panel.add(jb1);	
		panel.add(jb2);
		panel.add(jb3);
		
		frame.setLayout(new GridLayout(3, 1));
		frame.add(mb);
		frame.add(panel);
		frame.add(ta);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

}
JMenu1

JMenu1

JMenu2

JMenu2

JMenu3

JMenu3

JMenu4

JMenu4

3. A small Java Swing project

In this example, we’ll combine what we’ve learnt from the previous part and try to use them in a small project: a simple calculator with GUI display. In this project, we’ll add event listener into the system, and when we press the button, there’ll be some reactions to it.

The following code is for the simple calculator project. Note that it’s just a basic one, which supports only the basic add, subtract, multiply, divide operations. Most of the code could be referred here.

MainApp.java

package Calculator;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

/***
 * 
 * A simple calculator using Java Swing
 *
 */

public class MainApp {
	
	// Define different components
	private static JFrame frame;
	private static JTextField field;
	private static JPanel contentPanel;
	private static JPanel displayPanel;
	private static JPanel buttonPanel;
	private static boolean start = true;
	private static double result = 0;
	private static String lastCommand = "=";

	// Define the action listeners
	private static ActionListener insert = new InsertAction();
	private static ActionListener command = new CommandAction();

	public static void main(String[] args) {
		// Add the frame, panel and text field
		frame = new JFrame("Simple Calculator");
		field = new JTextField();
		contentPanel = new JPanel();
		displayPanel = new JPanel();
		buttonPanel = new JPanel();

		// Set the content panel
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPanel.setLayout(new BorderLayout(0, 0));
		contentPanel.add(displayPanel, BorderLayout.NORTH);
		contentPanel.add(buttonPanel, BorderLayout.CENTER);

		// Set the result field
		field.setText("0");
		field.setHorizontalAlignment(SwingConstants.RIGHT);
		field.setEditable(false);
		field.setColumns(13);

		buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));

		// Set the buttons
		JButton number7 = new JButton("7");
		number7.addActionListener(insert);
		
		JButton number8 = new JButton("8");
		number8.addActionListener(insert);
		
		JButton number9 = new JButton("9");
		number9.addActionListener(insert);
		
		JButton divide = new JButton("/");
		divide.addActionListener(command);
		
		JButton number4 = new JButton("4");
		number4.addActionListener(insert);
		
		JButton number5 = new JButton("5");
		number5.addActionListener(insert);
		
		JButton number6 = new JButton("6");
		number6.addActionListener(insert);
		
		JButton multiply = new JButton("*");
		multiply.addActionListener(command);
		
		JButton number1 = new JButton("1");
		number1.addActionListener(insert);
		
		JButton number2 = new JButton("2");
		number2.addActionListener(insert);
		
		JButton number3 = new JButton("3");
		number3.addActionListener(insert);
		
		JButton subtract = new JButton("-");
		subtract.addActionListener(command);
		
		JButton number0 = new JButton("0");
		number0.addActionListener(insert);
		
		JButton dot = new JButton(".");
		
		JButton equal = new JButton("=");
		equal.addActionListener(command);
		
		JButton add = new JButton("+");
		add.addActionListener(command);
		
		// Add the buttons
		buttonPanel.add(number7);
		buttonPanel.add(number8);
		buttonPanel.add(number9);
		buttonPanel.add(divide);
		buttonPanel.add(number4);
		buttonPanel.add(number5);
		buttonPanel.add(number6);
		buttonPanel.add(multiply);
		buttonPanel.add(number1);
		buttonPanel.add(number2);
		buttonPanel.add(number3);
		buttonPanel.add(subtract);
		buttonPanel.add(number0);
		buttonPanel.add(dot);
		buttonPanel.add(equal);
		buttonPanel.add(add);

		// Settings for the frame
		frame.setLayout(new GridLayout(2, 1));
		frame.add(field);
		frame.add(contentPanel);
		frame.pack();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

	//Insert action on digital numbers
	private static class InsertAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String input = e.getActionCommand();
			String text = field.getText();
			
			if (start) {
				field.setText("");
				start = false;
			}

			if (text.startsWith(".")) {
				field.setText("0" + field.getText() + input);
			} else if (text.startsWith("-0.") || text.startsWith("0.")) {
				field.setText(field.getText() + input);
			} else if (text.startsWith("-0")) {
				field.setText("-" + input);
			} else if (text.startsWith("0")) {
				field.setText(input);
			} else {
				field.setText(field.getText() + input);
			}
		}
	}


	// Command actions on +, -, *, /, =

	private static class CommandAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String command = e.getActionCommand();
			if (start) {
				if (command.equals("-")) {
					field.setText(command);
					start = false;
				} else {
					lastCommand = command;
				}
			} else {
				calculate(Double.parseDouble(field.getText()));
				lastCommand = command;
				start = true;
			}
		}
	}
	
	/*
	 * Real caculation function
	 */
	public static void calculate(double x) {
		char operator = lastCommand.charAt(0);
		switch (operator) {
		case '+':
			result += x;
			break;
		case '-':
			result -= x;
			break;
		case '*':
			result *= x;
			break;
		case '/':
			result /= x;
			break;
		case '=':
			result = x;
			break;
		}
		field.setText("" + result);

	}
}

The result after running the code is shown below:

Calculator

Simple Calculator

4. Download the Source Code

Download
You can download the source code of this example here: Java Swing Examples.zip

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of