2016-09-25 7 views
0

私はこのコードをテキストフィールドでenterを押すのではなく、追加ボタンとして機能させようとしています。 ボタンとして機能するようにaddメソッドを変更しようとしています

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 god私はアクションリスナーを追加するために少なくとも10の方法を試してみた – user6860301

答えて

0

は、私はあなたがコンソールの代わりにシンプルなGUIを使用したいと思い、ボタンプッシュに拾っていないボタンを押したときに何もしませんいくつかの値を入力します。あなたのコードは完全ではありません - あなたが達成したいことが何であるかははっきりしませんが、私はあなたに役立つ参考にしました。

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(); 
    } 
} 
関連する問題