This Java tutorial is designed for those who are new in Swing - the GUI APIs for developing desktop applications in Java. Throughout this tutorial, we will guide you how to build a Java desktop application that looks something like this:

Water Calculator Program

You see, this is a small Swing program that allows the user to enter his or her weight (kg) and calculate the amount of water he or she should drink every day, according to the given formula. When the user clicks the Tell Me button, a message dialog appears telling the exact amount of water.

Technically, you will learn the following things:

- How to create a window using the JFrame class.

- How to use label using the JLabel class.

- How to use text field using the JTextField class.

- How to use button using the JButton class.

- How to arrange components on the frame using FlowLayout - a simple layout manager.

- How to handle the click event of a button.

- How to show a message box using the JOptionPane class.

You can use any text editor of your choice (TextPad, NotePad, WordPad, Sublime, etc), and using the commands javac and java to compile and run the program.

Here’s the full source code of the program - WaterApp. And see our detailed explanation after the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * A Java Swing program that shows how much water you should drink a day.
 * @author www.codejava.net
 */
public class WaterApp extends JFrame implements ActionListener {
	private JLabel labelQuestion;
	private JLabel labelWeight;
	private JTextField fieldWeight;
	private JButton buttonTellMe;

	public WaterApp() {
		super("Water Calculator");

		initComponents();

		setSize(240, 150);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void initComponents() {
		labelQuestion = new JLabel("How much water should I drink?");
		labelWeight = new JLabel("My weight (kg):");
		fieldWeight = new JTextField(5);
		buttonTellMe = new JButton("Tell Me");

		setLayout(new FlowLayout());

		add(labelQuestion);
		add(labelWeight);
		add(fieldWeight);
		add(buttonTellMe);

		buttonTellMe.addActionListener(this);
	}

	public void actionPerformed(ActionEvent event) {
		String message = "Buddy, you should drink %.1f L of water a day!";

		float weight = Float.parseFloat(fieldWeight.getText());
		float waterAmount = calculateWaterAmount(weight);

		message = String.format(message, waterAmount);

		JOptionPane.showMessageDialog(this, message);
	}

	private float calculateWaterAmount(float weight) {
		return (weight / 10f) * 0.4f;
	}

	public static void main(String[] args) {
		new WaterApp().setVisible(true);
	}
}
 

1. Importing necessary packages

To work with Swing, we need to import the following packages:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
The package javax.swing contains the GUI component classes like JLabel, JTextField, JButton, etc.



The package java.awt contains layout manager classes like FlowLayout.

The package java.awt.event contains layout manager classes like FlowLayout.

 

2. Creating a window (JFrame)

Make the WaterApp class extends from the JFrame class:

public class WaterApp extends JFrame…
and call its super’s constructor with a String for the window title as the argument:

public WaterApp() {
	super("Water Calculator");

	initComponents();

	setSize(240, 150);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
After that, we call the initComponents() method to initialize the GUI components (described in the next section); set the size of the window (240x150) and specify the default close operation that terminates the program when the window is closed.

 

3. Creating GUI Components (JLabel, JTextField and JButton)

We declare the GUI components as class variables:

private JLabel labelQuestion;
private JLabel labelWeight;
private JTextField fieldWeight;
private JButton buttonTellMe;
And initialize these components in the initComponents() method like this:

labelQuestion = new JLabel("How much water should I drink?");
labelWeight = new JLabel("My weight (kg):");
fieldWeight = new JTextField(5);
buttonTellMe = new JButton("Tell Me");
We specify the text for the labels and caption for the button, and the width (number of columns) for the text field.

 

4. Using layout manager (FlowLayout)

Swing arranges GUI components in a container using layout managers. In this program, we use the FlowLayout manager which arranges components in a flow from left to right:

setLayout(new FlowLayout());
And adds the components to this frame:

add(labelQuestion);
add(labelWeight);
add(fieldWeight);
add(buttonTellMe);
With the FlowLayout, components appear by the order they are added. Note that if the container’s width is small, the components are placed on the next row.

 

5. Handling mouse click event for the button

To handle mouse click event for button, we need to specify an event handler (action listener) for the button like this:

buttonTellMe.addActionListener(this);
Here, this refers to the JFrame so we need to make the WaterApp class implements the ActionListener interface:

public class WaterApp extends JFrame implements ActionListener {
As the ActionListener interface defines the actionPerformed() method, we need to implement it in the WaterApp class:

public void actionPerformed(ActionEvent event) {
	String message = "Buddy, you should drink %.1f L of water a day!";

	float weight = Float.parseFloat(fieldWeight.getText());
	float waterAmount = calculateWaterAmount(weight);

	message = String.format(message, waterAmount);

	JOptionPane.showMessageDialog(this, message);
}
When the button is clicked, this method is called. In this method, we take the value entered in the text field as the weight, and pass it into the business method that calculates the amount of water:

private float calculateWaterAmount(float weight) {
	return (weight / 10f) * 0.4f;
}
And finally we show a message dialog using the JOptionPane class:

JOptionPane.showMessageDialog(this, message);
 

6. Showing the window

Finally, we create an instance of the frame and show it on the screen in the main() method:

public static void main(String[] args) {
	new WaterApp().setVisible(true);
}
That’s all for the coding stuffs.

 

7. Compile and Run the program

Type the following command to compile the WaterApp.java file:

javac WaterApp.java
And type the following command to run the program:

java WaterApp
A small window appears:

Water Calculator Window

Enter the number 70 into the text field and click the button, a message dialog appears:

Water Calculator Message dialog

And now, let try test the program yourself to see how it works.

Congratulations! You have successfully created your first Swing program.  You can also watch the full video tutorial here:

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#4alishabandri2020-03-29 05:36
Thank you very much for your tutorials. I was able to start learning java. Once again thank you very much May Allah Bless you

Ali
Quote
#3Santoki mihir2019-07-05 12:25
How to make thus java file to executable file for desktop application
Quote
#2Finn Gustafsson2018-12-27 13:25
A nice piece of code - good explanations - and smaill enough to follow the mantra "Keep it simple"
Quote
#1Nghia2017-08-16 06:00
Hi Mr.Nam,
I think you miss about line:
The package java.awt.event contains layout manager classes like FlowLayout.
Thanks you
Quote