2014-02-19 37 views

回答

6

对于这一点,你需要使用ActionListener,例如:

JButton b = new JButton("push me"); 
b.addActionListener(new ActionListener() { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     //your actions 
    } 
}); 

对编程产生点击事件,您可以使用JButtondoClick()方法:b.doClick();

+0

当按钮被正常点击时使用'actionPerformed'方法。如果你想与按钮做一些奇妙的交互,你也可以使用[其他事件](http://docs.oracle.com/javase/tutorial/uiswing/events/),比如MouseListener中的mousePressed。 – SebastianH

+0

@Suresh我知道你一直在使用GUI Builder。你需要做的是从设计视图中右键单击该按钮,然后选择“Events - > Action - > actionPerformed”,然后你会在源代码中看到自动生成的代码。Alex + –

0

首先,用一个按钮,分配ActionListener,在其中使用JOptionPane显示消息。

class MyWindow extends JFrame { 

    public static void main(String[] args) { 

     final JTextBox textBox = new JTextBox("some text here"); 
     JButton button = new JButton("Click!"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(this, textBox.getText()); 
      } 
     }); 
    } 
}