2012-05-31 61 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)。