Java - 通过JButton调用方法

9

如何通过按下JButton来调用一个方法?

例如:

when JButton is pressed
hillClimb() is called;

我知道如何在按下JButton时显示消息等内容,但想知道是否可能做到这一点?

非常感谢。


1
请查看http://docs.oracle.com/javase/tutorial/uiswing/components/button.html。 - DNA
5个回答

11
如果您知道如何在按下按钮时显示消息,那么您已经知道如何调用一个方法来打开一个新窗口。
更具体地说,您可以实现一个ActionListener,然后在JButton上使用addActionListener方法。这里有一个非常基础的教程介绍如何编写ActionListener:这里
您也可以使用匿名类:
yourButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
        hillClimb();
    } 
});

4
自 Java 8 开始,可以使用 Lambda 表达式更简洁地编写相同的代码:yourButton.addActionListener(e -> hillClimb()); - Lii

4

这是一个简单的应用程序,展示了如何声明和链接按钮和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!!!!!");
    }
}

1

您需要为JButton添加一个事件处理程序(在Java中为ActionListener)。

本文解释了如何实现此操作。


1
首先初始化按钮,然后为其添加ActionListener。
JButton btn1=new JButton();

btn1.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
        hillClimb();
   }
});

0
    btnMyButton.addActionListener(e->{
        JOptionPane.showMessageDialog(null,"Hi Manuel ");
    });

使用lambda表达式


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接