Results 1 to 2 of 2
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    4

    Default 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.


    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
    My question is:

    Instead of:
    ActionListener myActionListener= new SecondClass();
    myButton.addActionListener(myActionListener);

    Why can't I just use:
    myButton.addActionListener(this);

    ?

    Thank you for your helps.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default 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 11:58 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •