Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

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

OpenStudy (e.mccormick):

Hmmm... not sure off the top of my head. What error did it give,or worse, did it not give an error?

OpenStudy (anonymous):

i have 3 red xs

OpenStudy (anonymous):

first on:button.addActionListener(instanceOfbutton); second on:if(button.get.source()) third on: panel.setBackground(Color.black);

OpenStudy (anonymous):

OpenStudy (e.mccormick):

The ones on public class buttonListener implements ActionListener{ are scope issues. You drfined those in the main, not the listener.

OpenStudy (anonymous):

sorry i dont get it

OpenStudy (cybershadow):

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

OpenStudy (cybershadow):

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.

OpenStudy (anonymous):

k let me try it

OpenStudy (cybershadow):

Also add "new PushCounter();" line in ur main code, to call the constructor

OpenStudy (anonymous):

wow awsome..

OpenStudy (cybershadow):

did it work?

OpenStudy (anonymous):

yeap

OpenStudy (cybershadow):

Great

OpenStudy (anonymous):

thank you very much

OpenStudy (cybershadow):

no probs

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!