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?
You can also use lambda-function: JButton button = new JButton("click me"); button. addActionListener(e -> { // your code here });
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? 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.
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();
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()); } }); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With