【发布时间】:2012-03-23 02:31:18
【问题描述】:
如何通过按下 JButton 来调用方法?
例如:
when JButton is pressed
hillClimb() is called;
我知道如何在按下 JButton 时显示消息等,但想知道是否可以这样做?
非常感谢。
【问题讨论】:
如何通过按下 JButton 来调用方法?
例如:
when JButton is pressed
hillClimb() is called;
我知道如何在按下 JButton 时显示消息等,但想知道是否可以这样做?
非常感谢。
【问题讨论】:
如果您知道如何在按下按钮时显示消息,那么您就已经知道如何调用方法,因为打开新窗口就是调用方法。
有了更多细节,您可以实现ActionListener,然后在您的JButton 上使用addActionListener 方法。 Here 是一个关于如何编写 ActionListener 的非常基础的教程。
你也可以使用匿名类:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});
【讨论】:
yourButton.addActionListener(e -> hillClimb());
这是一个简单的应用程序,展示了如何声明和链接按钮和 ActionListener。希望它能让你更清楚。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}
【讨论】:
先初始化按钮,然后将 ActionListener 添加到它
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
【讨论】:
您需要将事件处理程序(Java 中的ActionListener)添加到JButton。
This article 解释了如何做到这一点。
【讨论】:
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
使用 lambda
【讨论】: