- 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); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*;The package javax.swing contains the GUI component classes like JLabel, JTextField, JButton, etc.
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.
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.
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.
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);
public static void main(String[] args) { new WaterApp().setVisible(true); }That’s all for the coding stuffs.
javac WaterApp.javaAnd type the following command to run the program:
java WaterAppA small window appears:Enter the number 70 into the text field and click the button, a message dialog appears: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: