How to use variables defined in a public class in other classes in java?

南笙酒味 提交于 2020-01-21 09:49:09

问题


A layman's question on the definition and use of variables:

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).

How can I do this? Are global variables the only way?

In my code I first define 'textfield' as JTextField and then I want it to be read (as 'text') and stored (in 'text.txt').

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
              }
            }

When I compile I get

Runcommand33.java:45: error: cannot find symbol
                String text = textfield.getText();
                              ^
  symbol:   variable textfield
  location: class ButtonHandler

Without lines String text = to new BufferedWriter the code compiles.

Note that I have tried the suggestions of this Get variable in other classes and this How do I access a variable of one class in the function of another class? but they didn't work.

Any suggestions?


回答1:


Let's look at this from a design perspective: ButtonHandler sounds a little too generic. In what way is the button click "handled"? Ah, it saves the contents of the text field to a file, so it should be called "TextFieldSaver" (or preferably something less lame).

Now, a TextFieldSaver needs to have a text field to save, yes? So add a member variable to hold the text field, and pass the text field created in the main class through a constructor:

    button.addActionListener(new TextFieldSaver(textfield));

....

class TextFieldSaver implements ActionListener {
    JTextField textfield;
    public TextFieldSaver(JTextField toBeSaved) {
        textfield = toBeSaved;
    }
    public void actionPerformed(ActionEvent event) {
        String text = textfield.getText();
        textfield.setText("");
        new BufferedWriter(new FileWriter("text.txt")).write(text).newLine().close();
    }
}

This isn't the only way to do it, nor necessarily the best way, but I hope it shows how using proper names sometimes shows a way out.




回答2:


How about using an anonymous inner class, and make the textfield variable final:

button.addActionListener(new 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              
    }
});

Note, you would need to declare the textfield as final:

final JTextField textfield = new JTextField();



回答3:


There is no global variable in java. each class can have some public fields. and other class may access them

you can use them like this:

class A{
    public String text;
}

class B{
    public static void main(String []args){
        A a= new A();
        System.out.println(a.text);
    }
}


来源:https://stackoverflow.com/questions/18090959/how-to-use-variables-defined-in-a-public-class-in-other-classes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!