1
我的任务是检索文本字段的值,并在点击按钮时将其显示在警告框中。如何在java swing中为按钮生成点击事件?如何创建点击事件按钮在秋千?
我的任务是检索文本字段的值,并在点击按钮时将其显示在警告框中。如何在java swing中为按钮生成点击事件?如何创建点击事件按钮在秋千?
对于这一点,你需要使用ActionListener
,例如:
JButton b = new JButton("push me");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//your actions
}
});
对编程产生点击事件,您可以使用JButton
doClick()
方法:b.doClick();
首先,用一个按钮,分配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());
}
});
}
}
当按钮被正常点击时使用'actionPerformed'方法。如果你想与按钮做一些奇妙的交互,你也可以使用[其他事件](http://docs.oracle.com/javase/tutorial/uiswing/events/),比如MouseListener中的mousePressed。 – SebastianH
@Suresh我知道你一直在使用GUI Builder。你需要做的是从设计视图中右键单击该按钮,然后选择“Events - > Action - > actionPerformed”,然后你会在源代码中看到自动生成的代码。Alex + –