在 Java 中存储一个 String 变量以备后用

Store a String variable in Java to use it later

我有一个问题。在我的应用程序中,我有一个按钮,当我单击它时,文本将保存在一个字符串变量中,当该变量不在操作按钮内部时,该值为 NULL,我该如何保存变量中的值并使用它之后。

private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 413, 445);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnNewButton = new JButton("Word for Search");
        btnNewButton.setBounds(223, 62, 118, 23);
        frame.getContentPane().add(btnNewButton);

        textField = new JTextField();
        textField.setBounds(35, 63, 131, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);


        btnNewButton.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            search = textField.getText();
            System.out.println("String for car = " + search); 
        WebDriver driver = new FirefoxDriver();
        driver.get("https://en.wikipedia.org/wiki/" + search);
        String tstr1 = driver.findElement(By.xpath("//*[@id='content']")).getText();
        System.out.println("String for car = " + tstr1);

        driver.close();
            }
        }); 

    }  
}

我只想在退出 public void actionPerformed(ActionEvent e)String tstr1 保留保存的数据。

在函数之外将其定义为对象成员

    ...
    private String tstr1;
    ...
    private void initialize() {
        ...
        btnNewButton.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ...
                tstr1 = driver.findElement(By.xpath("//*[@id='content']")).getText();
                ...
            }
        });
    }  

您可以在 class 中创建一个字段作为

private String tstr1;

在你的方法中你可以赋值

tstr1 = driver.findElement(By.xpath("//*[@id='content']")).getText();

当需要访问字段时,可以调用

tstr1;

这不是一个很好的做法,但您是否尝试过将您的 var 声明为全局变量?

这样您的 var 就可以根据需要保留值。

private String globalString;

private void functions() {
   ...
} 

没错,你需要做的就是定义一个全局变量。如果你想从 class 之外访问变量,你可以简单地添加一个 Getter:

public String getTStr1() { return tstr1; }

如果您有许多要保存的字符串,只需以全局方式使用列表,例如,

private List<String> tStrings = new ArrayList<String>();

并将每个 tstr1 添加到列表中

tStrings.add(tstr1);

那么您不需要全局 tstr1 字段。