How to add action listener that listens to multiple buttons

后端 未结 11 1108
温柔的废话
温柔的废话 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:39

    There is no this pointer in a static method. (I don't believe this code will even compile.)

    You shouldn't be doing these things in a static method like main(); set things up in a constructor. I didn't compile or run this to see if it actually works, but give it a try.

    public class Calc extends JFrame implements ActionListener {
    
        private Button button1;
    
        public Calc()
        {
            super();
            this.setSize(100, 100);
            this.setVisible(true);
    
            this.button1 = new JButton("1");
            this.button1.addActionListener(this);
            this.add(button1);
        }
    
    
        public static void main(String[] args) {
    
            Calc calc = new Calc();
            calc.setVisible(true);
        }
    
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == button1)
        }  
    
    }
    

提交回复
热议问题