Search code examples
javabuttonrepositorypreferences

Store a String variable in Java to use it later


I have a question. In my app I have a button, when I click on it a text is saved in a String variable, when the variable is not inside to action button the value is NULL, How can I make to save the value from the variable and use it later.

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();
            }
        }); 

    }  
}

All I want is when I exit from public void actionPerformed(ActionEvent e) the String tstr1 keep the saved data.


Solution

  • Define it outside of function as object member

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