Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Why does a cast need to happen in this code?

$
0
0
Hey,

I had a problem with my code and I found exactly what I needed to fix it, but the problem is I don't udnerstand why it works. I've looked all over but can't find a good explanation, could anyone here help?

public class MyButton extends JButton {

private int id;

// ...

public int returnID(){
return id;
}

}


MyButton myButton = new MyButton();
// ...
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
MyButton button = (MyButton) event.getSource();
button.returnID();
// Do something with x and y
}
});[/code]

in the actionPerformed, why is the the event cast to a button?

public class MyButton extends JButton {

private int id;

// ...

public int returnID(){
return id;
}

}


MyButton myButton = new MyButton();
// ...
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
MyButton button = (MyButton) event.getSource();
button.returnID();
// Do something with x and y
}
});


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>