2017-09-20 31 views
1

我是新来的java,我有以下问题: 我添加了一个ActionListener到一个按钮,我想从它访问一个数字,但它不工作的方式。我找到了它,但我找不到答案。 代码看起来像现在这样:如何从ActionListener获取整数?

public class example extends JPanel{ 

    int text; 

    public example(){ 

     JButton button = new JButton("x"); 
     JTextField textField = new JTextField(); 

     add(textField); 
     add(button); 

     ActionListener al = new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent event) { 
       text = Integer.parseInt(textField.getText()); 
      } 
     } 

     button.addActionListener(al); 
     system.out.println(text); 
    } 
} 

回答

2

问题是你的逻辑。您将ActionListener添加到按钮。因此,无论何时按下按钮,文本的值是textField的值。但文本的初始值为空。 在您的代码中,添加ActionListener之后,会打印文本的值。你可能想改变你的ActionListener这样的:

ActionListener al = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent event) { 
     text = textField.getText(); 
     someFun(); 
     system.out.println(text); 
    } 
} 

从字符串获取整数,使用的Integer.parseInt()函数

void someFun() { 
    int num = Integer.parseInt(text); 
    ... // Do whatever you want to do 
} 
+0

问题与逻辑有关。 – Dungnbhut

+0

是的,它可以工作,但是我怎样才能得到ActionListener外部的Integer? – Andy

+0

检查编辑。我想你应该看看Java的基础知识 – npk

0

您必须声明文本变量作为最终的行动听众的顶部。

public class example extends JPanel{ 

final String text; 

public example(){ 

    JButton button = new JButton("x"); 
    JTextField textField = new JTextField(); 

    add(textField); 
    add(button); 

    ActionListener al = new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent event) { 
      text = textField.getText(); 
     } 
    } 

    button.addActionListener(al); 
    system.out.println(text); 
} 

}

+0

这是行不通的。 Eclipse想要删除**“最终”** ......有没有办法解决? – Andy