gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:17:09 25 4
gpt4 key购买 nike

一个外行人关于变量定义和使用的问题:

我需要制作一个 Java GUI 来获取用户的输入并将其存储在文本文件中。然而,这种写入必须在 Actionlistener 类内完成(即,用户单击按钮并创建和存储文本文件)。这意味着我必须在一个类(公共(public)类)中定义一个变量,并在另一个类(定义 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 =new BufferedWriter 代码就会编译。

请注意,我已经尝试过此建议 Get variable in other classes和这个 How do I access a variable of one class in the function of another class?但他们没有工作。

有什么建议吗?

最佳答案

让我们从设计的角度来看这个: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();
}
}

这不是唯一的方法,也不一定是最好的方法,但我希望它表明使用正确的名称有时会显示出一条出路。

关于java - java中如何在其他类中使用公共(public)类中定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com