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?
Asked
Active
Viewed 1.6e+01k times
5 Answers
61
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();

alex2410
- 10,904
- 3
- 25
- 41
-
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](http://docs.oracle.com/javase/tutorial/uiswing/events/) like `mousePressed` in the MouseListener. – SebastianH Feb 19 '14 at 11:59
-
2@Suresh I know you've been using GUI Builder. What you need to do is right-click the button from the design view and select `Events -> Action -> actionPerformed` then you will see auto-generated code in the source code.. Alex +1 – Paul Samsotha Feb 19 '14 at 12:04
10
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());
}
});
}
}

Shocked
- 627
- 4
- 13
7
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).

garbart
- 465
- 4
- 19
0
JButton jEightButton=new JButton();
jEightButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jframe.getContentPane().setBackground(Color.blue);
}

mikus
- 3,042
- 1
- 30
- 40

Saleema Peridot
- 1
- 1
0
public GUI() {
JButton btn1 = new JButton("Click me!");
add(btn1);
btn1.addActionListener(new ActionListener()) {
@Override
public void actionPerformed(ActionEvent e) {
//action for the button
}
}
}

Lara Novak
- 1
- 1
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '23 at 09:48