How to create on click event for buttons in swing?
Matthew Harrington
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?
3 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();
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()); } }); }
} 1 You can also use lambda-function:
JButton button = new JButton("click me");
button.addActionListener(e ->
{ // your code here
});However, if you mean signals and slots like in Qt, then Swing does not support this. But you can always implement this yourself using the "Observer" pattern (link).