Sterling Duchess
Sterling Duchess

Reputation: 2080

Static method to assign non static variable

I have two clases GUI ( That renderes my main JFrame ) and Print class ( That is invoked by JButton on GUI class ). Now on my GUI Class i have JTextArea and a method:

void setOutput(String data)
{
   // output is JTextArea
   output.setText(data);
}

However the data is provided the the Print JFrame where i have a JButton with action listener:

sizOpt.addActionListener(new ActionListener()
{       
    @Override
    public void actionPerformed(ActionEvent event)
    {
       // textfield is a JTextField component
       String data = textfield.getText();   


       // My problem is here i need to invoke the setOutput
       // method in GUI to output the string however i cant call that method in
       // any way but making it static or calling new GUI which will create a new
       // Instance of GUI class
       GUI.setOutput(data);
    }
});

Upvotes: 1

Views: 1642

Answers (2)

Neil Coffey
Neil Coffey

Reputation: 21795

Make a static reference to the instance of your JFrame subclass, with an appropriate instance method on the JFrame to retrieve the text.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

The answer: don't use static anything here at all.

The only thing that should be static is your main method, and that's probably it. If you need to call a method on the GUI, then call it on an instance of the visualized GUI, not as a static method. Often the tricky part is getting that valid reference, and you are correct that you shouldn't create a new GUI object, but again don't try to do a non-working static solution. Some ways to get the valid reference are via a constructor parameter or a setter method.

i.e.,

public class PrintJFrame extends JFrame {
  private GUI gui;

  public PrintJFrame(GUI gui) {
    this.gui = gui;
  }

  // ...
}

Now in your ActionListener you can call a method on the correct GUI reference held by the gui variable. Next we'll talk about why you should avoid having classes extend JFrames and similar GUI components. Next we'

Upvotes: 2

Related Questions