Link to home
Start Free TrialLog in
Avatar of meow00
meow00

asked on

e.getSource()


 Hi Experts,

    What did I do wrong in the following line 01 ? and how do I fix it ?
 where I have :
    b1 = new JButton("1");  b1.addActionListener(this); Pane2.add(b1) ;
    b2 = new JButton("2");  b2.addActionListener(this); Pane2.add(b2) ;
------------------------------------------------------------------
  public void actionPerformed(ActionEvent e) {
        n++ ;    
            switch((int)e.getSource()){   //line 01   inconvertible types, found : java.Lang.Object, require : int
            case '1' : myString += '1'; break ;
            case '2' : myString += '2'; break ;
        }
       
----------------------------------------------------------------------
 please help !
ASKER CERTIFIED SOLUTION
Avatar of lhankins
lhankins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of meow00
meow00

ASKER

so .... does this mean : I must use

 if(e.getSource() == b1) {} ... I can't use switch ???
 that seems to be complicated to use a lot of if & else .... is there a better way to use switch here ?

 Thanks !
 
it returns the object , which is a component.
instead use
b1.setName("button1");
b2.setName("button2");
if(e.getSource() instanceof JButton)   {
if(((JButton)e.getSource()).getName() == "button1")
 dosomething
Where is the full code ? and what's the main problem ?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if(((JButton)e.getSource()).getText() == "1")
myString +=1;
if(((JButton)e.getSource()).getText() == "2")
myString +=2;
public void actionPerformed(ActionEvent e) {
        n++ ;    
            switch((int)e.getSource().getText().toString().charAt(0)){  
            case '1' : myString += '1'; break ;
            case '2' : myString += '2'; break ;
        }
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or you may try like this

 public void actionPerformed(ActionEvent e) {
        n++ ;    
            switch(e.getSource().getName().toString().charAt(0)){  
            case '1' : myString += '1'; break ;
            case '2' : myString += '2'; break ;
        }
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial