Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create on click event for buttons in swing?

Tags:

My task is to retrieve the value of a text field and display it in an alert box when clicking a button. How do I generate the on click event for a button in Java Swing?

like image 533
Suresh Avatar asked Feb 19 '14 11:02

Suresh


People also ask

How do you add an event on button in swing?

You can also use lambda-function: JButton button = new JButton("click me"); button. addActionListener(e -> { // your code here });

How can you handle an event in a swing program having a button?

Step 1 − The user clicks the button and the event is generated. Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object. Step 3 − Event object is forwarded to the method of the registered listener class.

What method is called when a user clicks a button on a Swing GUI?

What method is called when a user clicks a button on a Swing GUI? The actionPerformed method is used when a button is clicked normally. If you want to do some fancy interaction with the button you can also use other events like mousePressed in the MouseListener.19-Feb-2014.


2 Answers

For that, you need to use ActionListener, for example:

JButton b = new JButton("push me"); b.addActionListener(new ActionListener() {      @Override     public void actionPerformed(ActionEvent e) {         //your actions     } }); 

For generating click event programmatically, you can use doClick() method of JButton: b.doClick();

like image 79
alex2410 Avatar answered Oct 14 '22 08:10

alex2410


First, use a button, assign an ActionListener to it, in which you use JOptionPane to show the message.

class MyWindow extends JFrame {      public static void main(String[] args) {          final JTextBox textBox = new JTextBox("some text here");         JButton button = new JButton("Click!");         button.addActionListener(new ActionListener() {             @Override             public void actionPerformed(ActionEvent e) {                 JOptionPane.showMessageDialog(this, textBox.getText());             }         });     } } 
like image 40
Shocked Avatar answered Oct 14 '22 08:10

Shocked