How to write programs using Java Swing in a few easy steps

write-programs-using-java-swing

write-programs-using-java-swingIf you are bored of command line programs it’s high time to ride the Java Swing with this tutorial. Though as of now I have been writing programs using Java Swing for a couple of years, my introduction to Swing was quite interesting. It was when I joined college and I started teaching Java to school students to earn some pocket money. Java Swing was never part of the syllabus and never did I dream of teaching Swing but god had some other plans for me. I used to teach a batch of 5 students and if you had ever taught a batch of students, you will know there is always a student or two who were in short “a show off”. My batch was no exception. Even in my batch there was this son of a … who used to google up words related to Java and ask me to teach them and most of the time I didn’t know the answer. Every time I used to conjure up some other topic and escaped. Even at that time I was as lazy as I am now and I planned to finish the syllabus 2 months early so as to take a leave for few classes but that was not going to happen. This guy tells me as the syllabus is complete I should teach them Java swing and the other 4 students agreed as there was so much time left before the exams. And at last I couldn’t escape. 😥 Frankly at that time I just knew that Java Swing was used to build programs using graphical interface. And so the plan to take a leave backfired and I had to spend days figuring out Java swing. 😡

java swingSo what is all the fuss about Java Swing?

In simple words, Java Swing is used to make programs using buttons, menus and toolbars. It gives your program a good look and feel and a relief from the same old black screen. You can also do animations which is moving certain objects at the click of a button. In fact there are a large number of things you can do using Java Swing and at the end of the tutorial you will be able to create programs using Java Swing. So stop having a blunt face and let’s dive into the pool.

My first Java Swing Program:

This tutorial assumes that you know the basics of Java. There are certain things you should know before you start writing your first program:
1. In every program you will have to create a Java Frame (JFrame) and add the Components (buttons, labels or menus) into it.
2. import javax.swing package

We will show you a simple program which will contain a JFrame which will have a label and a button.

import javax.swing.*;

class MyFirstSwingProgram {
 JFrame frame;

 public static void main(String[] args) {
 MyFirstSwingProgram gui = new MyFirstSwingProgram();
 gui.go();
 }

 public void go() {
 frame = new JFrame("My first java program"); //this is the frame
 //to end the program when the window is closed
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 JLabel label = new JLabel("I'm a Label"); // create a label
 JButton button = new JButton("I'm a button. Click me"); //create a button

 frame.add(label); //adding the label to the frame
 frame.add(button);
 frame.setSize(300,300); //setting the size of the frame
 frame.setVisible(true); //make the frame visible
 }
}

Java Swing ButtonThat’s a huge button. And where is the Label?

The label and the button are both added to the frame but as the button was added later, it takes up the whole space. There must be a way to show both the label and the button at the same time. Also we don’t want such a huge button. This is where the LayoutManager comes in. But what is this LayoutManager used for? Layout Manager is used to manage the layout..duh. Let’s see how it will help in showing both the label as well as the button and also manage their size. There is also one more thing. The JPanel is like a window. Whenever we add a component (JButton or JLabel) to it, it takes up the whole space of the window. To confine the component to certain position of the window, we have to add it to that specific position in the window pane. Let’s see how it’s done.


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

class MySecondSwingProgram {
 JFrame frame;

 public static void main(String[] args) {
 MyFirstSwingProgram gui = new MyFirstSwingProgram();
 gui.go();
 }

 public void go() {
 frame = new JFrame("My first java program");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 JLabel label = new JLabel("I'm a Label");
 JButton button = new JButton("I'm a button. Click me");
//adds it to the pane instead of the frame directly
 frame.getContentPane().add(BorderLayout.CENTER, label); 
//BorderLayout is explained later
 frame.getContentPane().add(BorderLayout.SOUTH, button);
 frame.setSize(300,300);
 frame.setVisible(true);
 }
}

a label and a button

Now it looks much better. Is it the layout manager you were talking about?

layout manager in javaYes exactly. Layout Manager is a Java object who controls the components contained within a component. Controlling means in short the size and placement of the components. It got more confusing isn’t it? Let’s take the help of the previous example. There was a frame on which a label and button were added. So the layout manager of the frame will control the size and placement of both the button and the label. There are different types of layout in Java. Here we have used the most simple type that is the BorderLayout. The BorderLayout divides the frame into 5 parts – NORTH, CENTER, EAST, SOUTH and WEST. In each part you can add one component. There are other kinds of layouts like the BoxLayout, GridLayout, CardLayout and the FlowLayout. Click on layouts to get more details. After teaching the layouts, my students demanded that these buttons are great but they doesn’t work. They should do something at least change the label right?

Making the buttons work:

I knew this question would be coming so I had already prepared this. To make the button work first we need to check if anybody is clicking on the button. In Java we call it listening to the component. Whenever we listen to the button, Java notifies us whenever the user clicks on the button. But shouldn’t we do something when the button is pressed? We have to write a method which will be called every time the user clicks on the button. But how do we do all that?
1. We have to implement the ActionListener interface.
2. Add a ActionListener to the objects you want to listen.
3. Lastly override actionPerformed() to do what you want when the program listens something.

action listener in java

The students got bored…yawned. Enough of the theory part, give me some code.


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

class MyFirstSwingProgram implements ActionListener {
JFrame frame;
JLabel label;
JButton button;
int count;

 public static void main(String[] args) {
 MyFirstSwingProgram gui = new MyFirstSwingProgram();
 gui.go();
 }

 public void go() {
 count = 1;
 frame = new JFrame("My first java program");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 label = new JLabel("I'm a Label");
 button = new JButton("I'm a button. Click me");
 button.addActionListener(this);

 frame.getContentPane().add(BorderLayout.CENTER, label);
 frame.getContentPane().add(BorderLayout.SOUTH, button);
 frame.setSize(300,300);
 frame.setVisible(true);
 }

 public void actionPerformed(ActionEvent e) {
 label.setText("I have been clicked " + count++ + " times");
 }
}

In this program we listen to the button. Whenever the button is clicked the actionPerformed()  is called. In it we change the text of the label using the setText(). My students were very happy and they even tried to develop a few applications until a problem occured. What if we had two buttons and both buttons does separate work. How can a same method actionPerformed() do two different works?

How to make the same actionPerformed() do two different tasks?

Just use getSource(). The getSource() returns the object on which the Event has occurred. So you have to check using an if condition and call the appropriate function. Let’s see how it’s done. Here we show how there are two buttons which can change the label to different texts.


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

public class TwoButtons implements ActionListener {
 JFrame frame;
 JLabel label;
 JButton labelButton1;
 JButton labelButton2;

 public static void main (String[] args) {
 TwoButtons gui = new TwoButtons();
 gui.go();
 }

 public void go() {
 frame = new JFrame();
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 labelButton1 = new JButton("Change to Hello");
 labelButton1.addActionListener(this);
 labelButton2 = new JButton("Change to World");
 labelButton2.addActionListener(this);
 label = new JLabel("I'm a label");

 frame.getContentPane().add(BorderLayout.SOUTH, labelButton1);
 frame.getContentPane().add(BorderLayout.NORTH, labelButton2);
 frame.getContentPane().add(BorderLayout.CENTER, label);
 frame.setSize(300, 300);
 frame.setVisible(true);
 }

 public void actionPerformed(ActionEvent event) {
 if (event.getSource() == labelButton1)
 label.setText("Hello");
 else if (event.getSource() == labelButton2)
 label.setText("World");
 }
}

There is a better way by creating Inner Classes. Though this is a better way when you are not listening to many objects as all the actionPerformed() code are kept at the same place. My students were very happy and they started building small applications using several buttons.

This is the end of this tutorial. I hope you got to know a bit about Java Swing. You can do a lot of other stuffs using Java Swing and make sure you try to make new applications and share your experiences. Hopefully you enjoyed reading this tutorial. If you have any doubts please use the comments.  Thank you and visit www.intechgrity.com for more tutorials.

3 comments

  1. Palanikumar

    You gave so many programs i am really proud of you. better you update java swing programs using eclipse IDE. just we click and drag the components why we type many coding and also confused. IDE is better in my point of view

  2. arnab Post author

    Hi Palani, thanks for asking this question. First of all dragging the components using IDE might seem easy but it creates a lot of unnecessary code. Secondly though it seems difficult to write the program and make the swing components, it is actually pretty easy once you get a grasp of it, so why not do it this way? You can learn both the ways and if you don’t like to write the code yourself you can always go back to dragging 🙂

  3. Goutsmi

    Hi Arnab, can write a code for student details by using java swing on eclipse IDE. And the form must contain 2 buttons one save and Display. When u click on save it data should save on mysql database. When u click on display the inform should display on the same frame.

    Plz help me with this code

Comments are closed.