【问题标题】:How to use variables defined in a public class in other classes in java?java - 如何在java中的其他类中使用公共类中定义的变量?
【发布时间】:2013-08-08 02:18:19
【问题描述】:

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

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

我该怎么做?全局变量是唯一的方法吗?

在我的代码中,我首先将“textfield”定义为 JTextField,然后我希望它被读取(作为“文本”)并存储(在“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? 但他们没有工作。

有什么建议吗?

【问题讨论】:

    标签: java class variables file-io


    【解决方案1】:

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

    这不是唯一的方法,也不一定是最好的方法,但我希望它能说明使用专有名称有时会带来出路。

    【讨论】:

    • 哇,它成功了!非常感谢。确实有用的评论。虽然我现在更困惑:(让我回顾一下:我在 A 类中定义了一个变量。我使用这个变量设置了一个构造函数。变量在 B 类中获取它的值,然后返回给 A 类。对吧?太棒了。现在解释:什么 A. ActionListener{JTextField textfield; ...} 和 B. textfield = toBeSaved; 是什么意思???我们必须定义多少次'textfield'?为什么,在我的程序的原始版本中,我的类 B 会无法识别变量“文本字段”?再次感谢。
    • 这些确实应该是他们自己的问题,但是: A 是一个接收参数的构造函数。 B 是一个变量赋值。 C 变量被定义为局部变量,因此它的可见性仅限于它声明的块。这是非常基本的东西,阅读有关 Java 编程的书可能是个好主意。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      java 中没有全局变量。每个类都可以有一些公共字段。其他班级可以访问它们

      你可以像这样使用它们:

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

      【讨论】:

      • 因为textfield 是局部变量,您只能在该函数上使用它,不能在其他函数上使用,也不能在其他类上使用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      相关资源
      最近更新 更多