Minimal Java Code for a GUI Program

(c) 2016 by Barton Paul Levenson


Language:
Java

Dialect:
NetBeans IDE

Discussion:
Creating a GUI program in Java is unbelievably convoluted. Any event for a control needs an "action listener." If you try to assign the main program (always main) as the action listener, you get an error message that you can't do that with a static method. And main must always be declared static. You could go crazy trying to figure out how to make this work. Here's the key, which I had to find out myself:

You must instantiate an object of the class main appears in, inside main, and run that from main (Got it?).

Then you can assign that as the action listener, and suddenly everything works. Examine the example below, and try running it on your own Java software:



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

public class Gui implements ActionListener {
    public static void main(String[] args) throws Exception {
        Gui obj = new Gui();
        obj.run(args);
    } // main

    @Override
    public void actionPerformed(ActionEvent e) {
        JFrame msg = new JFrame("message");
        JLabel ms = new JLabel("Boo!");
        
        msg.add(ms);
        msg.setSize(100,100);
        msg.setVisible(true);
    } // actionPerformed
    
    public void run (String[] args) throws Exception {
        JFrame mainWindow = new JFrame("GUI Example");
        JButton goButton = new JButton("Go");
        goButton.addActionListener(this);
        
        mainWindow.add(goButton);
        mainWindow.setSize(300,300);
        mainWindow.setVisible(true);
    } // run
} // gui


Page created:05/06/2016
Last modified:  05/06/2016
Author:BPL