can some please what im doing wrong with my action listener.. i have no idea how an action listener work a little help will be appreciated. thanks in advance. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class PushCounter{ public static void main(String[] args){ JFrame frame =new JFrame("Calculator"); frame.setVisible(true); frame.setSize(300,300); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE ); // THE BUTTON SETUP JButton button = new JButton("CLICK ON ME"); button.setBorderPainted(true); button.addActionListener(new buttonListener()); //sets up label JLabel label= new JLabel("display is on wait:"); // sets up the panel JPanel panel = new JPanel(); panel.setBackground(Color.cyan); //completing my frame panel.add(button); panel.add(label); frame.add(panel); } public class buttonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(button.get.source()) panel.setBackground(Color.black); } } }
Hmmm... not sure off the top of my head. What error did it give,or worse, did it not give an error?
i have 3 red xs
first on:button.addActionListener(instanceOfbutton); second on:if(button.get.source()) third on: panel.setBackground(Color.black);
The ones on public class buttonListener implements ActionListener{ are scope issues. You drfined those in the main, not the listener.
sorry i dont get it
I think u r getting the First error because u have declared "button" variable only in Main method , But u r using it in the listener, add "private JButton button;" and "private JPanel panel;" at the top of ur code
secondlt make a constructor and add listener in that method, i think u get problems when u add listener in the main method.......... remove button.addActionListener() line from the main code and Add Public PushCounter() { button.button.addActionListener(this) ; } in ur code, that should do it.
k let me try it
Also add "new PushCounter();" line in ur main code, to call the constructor
wow awsome..
did it work?
yeap
Great
thank you very much
no probs
Join our real-time social learning platform and learn together with your friends!