2012-05-31 58 views
0

我有麻烦添加一个actionlistener到我的JTextField。我需要从用户输入的文本到一个字符串,所以我可以使用它。GridBagLayout中的JTextField ActionListener

任何人都可以告诉我什么即时通讯做错了或我应该怎么做。

下面是代码:

public void actionPerformed(ActionEvent e) 
     { 
      //Execute when button is pressed 
      JFrame frame = new JFrame("Value Bet"); 
      frame.setVisible(true); 
      frame.setSize(500,300); 
      GridBagLayout layout = new GridBagLayout(); 
      frame.setLayout(layout); 
      GridBagConstraints c = new GridBagConstraints(); 

      JLabel label; 
      JTextField tf; 

      if (shouldFill) { 
      //natural height, maximum width 
      c.fill = GridBagConstraints.HORIZONTAL; 
      } 
      if (shouldWeightX) { 
      c.weightx = 0.5; 
      } 

      ... 

      tf = new JTextField(); 
      c.fill = GridBagConstraints.HORIZONTAL; 
      c.gridx = 1; 
      c.gridy = 2; 
      frame.add(tf, c); 
      tf.addActionListener(new ActionListener(){ 
       public void actionPerformed(ActionEvent e) 
       { 
        String chance1 = tf.getText(); 
       } 
      }); 

... 

回答

1

你为什么要使用ActionListener代替KeyListener

您应该使用KeyListener或:

tf.getDocument().addDocumentListener(documentListener); 

DocumentListener

+0

文档监听器是否允许我将用户输入存储在变量中?如何? –

1
public void actionPerformed(ActionEvent e) 
{ 
    // Look Ma, a one-liner! 
    String chance1 = JOptionPane.showInputDialog(someComponent, "Value Bet"); 
} 

option pane one-liner

深入了解一下重载方法来调整一下,为的鲁棒性增加null检查,并考虑使用微调而不是文本字段(BNI)。