如何在java中的其他类中使用公共类中定义的变量?

外行人对变量的定义和使用的问题:

我需要创建一个Java GUI来获取用户的输入并将其存储在文本文件中。 但是,这篇文章必须在Actionlistener类中完成(即,用户单击按钮并创建并存储文本文件)。 这意味着我必须在一个类(公共类)中定义一个变量,并在另一个类(定义Actionlistener的那个)中使用它。

我怎样才能做到这一点? 全局变量是唯一的方法吗?

在我的代码中,我首先将’textfield’定义为JTextField然后我希望它被读取(作为’text’)并存储(在’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 } } 

当我编译我得到

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

没有行String text = to new BufferedWriter代码编译。

请注意,我在其他类中尝试了此Get变量的建议,以及如何在另一个类的函数中访问一个类的变量? 但他们没有工作。

有什么建议么?

让我们从设计角度来看这个: ButtonHandler听起来有点过于通用。 按钮点击“处理”的方式是什么? 啊,它将文本字段的内容保存到文件中,因此它应该被称为“TextFieldSaver”(或者最好是不那么蹩脚的东西)。

现在,TextFieldSaver需要有一个文本字段来保存,是吗? 因此,添加一个成员变量来保存文本字段,并通过构造函数传递在主类中创建的文本字段:

  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(); } } 

这不是唯一的方法,也不是最好的方法,但我希望它能说明使用专有名词有时会显示出一条出路。

如何使用匿名内部类,并使textfield变量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 } }); 

注意,您需要将textfield声明为final

 final JTextField textfield = new JTextField(); 

java中没有全局变量。 每个class级都有一些公共领域。 和其他class级可以访问它们

你可以像这样使用它们:

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