Creating A GUI Form Window (Java)

Creating a Java form window

As much as I enjoy creating programs that run in a command line / terminal, the majority of end users prefer a program to have a Graphical User Interface (GUI). I have managed to put a GUI on the front of some of my Python projects, so today I am going to look at creating one in Java.

To create the GUI I will be using the Swing package, which I see as being similar to TKinter in Python. For more information on Swing please see: https://en.wikipedia.org/wiki/Swing_(Java).

My initial attempt creates a Java form (200 pixels by 200 pixels) which is covered by one button.

Creating a Java form window
Creating a Java form window

The form loads, a button loads with the right text and when clicked….nothing happens. Closing the frame (hitting the X on the window) ends the program. For the button to do something (anything) Java needs to detect that it has been pressed and then have an action to carry out on detection of the button press.

——

import javax.swing.*; //imports Swing package which creates form and button
import java.awt.event.*; //imports Event package which listens for button press

public class gui_test implements ActionListener { //notice implements ActionListener
    JButton button;

    public static void main (String[] args) {
        gui_test gui = new gui_test();
        gui.press();

    }

    public void press(){
        JFrame frame = new JFrame(); //creates a Java Frame called frame
        button = new JButton("geektechstuff.com"); //creates a Button called button
        button.addActionListener(this); //listens for button press
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //ends program when JFrame closed

        frame.getContentPane().add(button); //adds button to frame

        frame.setSize(200,200); //pixel size of frame in width then height

        frame.setVisible(true); //if false then frame will be invisible

    }

    public void actionPerformed(ActionEvent event){ //if button is pressed then this changes button text
        button.setText("I was pressed!");
    }

}

——-

Java Button with detection/action
Java Button with detection/action

This attempt uses the Java event package to “listen” for the button click and if detected the button text changes from “geektechstuff.com” to “I was pressed!”.

I then added another line so that the frame window would have a title.

frame.setTitle("GeekTechStuff.com"); //sets title on window
Java - Setting a title on the frame window
Java – Setting a title on the frame window