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?
5 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();
-
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 likemousePressed
in the MouseListener. Feb 19, 2014 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 Feb 19, 2014 at 12:04
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());
}
});
}
}
-
6
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).
JButton jEightButton=new JButton();
jEightButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jframe.getContentPane().setBackground(Color.blue);
}
public GUI() {
JButton btn1 = new JButton("Click me!");
add(btn1);
btn1.addActionListener(new ActionListener()) {
@Override
public void actionPerformed(ActionEvent e) {
//action for the button
}
}
}
-
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.– Community BotJan 25 at 9:48