Building GUI is a crucial part of any application with requires user interactions. Mostly when interactions involves Graphical Representations. It could be in form of Data Display or for taking inputs from users. Java provide JFrame class from javax.swing  extented from awt library to support swing components capabilities. We are going to present some basics of JFrame and will tell how to create simple GUI applications in Java. This article will more focus on code rather then talking extra details. So let’s get started.

First GUI Application in Java

To display a simple GUI which obviously will be only a simple frame we just have to include Jframe package and later on create an Instance of Object and set visibility to true. Remember to do all this thing in your main() function so that it could actually be able to run. First lets create an Empty class under our required package(You may name any package).

package fypsol.guiexamples.ex01;

public class MainClass {
 public static void main(String[] args) {

 }
}

Now that we have our working class lets add an Instance of JFrame into it.

JFrame mJFrame = new JFrame("My First Jframe");

but dont froget to add proper import of JFrame Class

import javax.swing.JFrame;

Now if you make is visible using setter function named

mJFrame.setVisible(true);

and try to compile and run the code you will see a very little screen with practically no height and width to it. So the next task you might guess would be to set width and height of the frame. You can do this with setSize(int,int) setter function. Now complete code may look like this

create empty jframe code
Empty Jframe Code in Eclipse

and the resultant window will look like this

Empty Jframe window
Empty JFrame Window

Changing Close Operation

Now you may have noticed that when you click on close button although the JFrame goes vanished but the program does not terminated as it is supposed to do on close event. Well! this behavior is due to the default behavior of window close event which actually hides the frame. You could do multiple things instead of just hiding the frame. You could do this by using the method  setDefaultCloseOperation which supports following possible behaviours

  • DO_NOTHING_ON_CLOSE
  • HIDE_ON_CLOSE (this is default behavior for JDialog and JFrame)
  • DISPOSE_ON_CLOSE
  • EXIT_ON_CLOSE (this will close like System.exit(0))

Now just need to add one more line to your code and your first GUI is working properly

mJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Changing Appearance Location

By default the JFrame will appear on Top Left corner of your screen. If you want to change this behavior, you may do this using available method called setLocation(int x, int y) This method will take two arguments first is the X point of the Screen and second is Y point. There is also another overloaded method which takes Point() instance so you can also pass an Instance of a Point class. Now to (for example) display our GUI in specific x,y location on the screen we may use following line to make it happen.

mJFrame.setLocation(400, 200);

But what if we want to make it exactly center in the screen? Luckily we also have method for it

mJFrame.setLocationRelativeTo(null);

providing null in argument will make frame Center to Screen. But this method expect a component object and set Location relative to that component.

Changing Resize Behavior

In our above code, although we had provided default size of the Frame but yet you can resize the Frame by dragging the edges and corners of that frame. If you wish that your use would not be able to resize your provided frame you can change this behavior with following line

mJFrame.setResizable(false);

Now by setting this to false, you will not be able to resize the window either by dragging the frame or by pressing the maximize button. As you may have noticed that the maximize button had been disabled.

 

Changing the Title

Although we had provided the title of JFrame via it’s constructor but if we wish to add or change the title of the JFrame later on in our code we can do this with help of title property. This property is available under default getter and setter functions of JFrame class. Which means we can also read the current title of the window with the help of getTitle() method. This method will return String object containing the current title of the JFrame. Similarly if you wish to add title you can use setTitle(String name); method to change the title of JFrame. This method accepts String object as an argument and the title of JFrame will be replaced with this string object.

mJframe.setTitle("My new Title");

Adding a Button

Before leaving Let’s make our boring GUI some dynamic and interactive via adding a simple Button to it. To add button into JFrame we first had to create an Instance of JButton Class.

JButton myButton = new JButton("Hello World");

This needs proper import of required swing package as well

import javax.swing.JButton;

Now to add this button to our JFrame instance we can use add() method simply like this

mJFrame.add(myButton);

But this line will make button to be appeared whole over the JFrame. To be this button under its limits and bounds we need to handle layouts. Proper layout managers handle the way component will be placed over JFrame. We will explain Layouts in our next tutorial, but for now to make things simple just add following line before setting the visibility true and after adding button to mJFrame object.

mJFrame.setLayout(new FlowLayout());

Display JOptionPane on JButton Click

Now finnaly to make it interactive we can add ActionListner to our JButton Instance. We can do this simply by adding an anonymus ActionListner and in that action Listner we could use JOptionPane Class to show dialogbox. This dialogbox is equal to MessageBox class in C# or Alert() in Javascript. We will explain this class in seperate article in our future posts.



This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters


package fypsol.guiexamples.ex01;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainClass {
public static void main(String[] args) {
JButton myButton = new JButton("Hello World");
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(myButton, "Alert", "Hello World Clicked", JOptionPane.INFORMATION_MESSAGE);
}
});
JFrame mJFrame = new JFrame("My First Jframe");
mJFrame.setSize(250, 150);
mJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mJFrame.setLocationRelativeTo(null);
// mJFrame.setLocation(400, 200);
mJFrame.setResizable(false);
mJFrame.add(myButton);
mJFrame.setLayout(new FlowLayout());
mJFrame.setVisible(true);
}
}

view raw

simplegui.java

hosted with ❤ by GitHub

 

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.