Results 1 to 2 of 2
Thread: Why can't I use this?
- 12-17-2011, 10:39 AM #1
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
Why can't I use this?
Hi;
I have a small code that creates a frame, adds a button on it, and when the button is clicked, the text on button is changed.
My question is:Java Code:package myPackage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class SecondClass implements ActionListener { static JFrame myFrame; static JButton myButton; public static void main(String[] args) { // TODO Auto-generated method stub myFrame = new JFrame(); myFrame.setVisible(true); myFrame.setSize(250, 250); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myButton = new JButton(); myButton.setText("This is a button!"); myFrame.getContentPane().add(myButton); ActionListener myActionListener= new SecondClass(); myButton.addActionListener(myActionListener); }//end main method @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub myButton.setText("I have been clicked!"); }//end actionPerformed method }//end Class
Instead of:
ActionListener myActionListener= new SecondClass();
myButton.addActionListener(myActionListener);
Why can't I just use:
myButton.addActionListener(this);
?
Thank you for your helps.
- 12-17-2011, 10:56 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,546
- Rep Power
- 11
Re: Why can't I use this?
Did you try that? The compiler will alert you any problems. If you can't understand what the compiler is grumbling about, post the entire message that it gives.
-----
You should not be putting so much into the static main() method. Apart from anything else the static context won't make easy (as you've found!). The frame and button should not be static, and main() should create an instance of SecondClass to access them and their actionPaerformed() method.
It would also be a good thing to follow the overall structure of Swing programs used, eg, in Oracle's Tutorial. I would highly reccommend that you read the examples and commentary the Tutorial contains.Last edited by pbrockway2; 12-17-2011 at 10:58 AM.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks