How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display me
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!!!!!");
}
}
Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda
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();
}
});
You need to add an event handler (ActionListener
in Java) to the JButton
.
This article explains how to do this.