Quick GUI in Java

in #technology15 hours ago

image.png

Previously we looked at a Java terminal application for generating 'Hello World!', today let's get graphical!

Java is mainly thought of as either an Android app development language or the language of massive corporations, but that is not strictly true. A lot of desktop software that we use daily is quietly developed in Java.

We might not realize we are using a Java app because Java apps do not have a particular 'look', and that is because there are frameworks that give us a lot of control over the appearance of our interfaces.

The two major approaches are called JavaFX and Swing.

JavaFX vs Swing

JavaFX is a modern, actively maintained Java project for developing graphical user interfaces (GUIs).

Modern means it has advanced features like CSS styling, FXML for declarative UI design, and better animation support. It also includes graphics primitives like rectangles and text, 3D features, and a web view.

Swing on the other hand is an older framework (~1998) that's not actively improved any longer but is bundled as default, and while it is is mainly used for maintaining legacy systems, there are still a lot of people who use it due to its simplicity and immediacy.

I was surprised to find out, that a popular Java IDE that I use called IntelliJ is built using Swing.

Due to it being simple and right there ready to use without any additional installation, it also makes it ideal for learning, so many people start with Swing before progressing to JavaFX.

Write a Swing App in 2 Minutes

To demonstrate how quickly you can get a quick and dirty GUI app running in Java let's build a simple example of a question-and-answer dialog box type wizard.

import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        
        String name = JOptionPane.showInputDialog("Enter your name");
        JOptionPane.showMessageDialog(null, "Hello "+name);
        
    }   
}

image.png

image.png

Windowed GUI Apps with Java Swing

You are not restricted to dialog boxes, we can create fully windowed applications with just a few more instructions.

For example, let's make a graphical version of 'Hello World'.

image.png

import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class hellogui {



    public static void main(String[] args) {
                
        // create a new label
        JLabel label = new JLabel(); 
        label.setText("Hello World!");

        // set text color to blue
        label.setForeground(new Color(0x0000FF));
        
        // create an icon
        ImageIcon icon = new ImageIcon("java.png");
        label.setIcon(icon);

        // create a window ('frame')
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(label);

        // make the window fit the contents
        window.pack();
        window.setVisible(true);     

    }

    
}

Notice where we say window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - that is necessary because otherwise, the application will keep running even when the last window is closed. This is because Java doesn't know if you are creating a multi-window app where closing a window might not be the end of your interaction with the software.

Adding Interaction using Buttons and Events

For the final example today let's add some interactivity in the form (sorry) of a button that initiates an action.

Since we are still using the default layout, the order in which we add our form elements matters. In the future you will not be so constrained, we are just sticking to the default layout for brevity right now.

import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class hellogui {



    public static void main(String[] args) {
                
        // create a new label
        JLabel label = new JLabel(); 
        label.setText("Hello World!");

        // set text color to blue
        label.setForeground(new Color(0x0000FF));
        
        // create an icon
        ImageIcon icon = new ImageIcon("java.png");
        label.setIcon(icon);
        label.setVisible(true);

        // create a window ('frame')
        JFrame window = new JFrame();
        //window.setLayout(null);
        window.setSize(800,600);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        // clickable button
        JButton button = new JButton("OK");  
        button.addActionListener(new ActionListener() {
            
           public void actionPerformed(ActionEvent e) {
            if(e.getSource()==button) {
                
                label.setText("CLICK!");
            }   
        }});
        button.setBounds(0, 120, 250, 50);
        window.add(button);
        window.add(label);

        // make the window fit the contents
        window.pack();
        window.setVisible(true);     

    }



    
}

The button itself is as simple as adding a label, but it has an extra piece where we tell Java that we need to listen out for 'actions' which are the event messages informing us that something has happened.

Our event handler is added right there in our example to keep things all in one code listing, but they need not be if you prefer to separate this out.

The function is passed e which we interrogate to see if it was generated by the button. If not we ignore it, otherwise we set the label text.

Just to show this is a cross-platform application, here it is developed on Linux, running on a Mac, and without re-compiling :)

image.png

Sort:  

That is really a nice tip for Java!

Loading...

Curious about HivePakistan? Join us on Discord!

Delegate your HP to the Hivepakistan account and earn 90% of curation rewards in liquid hive!

50 HP
100 HP
200 HP
500 HP (Supporter Badge)
1000 HP

Follow our Curation Trail and don't miss voting!

Additional Perks: Delegate To @ pakx For Earning $PAKX Investment Token


Curated by gwajnberg

Loading...

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).


 
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 

Loading...