一个外行人关于变量定义和使用的问题:
我需要制作一个 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
不带线字符串文本= to 新的缓冲写入器代码编译。
请注意,我已经尝试过此建议获取其他类中的变量和这个如何在另一个类的函数中访问一个类的变量?但他们没有工作。
有什么建议么?
让我们从设计的角度来看一下: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();
}
}
这不是唯一的方法,也不一定是最好的方法,但我希望它表明使用正确的名称有时会显示出一条出路。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)