portrait
portrait

Reputation: 61

Java JFrame - Access an object instance when an event is triggered

I'm requesting some help in how i would go about accessing a variable (within the jframe) from a method that is called when a button is pressed.

Here is my code:

public class GUI extends javax.swing.JFrame {

/**
 * Creates new form GUI
 */
public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    MyObject myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}

How would i access 'myObject' with buttonActionPerformed()?

Upvotes: 0

Views: 1064

Answers (3)

tzimnoch
tzimnoch

Reputation: 216

Might as well give the answer:

public class GUI extends javax.swing.JFrame {

private MyObject myObject;  // Moved from constructor scope to class scope.

public GUI() {
     myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt)
{                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}

Upvotes: 0

Timothy Wright
Timothy Wright

Reputation: 351

public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    MyObject myObject = new MyObject();
}

In the above code, myObject is a local variable in the GUI() constructor. Once the constructor finishes, that myObject variable is destroyed. Nothing outside the constructor can see it.

You need to make the object a member variable of the class.

public class GUI extends javax.swing.JFrame {

    private MyObject myObject; // member variable

/**
 * Creates new form GUI
 */
public GUI() {
    initComponents();
    //my own objects for registration, matches and reports
    myObject = new MyObject();
}

private void buttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // How would I access 'myObject' here?
    myObject.soSomething();
}

Upvotes: 4

Bart Hofma
Bart Hofma

Reputation: 644

Declare myObject in your class, not in the method

Then where you make the frame:

    JButton button = new JButton("Click me");//The JButton name.
    frame.add(button);//Add the button to the JFrame.
    button.addActionListener(this);//Add a listener to the button

Also add next method to the class, in here you will put the code that schould run upon clicking the button

public void actionPerformed(ActionEvent e) {
    myObject.soSomething();
}

Upvotes: 0

Related Questions