views:

71

answers:

2

I have created in my Java Swing application a main window with a JButton. I have added to this button an event listener class (implementing the ActionListener interface) which, every time the button is clicked, launches a "pop-up" window. The method works fine when the button is clicked, except when the button is clicked for the first time, as it does nothing. Does anyone know the reason behind such behaviour?

+1  A: 

Posting the code of the event handler as well as how you are attaching it to the button might help. You might want to take a quick look at this Sun Tutorial

npinti
+2  A: 

A simpler way is perhaps to provide an AbstractAction. You could try the approach outlined below. (It shows a popup-window when the button is clicked.)

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(new JButton(new AbstractAction("Button Text") {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hello World");
            }
        }));
        jf.setSize(200, 200);
        jf.setVisible(true);
    }
}
aioobe