2017-03-15 12 views
0

ActionListerを2つ使用して同じアクションを実行できますが、実装を使用してコードを圧縮しますが、動作しません。 b1を選択すると、テキストフィールドにテキストはありません。JPanelとActionListerが動作しません

public Radio_Button() { 
     setSize(600, 400); 
     panel = new JPanel(); 
     tf = new JTextField("    "); 
     group = new ButtonGroup(); 
     b1 = new JRadioButton("1"); 
     b2 = new JRadioButton("2"); 
     b1.setActionCommand("you choose one"); 
     b2.setActionCommand("you choose two"); 
     group.add(b1); 
     group.add(b2); 
     panel.add(b1); 
     panel.add(b2); 
     panel.add(tf); 
     add(panel); 

    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // TODO Auto-generated method stub 
     tf.setText(e.getActionCommand()); 

    } 
} 
+0

を持っている場合は

b1.addActionListener(this); b2.addActionListener(this); 

[ActionListenerを書く方法](https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html)かもしれませんより良いリソースになる – MadProgrammer

+0

初めてこのサイトが表示されます。私に知らせてくれてありがとう – zoey

答えて

0

ラジオボタンのリスナーを登録するのは忘れてしまいます。

setActionCommand()の後に追加します。あなたが異なるボタン

JButton button1 = new JButton("Some Text"); 
JButton button2 = new JButton("Some Other Text"); 

    button1.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      JOptionPane.showMessageDialog(null, "I was clicked !"); 
     } }); 

    button2.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      JOptionPane.showMessageDialog(null, "Second button was clicked!"); 
     } }); 
+0

Thx!私はこれが必要ではないと思った。パネルに別のボタンがある場合でも、私が押してもポップアップウィンドウが表示されるようにすることもできます。この実装されたActionListerでも使用できますか、それともそれらを実装する必要がありますか? – zoey

+0

私はあなたのためにそれらを作ることをお勧めします。 –

関連する問題