How to add action listener that listens to multiple buttons

后端 未结 11 1138
温柔的废话
温柔的废话 2020-11-27 04:25

I\'m trying to figure out what i am doing wrong with action listeners. I\'m following multiple tutorials and yet netbeans and eclipse are giving me errors when im trying to

11条回答
  •  心在旅途
    2020-11-27 04:53

    You've been told how to sort your immediate problem, but I think there are more important problems here.

    • stick with conventions. Even for throw-away code. That means initial cases for class names.

    • Don't extend classes you don't need to. JFrame should rarely be extended. In fact, you don't create an instance of your derived class!!!

    • Don't bundle a bunch of things into one class. In particular, you should generally only subtype at most one main class or interface at a time (things like Comparable not included).

    • Always interact, including construct, Swing/AWT GUIs on the AWT Event Dispatch Thread (EDT). It's ugly and verbose, but that's Java for you.

    • Checking a source of an event is a bit of hack. Listeners are small, so you can't even claim the lame performance excuse.

    So:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    
    public class Calc {
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
                runEDT();
            }});
        }
        private static void runEDT() {
            assert java.awt.EventQueue.isDispatchThread();
    
            JFrame frame = new JFrame();
    
            frame.setSize(100, 100);
    
            JButton button1 = new JButton("1");
            button1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    ...
                }
            });
    
            frame.add(button1);
    
            frame.setVisible(true);
        }
    }
    

    If you need to access any of the variables from the enclosing method within the listener, make them final.

提交回复
热议问题