-2

I want to add a JButton to my script but for some reason I can't add an Action Listener to it. Here's my code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NewJFrame extends javax.swing.JFrame {

    public static void main(String args[]) {

        jButton1.addActionListener(new ActionListener() {    //ERROR here
            public void actionPerformed(ActionEvent le) {
                //Do stuff
            }
        });

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration
    }
}

I get the following error:

non-static variable JButton1 cannot be referenced from a static context

Any help is appreciated, as I am new to the whole GUI stuff

Smirlianos
  • 5
  • 1
  • 6

1 Answers1

0

The code for creating the jButton1 object (private javax.swing.JButton jButton1;) should not be within the main method. This object should be created within the class. Additionally, to access the button from the main method you need to make the button static by adding the static keyword since the main method is static. Therefore the code should look more like

public class NewJFrame extends javax.swing.JFrame {
    private static javax.swing.JButton jButton1;

    public static void main(String args[]) {
jeremyms
  • 319
  • 2
  • 11