Java - call method via JButton

How can I call a method by pressing the JButton button?

For example:

when JButton is pressed hillClimb() is called; 

I know how to display messages, etc. when you click JButton, but want to know if this can be done?

Many thanks.

+7
source share
5 answers

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

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

You can also use an anonymous class:

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

Here is a trivial application showing how to declare and associate a button and an ActionListener. Hope this makes things more clear to 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!!!!!"); } } 
+4
source

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

This article explains how to do this.

+1
source

Click the initialize button, then add an ActionListener to it

 JButton btn1=new JButton(); btn1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ hillClimb(); } }); 
+1
source
  btnMyButton.addActionListener(e->{ JOptionPane.showMessageDialog(null,"Hi Manuel "); }); 

with lambda

0
source

All Articles