How to add action listener that listens to multiple buttons

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

    You are declaring button1 in main method so you can not access it in actionPerform. You should make it global in class.

     JButton button1;
     public static void main(String[] args) {
    
        JFrame calcFrame = new JFrame();
    
        calcFrame.setSize(100, 100);
        calcFrame.setVisible(true);
    
        button1 = new JButton("1");
        button1.addActionListener(this);
    
        calcFrame.add(button1);
    }
    
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button1)
    }
    

提交回复
热议问题