Reputation: 11
I'm trying to share a JFrame
between instances of a Lotus Notes Java agent. I would like to re-use my window instead of recreating it each time my agent executes.
My class, RaiseJira
, extends JFrame
, which extends Frame. When I run the following code, I get a ClassCastException
.
Frame[] fs = Frame.getFrames();
for (int i = 0; i < fs.length; i++) {
if (fs[i].getName().equals("RaiseJira")) {
RaiseJira f = (RaiseJira) fs[i];
}
}
If I cast it to a JFrame
, it works fine and I have access to the JFrame
methods. I'm trying to pass data to it using RaiseJira
methods, so it needs to be of the correct type.
Am I missing something with downcasting? Also, am I missing an easier way of passing data to a common JFrame
from separate agents?
Upvotes: 0
Views: 173
Reputation: 17971
When I run the following code, I get a ClassCastException.
In your if
condition:
if (fs[i].getName().equals("RaiseJira"))
Checking the frame's name doesn't make sense in this context because you can have a JFrame
which is not instance of RaiseJira
class but its name is set to "RaiseJira". For instance:
JFrame trollFrame = new JFrame("He he");
trollFrame.setName("RaiseJira");
Then you'll have a ClassCastException
here:
if (fs[i].getName().equals("RaiseJira")) { // This is true
RaiseJira f = (RaiseJira) fs[i]; // ClassCastException because is a JFrame not RaiseJira instance
}
If you want to be sure if a given frame is actually an instance of RaiseJira
class you should use instanceof
operator (I'd also use enhanced for loop but it's me):
for (Frame frame : Frame.getFrames()) {
if (frame instanceof RaiseJira) {
RaiseJira raiseJira = (RaiseJira) frame;
}
}
I strongly suggest you read this topic: The Use of Multiple JFrames, Good/Bad Practice?
Upvotes: 1