我想知道如何从这段代码中检索字符串textOperandValue:
final JTextField textOperand = new JTextField();
textOperand.setBounds(200,100,75,25);
//textOperand action Listener
textOperand.addActionListener( new ActionListener () {
public void actionPerformed(ActionEvent e) {
String textOperandValue = textOperand.getText();
}
});
所以我可以接受它,然后将其解析为 double 型,以便稍后在程序中使用。我尝试将其设置为等于另一个字符串
字符串输入=“”;
但它说我必须将字符串初始化为 Final String Input = "";
我了解到它类似于 C++ 中的常量。
最佳答案
您在 ActionListener 中声明的任何变量对于代码的其余部分都是不可见的。您需要设置一个具有更广泛范围的变量(在监听器内):
public class Listen
{
String usefulResult = null;
public Listen()
{
final JTextField textOperand = new JTextField();
textOperand.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Listen.this.usefulResult = textOperand.getText();
}
});
}
}
这里我们使用“OuterClass.this”技巧来访问周围的范围,而不需要最终变量。
或者您需要从监听器本身执行所有必要的工作(即您不“检索”该值,您只需使用该值):
public void doSomethingUseful(String usefulValue) { /* add code here */ }
textOperand.addActionListener( new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
doSomethingUseful(textOperand.getText());
}
});
或者您可以使用第二种技术来调用更改变量值的 setter 方法,从而避免在事件监听器中访问最终变量的问题:
public class Listen
{
String usefulResult = null;
public void setUseful(String usefulValue){
usefulResult = usefulValue;
}
public Listen()
{
final JTextField textOperand = new JTextField();
textOperand.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setUseful(textOperand.getText());
}
});
}
}
这取决于您想要如何处理 TextField 中的值。
关于java - 从匿名类中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23014455/