9

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.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Mus
  • 7,290
  • 24
  • 86
  • 130

5 Answers5

11

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();
    } 
});
talnicolas
  • 13,885
  • 7
  • 36
  • 56
  • 4
    Since Java 8 the same thing can be written much prettier using a lambda: `yourButton.addActionListener(e -> hillClimb());` – Lii Aug 28 '15 at 09:33
4

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!!!!!");
    }
}
Jochem Kuijpers
  • 1,770
  • 3
  • 17
  • 34
Aleksandr Kravets
  • 5,750
  • 7
  • 53
  • 72
1

Fist you initialize the button, then add ActionListener to it

JButton btn1=new JButton();

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

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

This article explains how to do this.

Community
  • 1
  • 1
JJ.
  • 5,425
  • 3
  • 26
  • 31
0
    btnMyButton.addActionListener(e->{
        JOptionPane.showMessageDialog(null,"Hi Manuel ");
    });

with lambda

Danh
  • 5,916
  • 7
  • 30
  • 45