Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use variables defined in a public class in other classes in java?
    text
    copied!<p>A layman's question on the definition and use of variables:</p> <p>I need to make a Java GUI that gets user's input and stores it within a text file. However this writing has to be done inside an Actionlistener class (ie, user is clicking the button and text file is created and stored). This means that I have to define a variable in one class (public class) and use it in another (the one that defines the Actionlistener).</p> <p>How can I do this? Are global variables the only way?</p> <p>In my code I first define 'textfield' as JTextField and then I want it to be read (as 'text') and stored (in 'text.txt').</p> <pre><code>import javax.swing.*; //... import java.io.BufferedWriter; public class Runcommand33 { public static void main(String[] args) { final JFrame frame = new JFrame("Change Backlight"); // ... // define frames, panels, buttons and positions JTextField textfield = new JTextField();textfield.setBounds(35,20,160,30); panel.add(textfield); frame.setVisible(true); button.addActionListener(new ButtonHandler()); } } class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ String text = textfield.getText(); textfield.setText(""); new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close(); // Afterwards 'text' is needed to run a command } } </code></pre> <p>When I compile I get</p> <pre><code>Runcommand33.java:45: error: cannot find symbol String text = textfield.getText(); ^ symbol: variable textfield location: class ButtonHandler </code></pre> <p>Without lines <em>String text =</em> to <em>new BufferedWriter</em> the code compiles.</p> <p>Note that I have tried the suggestions of this <a href="https://stackoverflow.com/questions/15999934/get-variable-in-other-classes">Get variable in other classes</a> and this <a href="https://stackoverflow.com/questions/10230274/how-do-i-access-a-variable-of-one-class-in-the-function-of-another-class">How do I access a variable of one class in the function of another class?</a> but they didn't work.</p> <p>Any suggestions?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload