繁体   English   中英

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

[英]How to use variables defined in a public class in other classes in 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

如果没有行,则将字符串text =转换新的BufferedWriter

请注意,我已经尝试了在其他类中使用此Get变量的建议,并且该如何在另一个类的函数中访问一个类的变量? 但是他们没有用。

有什么建议么?

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

让我们从设计的角度来看一下: ButtonHandler听起来有点过于通用。 按钮以什么方式单击“处理”? 嗯,它会将文本字段的内容保存到文件中,因此应将其称为“ TextFieldSaver”(或最好不要太la脚)。

现在,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中没有全局变量。 每个班级可以有一些公共领域。 其他班级可能会访问它们

您可以像这样使用它们:

class A{
    public String text;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM