开发者

Faulty JButton event listener

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?


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);
    }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜