[SOLVED!]java.lang.ClassCastException error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[SOLVED!]java.lang.ClassCastException error

hey guys me again I'm confused abt something. I keep getting this error: java.lang.ClassCastException: class javax.swing.JTextArea cannot be cast to class project.frame (javax.swing.JTextArea is in module java.desktop of loader 'bootstrap'; project.frame is in unnamed module of loader 'app'). at project.frame.load(frame.java:76) at project.frame$1.run(frame.java:60) first it was JLayeredPane then JFrame and now JTextArea. I'm really confused as why this is. if i can fix this, then ill be able to save my data...after like so many hours xd. i've tried searching it up but i don't really get it. Like i have to change something abt line 75, but idk to what here is my code, not the main class. https://code.sololearn.com/c4U660OrbtGN maybe Serializable doesn't work with swing...if that's the case...fml btw sorry, im here again xd

28th Jun 2020, 8:54 PM
Jordi
Jordi - avatar
3 Answers
+ 2
you saved JTextArea object as data type so try something like load() .. //frame frame = (frame) is.readObject(); // something wrong here NotesText = (JTextArea) is.readObject();
29th Jun 2020, 12:50 AM
zemiak
+ 1
Hello Jordi de Pelseneer You get such an exception when you try to cast an object which is not an instance of the subclass. For example Integer and Double are both subclasses of Number. So you can do this: Number a = Integer.valueOf(7); Number b = Integer.valueOf(5.0); Both can be downcasted but only to it's real type: Integer myInt = (Integer)a; Double myDouble = (Double)b; This will throw an class cast exception: Integer myInt = (Integer)b; because b is from type Double. I guess you are right that the error is in line 75. frame frame = (frame) is.readObject(); // something wrong here I am not sure what you are trying here. But before you cast you should check if the object is an instance of the class. You can do this with instanceof if(is.readObject() !instanceof frame){ //return or throw an exception }else{ //cast is save frame frame = (frame)is.readObject; } Note: Only upcasting is save. Because every subclass is always an instance of it's super class.
28th Jun 2020, 11:19 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
i actually got it to work...omfg.
29th Jun 2020, 9:13 AM
Jordi
Jordi - avatar