Craig
Craig

Reputation: 685

Java GUI/OOP variable issues

I'm new to using GUI's in Java, so i'm trying to adapt a sat-nav system i've wrote in the console to work in a gui. I've designed a form, and i'm trying to get the program so that on a button click it will access a function from a class - however in the JFrame class, i'm having issues trying to get access to a variable I created in the main.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        //graph.gatherData();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */

        }

        //</editor-fold>
        Engine graph = new Engine();
        graph.addNode("Aberdeen", 391, 807);
        graph.addNode("Blackpool", 331, 434);
        graph.addNode("Bristol", 358, 173);
        graph.addNode("Cardiff", 319, 174);

In the jButton1ActionPerformed function, I'd like to be able to access graph. I tried to define it elsewhere but it won't work. Could someone explain how to solve this issue?

Upvotes: 0

Views: 57

Answers (1)

Subler
Subler

Reputation: 657

Its because the main method is a static method. Create an instance of this class and in the constructor create your Engine instance (and store it as a variable in your class).

Edit: Some code to go with that:

public class MyClass {
    private Engine graph;

    public MyClass(){
        graph = new Engine();
        graph.addNode("Aberdeen", 391, 807);
        graph.addNode("Blackpool", 331, 434);
        graph.addNode("Bristol", 358, 173);
        graph.addNode("Cardiff", 319, 174);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

        //graph.gatherData();
    }  

     /**
     * @param args the command line arguments
     */
    public static void main(String[] args){
         /* Set the Nimbus look and feel */

        //Create instance of your class (im assuming your jframe?)
        new MyClass();
    }
}

Upvotes: 1

Related Questions