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.
Not a very good practice but have you tried declaring your var as global?
This way your var can keep the value as long as you want.
private String globalString;
private void functions() {
...
}
you can create a field in your class as
private String tstr1;
and inside your method you can assign value
tstr1 = driver.findElement(By.xpath("//*[@id='content']")).getText();
when you need to access the field, you can call
tstr1;
Exactly, all you need to do is to define a global variable. If you want to access the variable from outside the class you could simply add a Getter:
public String getTStr1() { return tstr1; }
If you have many Strings you want to save just use a List in a global way, eg,
private List<String> tStrings = new ArrayList<String>();
and add each tstr1 to the list
tStrings.add(tstr1);
Then you do not need a global tstr1 field.
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();
...
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.