2016-09-25 36 views
0

我試圖使這個代碼工作作爲一個添加按鈕,而不是隻是按下輸入一個文本字段。試圖改變添加方法作爲一個按鈕

ActionListener cmdLis = new CmdTextListener(); 

    cmdTextField.addActionListener(cmdLis); 

    public void actionPerformed(ActionEvent evt) 
      { 
       String cmdStr = cmdTextField.getText(); 
       Scanner sc = new Scanner(cmdStr); 
       String cmd = sc.next(); 

if (cmd.equals("add")) 
       { 
        int value = sc.nextInt(); 
        binTree.add(value); 

        if(view != null) 
         remove(view); 
        view = binTree.getView(); 
        add(view); 

        pack(); 
        validate(); 
        cmdResultTextField.setText(" "); 

       } 

所以我試圖做這樣的,但它什麼都不做,當我按下按鈕它甚至沒有拿起按下按鈕

if (e.getSource() == addButton) 
       { 
        //int value = Integer.parseInt(cmd); 

        int value = Integer.parseInt(cmdStr); 
        binTree.add(value); 

        if(view != null) 
         remove(view); 
        view = binTree.getView(); 
        add(view); 

        pack(); 
        validate(); 
        cmdResultTextField.setText("Added "+ value); 

       } 
+0

您是否調用了'addButton.addActionListener(cmdLis);' – guleryuz

+0

請澄清您的問題和您的代碼。我不能爲其他人說話,但不清楚你想要做什麼或代碼做什麼。考慮發佈更詳細和明確的解釋和更好的代碼,最好是[mcve]或[sscce](http://sscce.org)(請閱讀鏈接)。 –

+0

謝謝Guleryuz上帝,我嘗試了10種不同的方式,至少添加了動作偵聽器,那就是我所缺少的 – user6860301

回答

0

我猜你想用簡單的圖形用戶界面,而不是控制檯輸入一些值。你的代碼是不完整的 - 目前還不清楚你想要達到什麼目標,但我爲你做了一些可以幫助你的例子。

public class Main extends JFrame { 

    private JTextField textField; 
    private JButton button; 

    // private YourBinaryTree; 

    public Main() { 

     textField = new JTextField(5); 

     button = new JButton("add to binary tree"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       String read = textField.getText(); 
       Integer number = Integer.parseInt(read); 
       // binTree.add(number); 
      } 
     }); 

     button.setPreferredSize(new Dimension(200, 200)); 

     getContentPane().setLayout(new FlowLayout()); 
     getContentPane().add(textField); 
     getContentPane().add(button); 
     pack(); 
     setVisible(true); 
    } 

    public static void main(String[] args) { 
     new Main(); 
    } 
}