Java - Call Method via JButton

只谈情不闲聊 提交于 2019-12-30 03:12:28

问题


How can I call a method by pressing a JButton?

For example:

when JButton is pressed
hillClimb() is called;

I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?

Many thanks.


回答1:


If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.

With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.

You can use an anonymous class too:

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



回答2:


Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.

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!!!!!");
    }
}



回答3:


Fist you initialize the button, then add ActionListener to it

JButton btn1=new JButton();

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



回答4:


You need to add an event handler (ActionListener in Java) to the JButton.

This article explains how to do this.




回答5:


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

with lambda



来源:https://stackoverflow.com/questions/9569700/java-call-method-via-jbutton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!