[英]Is it possible: trigger JButton events via method call - not JButton clicks?
[英]Java - Call Method via JButton
如何通過按JButton調用方法?
例如:
when JButton is pressed
hillClimb() is called;
我知道如何在按下JButton時顯示消息等,但是想知道是否可以這樣做?
非常感謝。
如果您知道如何在按下按鈕時顯示消息,那么您已經知道如何調用方法,因為打開新窗口就是對方法的調用。
有關更多詳細信息,可以實現ActionListener
,然后在JButton上使用addActionListener
方法。 這是有關如何編寫ActionListener
的非常基本的教程。
您也可以使用匿名類:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent 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();
}
});
您需要向JButton
添加事件處理程序(Java中的ActionListener
)。
本文介紹了如何執行此操作。
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
帶lambda
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.