Say you have an instance of a jpanel. Is it possible to override e.g. its paintComponent method without actually subclassing it?
Overriding methods
Page 1 of 16 Replies - 145 Views - Last Post: 04 June 2012 - 09:53 AM
Replies To: Overriding methods
#2
Re: Overriding methods
Posted 04 June 2012 - 07:55 AM
oha055, on 04 June 2012 - 09:16 AM, said:
Say you have an instance of a jpanel. Is it possible to override e.g. its paintComponent method without actually subclassing it?
No. Methods are not first-class objects in Java, so this kind of thing isn't possible.
If you have a final class, for example a String, and you want to "override" one of its methods, the closest you can do would be to wrap it in some class of your own and write a bunch of passthrough methods for everything you didn't want to override, and write a replacement method for the one you did want to replace. This is pretty limited, though. You wouldn't have access to anything but the public fields and methods, and you wouldn't be in the inheritance hierarchy. This would not be an instanceof String.
EDIT: But pbl's answer below is probably what you're looking for.
This post has been edited by jon.kiparsky: 04 June 2012 - 09:57 AM
#3
Re: Overriding methods
Posted 04 June 2012 - 09:27 AM
public class MyFrame extends JFrame {
MyFrame() {
super("Foo");
JPanel p = new JPanel() {
public void paintComponent(Graphics g) {
g.drawString("Hello Jon", 30, 30);
}
};
add(p);
}
public static void main(String[] args) {
JFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myFrame.setSize(300, 200);
myFrame.setVisible(true);
}
}
#4
Re: Overriding methods
Posted 04 June 2012 - 09:35 AM
Actually, you're subclassing there - there's a bit of syntactic sugar, but you're creating an anonymous class which subclasses JPanel.
Notice that you can't do this:
Close, but no cigar.
Notice that you can't do this:
String s = new String() {
public int charAt(int index)
{
return 7;
}
};
Close, but no cigar.
#5
Re: Overriding methods
Posted 04 June 2012 - 09:38 AM
You are right Jon, but I guess the OP question was not correctly formulated... and I guess that this is exactly what he wanted
#6
Re: Overriding methods
Posted 04 June 2012 - 09:42 AM
I think you're right - your answer is definitely what he was looking for.
But the answer to the question he actually asked... is no.
But the answer to the question he actually asked... is no.
#7
Re: Overriding methods
Posted 04 June 2012 - 09:53 AM
Thanks for the replies! Very informative 
EDIT: Yes, this was something along the lines of what I was thinking about:
EDIT: Yes, this was something along the lines of what I was thinking about:
JPanel p = new JPanel() {
public void paintComponent(Graphics g) {
g.drawString("Hello Jon", 30, 30);
}
};
This post has been edited by oha055: 04 June 2012 - 09:59 AM
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote



|