java.lang.ClassCastException socket readObject - java

Hi guys I am getting this problem on my console, but only appear sometimes.. not always..
I would like your help if possible, thanks
Error:
Exception in thread "Thread-2" java.lang.ClassCastException: cannot assign instance of java.lang.String to field Element.posElement of type java.awt.Point in instance of Personagem
at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(Unknown Source)
at java.io.ObjectStreamClass.setObjFieldValues(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at LaunchCliente$receberDoServidor.run(LaunchCliente.java:332)
and here is my code, when I am trying to read the object :
Object a = inputStream.readObject();
if(a instanceof Mapa){
Mapa novo = (Mapa) a;
if(launchJogo.getListaObstaculos().size() == 0)
launchJogo.setLista(novo.getListaObstaculos());
launchJogo.setListaPers(novo.getListaPersonagens());
launchJogo.setElements(novo.getElements());
launchJogo.getFrame().pack();
}
else if(a instanceof logout){
if(launchJogo != null)
launchJogo.getFrame().dispose();
novo.close();
}
else if(a instanceof updateList){
Vector<String> novo = ((updateList) a).getUpdateList();
if(novo.size() != 0){
if(!nomeUtilizador.isEnabled()){
modeloDaLista.clear();
arrayDeJogos = new Vector<String>(novo);
for (String x : arrayDeJogos) {
modeloDaLista.addElement(x);
}
janela.validate();
}
}
if(novo.size() == 0){
modeloDaLista.clear();
}
}
else if(a instanceof String){
String b = a.toString();
if(b.equals("COLOR:FALSE")){
JOptionPane.showMessageDialog(c, "Essa cor já está em uso no jogo selecionado!" , "Cor já escolhida!",
JOptionPane.WARNING_MESSAGE);
launchJogo = null;
cores.dispose();
janela.setVisible(true);
}
else if(b.equals("CREATE:BUTTONSTART")){
launchJogo.getOptions().showButton(true);
}
else if(b.equals("ACTIVE:BUTTONSTART")){
if(!launchJogo.getOptions().isButtonEnabled()){
launchJogo.getOptions().setBotaoState(true);
}
}
else if(b.equals("COLOR:TRUE")){
cores.dispose();
out.writeObject(new addToAGame(corDoJogador, nomeJogador, jogoSelecionado));
launchJogo = new LaunchJogo(launchCliente, jogoSelecionado, nomeJogador);
}
else if(b.equals("LAUNCH:GAME")){
if(launchJogo != null)
launchJogo.addPersonagemListener();
}
}
} catch (ClassNotFoundException e) {
System.out.println("Class not found!");
} catch (IOException e) {
this.interrupt();
}
Thanks alot in advance guys, I would appreciate some help

The error message is telling you that the object stream is encountering a runtime error while rebuilding a serialized object. The object state being deserialized has a String for a value of the field Element.posElement ... which ought to be a Point according to the version of the Element class that your application is using.
The problem is with the actual serialized objects that you are attempting to read. I suspect that some time in the past you have changed the type of the Element.posElement field from String to Point (or vice versa), and you are trying to deserialize an object created by the other version of the class to the one you are currently using.
Normally, the object reader would complain about incompatible versions, but I suspect that you have:
- added serialVersionId constants to your classes, and
- failed to update the serialVersionId for Element after making a change that makes the new version incompatible with the old one.
Another possibility (see #TInusTate's comment) is that there are multiple threads writing to a shared ObjectOutputStream instance without synchronizing properly. This can result in the bytes from different objects getting "mixed up".
You could get a similar effect if you did other things like:
Multiple ObjectOutputStream instances wrapping a shared OutputStream.
Multiple threads reading from the same ObjectInputStream.
In some cases, the solution is proper synchronization. In others, the problem is intractable. None of the stream classes are inherently thread-safe, and multiple threads multiplexing data over a single stream is a difficult problem, requiring considerable care.
You are going to need to find where these incompatible serialized objects are coming from and either get rid of them or (somehow) replace them. In the future, you need to be more careful whan making changes to classes that may have been serialized and persisted, etcetera.
(This kind of problem is one of the reasons why ObjectStream serialization can be problematic for persisting state.)

The error is quite obvious.
cannot assign instance of java.lang.String
to field Element.posElement of type java.awt.Point
At the point where the error occurs, you are trying to assign a String where a "awt.Point" is exspected.
The bad thing is that I'm not sure of the problem is in the code you pasted.
Check line 332 of LaunchCliente.java.
You should be able to debug the issue and figure out which line it is.

First few points
You don't have "a instance of Persongem"
You are not capturing ClassCastException. May be capture it with as much information as you can.
The problem is with the Serialized version of your class only. It has definitely been changed at least once for at least one data (data/row in lose terms).
Thread does complicate the stuff. Have a test around it.
Resolution: The thing you can do is identify the data. alienate/correct/log and fail safely in such case.

Related

What causes an InternalError to be thrown by sun.awt.shell.Win32ShellFolder2.initSpecial()?

Some of our Windows users get this stack trace shortly after launching our app:
java.lang.InternalError: Could not bind shell folder to interface
at sun.awt.shell.Win32ShellFolder2.initSpecial(Native Method) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2.access$300(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.ShellFolder.invoke(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2.<init>(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolderManager2.getNetwork(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2.getFileSystemPath(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2.access$400(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2$10.call(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolder2$10.call(Unknown Source) ~[na:1.7.0_25]
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) ~[na:1.7.0_25]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:1.7.0_25]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[na:1.7.0_25]
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source) ~[na:1.7.0_25]
at java.lang.Thread.run(Unknown Source) ~[na:1.7.0_25]
Observations:
Every frame in the stack trace is something in the JDK, not in our code.
This happens only on Windows, but we've had reports of it on both Vista and Windows 7.
This happens with various versions of Java: 1.6.0_19, 1.6.0_21, 1.7.0_11, 1.7.0_25.
The problem happens to only a handful of our users, but is 100% repeatable for those users. Unfortunately, we haven't been able to see anything which those users' systems have in common other than exhibiting this issue, and none of our developers has ever experienced it themselves.
My search of Oracle's bug database turned up no bugs with the same or a similar stack trace.
There seem to be a lot of posts on the net about this particular issue without anyone having any idea what causes it.
I'm not holding out any hope of Oracle fixing whatever the problem is, if it is indeed a JDK bug---but if we knew what triggered the bug, we could at least help our users afflicted by it. Can anyone shed light on what causes this to happen?
Edit: The relevant native function is this one, from ShellFolder2.cpp:
JNIEXPORT void JNICALL Java_sun_awt_shell_Win32ShellFolder2_initSpecial
(JNIEnv* env, jobject folder, jlong desktopIShellFolder, jint folderType)
{
// Get desktop IShellFolder interface
IShellFolder* pDesktop = (IShellFolder*)desktopIShellFolder;
if (pDesktop == NULL) {
JNU_ThrowInternalError(env, "Desktop shell folder missing");
return;
}
// Get special folder relative PIDL
LPITEMIDLIST relPIDL;
HRESULT res = fn_SHGetSpecialFolderLocation(NULL, folderType,
&relPIDL);
if (res != S_OK) {
JNU_ThrowIOException(env, "Could not get shell folder ID list");
return;
}
// Set field ID for relative PIDL
env->CallVoidMethod(folder, MID_relativePIDL, (jlong)relPIDL);
// Get special folder IShellFolder interface
IShellFolder* pFolder;
res = pDesktop->BindToObject(relPIDL, NULL, IID_IShellFolder,
(void**)&pFolder);
if (res != S_OK) {
JNU_ThrowInternalError(env,
"Could not bind shell folder to interface");
return;
}
// Set field ID for pIShellFolder
env->CallVoidMethod(folder, MID_pIShellFolder, (jlong)pFolder);
}
In order to reach the "Could not bind" exception, it looks like pDesktop != NULL and relPIDL is retrieved successfully, but pDesktop->BindToObject() returns something other than S_OK. pDesktop is an IShellFolder*, which is apparently defined in Windows's <shellapi.h>. Aggravatingly, Java throws away the error code returned by IShellFolder::BindToObject.
So, I guess the question reduces to: What can cause IShellFolder::BindToObject to fail?
Edit 2: Since Win32ShellFolderManager2.getNetwork() is what's calling the Win32ShellFolder2 ctor at Win32ShellFolderManager2.java:181, we can see that the last argument to Win32ShellFolder2.initSpecial must be Win32ShellFolder2.NETWORK. So, is something is wrong with the user's Network Neighborhood folder, perhaps?
Well, there are several reports similar to yours (like this one from jEdit, this one from codenameone and this one - in german - which seems like a JFileChooser bug with a stack trace very close to yours in Windows 7 and Java 6). All seem related to JFileChooser and/or File Browsing in one way or another.
So I would approach this in one of two ways:
Either go for the time-consuming / non speculative road and take dumps of the affected installations with tools such as jstack, VisualVM or JConsole until you are able to isolate the root cause of the problem (which may or may not be the JFileChooser). If you choose that path, remember that either remote access to one of the affected installations or help from a technical savvy user is a must.
Or try to take a shortcut, assume that the problem is indeed the JFileChooser (as anecdotal evidence shows) and release a custom version replacing the JFileChooser by FileDialog. If it runs as expected on the affected machines case is closed; else give yourself a tap on the back for trying and take "The Long and Winding Road".
Had same problem and the answer was
java.awt.FileDialog
If you look up VbScript solutions for "Open File Dialog", it seems that there is no COM class doing the job for most of the windows platforms

readObject() is not working and breaks from method

I'd like to read different kinds of objects from file to an ArrayList, all of them are instances of class which extend the class Advertisement. I'm trying with this code:
ArrayList <Advertisement> ads = new ArrayList<Advertisement>();
ObjectInput input2 = new ObjectInputStream(
new BufferedInputStream(new FileInputStream("ads.ser")));
//break from this method at this point
ads = (ArrayList<Advertisement>) input2.readObject();
The problem is at the 3rd line/last line. It doesn't read the objects in variable ads of type ArrayList<Advertisement>, furthermore, it breaks from this method, without any messages.
Edit: Removed the try-catch block, I should have done it earlier, but I still don't know the solution. Stacktrace:
java.io.InvalidClassException: Kiado; local class incompatible: stream classdesc serialVersionUID = -1393576200767336208, local class serialVersionUID = -841663850423605586
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Main.beolvasas(Main.java:30)
at Main.startup(Main.java:57)
at Main.main(Main.java:633)
Now that you have a stack trace, the problem is clear: since the moment you serialized the objects to the file, you have made changes to the class Kiado. So the class you have now is not compatible anymore with the class as it was when serializing the objects to the file.
If you didn't change the number and the names of the fields of the class (and of all its superclasses), you can make it compatible again by just adding the following variable declaration in the class:
private static final long serialVersionUID = -1393576200767336208;
If you added, removed or renamed at least one (non-transient) field, then you might make the new class still compatible with the old one, but with more pain. And we would have to know the nature of the changes to help you.
I would personally avoid using native serialization for long-term storage because, as you just noticed, it's fragile and makes it hard to change the model. I would use a more easily readable and migratable file format: XML or JSON for example.
Do you have any code like:
catch(<WheteverException> e)
{
// nothing here
}
If so do the following:
change the // nothing here to e.printStackTrace();
remove the try/catch and only add it back if the compiler tells you to, and then only add back what exception that the compiler tells you to add (for instance don't do catch(Exception e).

Java NullPointerException when using Evaluation.areaUnderROC from Weka

So I'm trying to evaluate the performance of a classifier on a test instance and when I try to get the area under the ROC, the following error is thrown:
Java.lang.NullPointerException
at weka.classifiers.evaluation.ThresholdCurve.getROCArea(ThresholdCurve.java:268)
at weka.classifiers.Evaluation.areaUnderROC(Evaluation.java:382)
at Classifier_Search.runAda(Classifier_Search.java:74)
at Classifier_Search.acrossTest(Classifier_Search.java:142)
at Classifier_Search.main(Classifier_Search.java:511)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:271)
The code that is throwing the error is this:
Evaluation eval = new Evaluation(train);
String[] options = {"-P 100", "-S 1", "-I " + it, "-W weka.classifiers.trees.DecisionStump"};
AdaBoostM1 cls = new AdaBoostM1();
cls.setOptions(options);
cls.buildClassifier(train);
eval.evaluateModel(cls, test);
int index = test.classIndex();
return eval.areaUnderROC(index);
When I look up the javadoc for Evaluation (javadoc for Evaluation), It says that areaUnderROC needs to be set by an evaluateClassifier method. No such method exists. Other similar methods (such as falsePositive) work just fine. Has anyone encountered this problem? I can't find anything on OldNabble (Weka's help site).
Thanks!
EDIT: to clarify, test and train are both Instances objects that were created with the following code:
private static Instances readFile(File filename) throws IOException
{
CSVLoader loader = new CSVLoader();
loader.setSource(filename);
Instances data = loader.getDataSet();
data.setClassIndex(data.numAttributes() - 1);
return data;
}
They are read from .csv files. Typically if there is something wrong with test or train, the error is thrown here.
Once again, I have the answer to my own question. If someone disagrees with this answer, please let me know. The weka documentation for areaUnderROC, which already has one typo (it references a method, evaluateClassifier, which does not exist), has led me in the wrong direction. I think there is another error in the form of a misleading explanation. areaUnderROC works (without throwing the exception) for two values: 0 and 1. So, rather than taking the class index (the index of the attribute I am using as the class in the Instances object), what it actually wants is which class (of the two classes) to consider as positive. Given the variable names in the documentation, I think it's reasonable to not understand this at first glance. I also think that since its explanation is in parallel with that of methods that do take the class index (rather than 0 or 1), it is also misleading.

InvalidClassException : class invalid for deserialization

I am using SSA parser library in my project. When I invoke main method of one of it's class using command prompt it works fine on my machine.
I execute following command from command prompt :
java -Xmx800M -cp %1 edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -outputFormat "penn,typedDependenciesCollapsed" englishPCFG.ser.gz %2
But when I tried to use the same class in my java program, I am getting Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization exception.
Following line throws error :
LexicalizedParser _parser = new LexicalizedParser("C:\englishPCFG.ser.gz");
This englishPCFG.ser.gz file contains some classes or information which gets loaded when creating object of type LexicalizedParser.
Following is the stacktrace :
Loading parser from serialized file C:\englishPCFG.ser.gz ...
Exception in thread "main" java.lang.RuntimeException: Invalid class in file: C:\englishPCFG.ser.gz
at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:822)
at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromFile(LexicalizedParser.java:603)
at edu.stanford.nlp.parser.lexparser.LexicalizedParser.<init>(LexicalizedParser.java:168)
at edu.stanford.nlp.parser.lexparser.LexicalizedParser.<init>(LexicalizedParser.java:154)
at com.tcs.srl.ssa.SSAInvoker.<init>(SSAInvoker.java:21)
at com.tcs.srl.ssa.SSAInvoker.main(SSAInvoker.java:53)
Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; edu.stanford.nlp.stats.Counter; class invalid for deserialization
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserDataFromSerializedFile(LexicalizedParser.java:814)
... 5 more
Caused by: java.io.InvalidClassException: edu.stanford.nlp.stats.Counter; class invalid for deserialization
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
... 17 more
I am new to Java world so I dont to why this error is coming and what should I do to avoid it.
I googled for this error then I found out that this error comes because of some version mismatch which I think is something similar to dll hell of windows API. Am I correct?
Anyone knows why this kind of error comes? and what should we do to avoid it?
Please enlighten !!!
It could be because the serialVersionUID of the classe has changed, and you are trying to read an object that was written with another version of the class.
You can force the version number by déclaring a serialVersionUID in your serializable class:
private static final long serialVersionUID = 1L;
The java word for dll hell is classpath hell ;-) But that's not your hell anyway.
Object serialization is a process of persisting java objects to files (or streams). The output format is binary. Deserialization (iaw: making java objects from serialized data) requires the same versions of the classes.
So it is possible, that you simply use an older or newer version of that Counter class. This input file should be shipped with a documentation that clearly says, which version of the parser is required. I'd investigate in that direction first.
OT: For the sake of completeness I ran into InvalidClassException ... class invalid for deserialization (and this question) when solving another problem.
(Since edu.stanford.nlp.stats.Counter is not anonymous, the case in this question is certainly not the same case as mine.)
I was sending a serialized class from server to client, the class had two anonymous classes. The jar with these classes was shared among server and client but for server it was compiled in Eclipse JDT, for client in javac. Compilers generated different ordering of names $1, $2 for anonymous classes, hence instance of $1 was sent by server but could not be received as $1 at client side. More info in blogpost (in Czech, though example is obvious).
Try using serialVer to generate the serialID of your old classes that you're trying to de-serialize and add it explicitly (private static final long serialVersionUID = (insert number from serialVer here)L;) in the new versions of the class. If you change anything in a class serialized and you haven't setted the serialID, java thinks the class you've serialized isn't compatible with the new one.
This error suggests that the serialized objects within C:\englishPCFG.ser.gz were serialized with using a older or newer definition of the class which unfortunately is different in such a way that it breaks the terms of compatible serialization from one version to another.
Please see http://download.oracle.com/javase/1.4.2/docs/api/java/io/InvalidClassException.html
Can you check to see when this file was produced and then if possible locate the version of the SSAParser library at the time of it's creation?

Unknown source of ClassCastException (in JTables)

I'm presently refactoring a JTable which displays a multitude of different types of data. The primary reason for this refactoring is that there a few ClassCastExceptions (the author/friend who wrote the code is off on hiatus), and I can't seem to find where these are originating from. Due to the large codebase, I'm at a loss as to where to start. Does anyone have any suggestions? I realize and apologize for the ambiguity of this question!
I've included the stack trace below. Thanks!!
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(Unknown Source)
at javax.swing.JTable.prepareRenderer(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
This error which is occurring in BooleanRenderer is because it is expecting that the value that is from the table's model is of type Boolean and tries to cast to it (akf's answer has the exact line of code where it occurs).
My guess is that initially it was expected that the model would return Boolean values for the given column but at one point it is returning strings instead.
Therefore, I would concentrate on what model is being used for this given table (is it a custom model? Is it the default model where it is adding values to it?) and see where it may be getting a String instead of a Boolean.
Probably the table contains a checkbox (when the column model states that the column contains type Boolean) and the renderer tries to convert the contents into a boolean. But probably the contents are just strings. The solution is to change the data in the table or to create your own renderer.
I think the problem comes from your TableModel (jtable.getModel())
It said somewhere
(..)
public Class<?> getColumnClass(int column)
{
switch(column)
{
(...)
case XX: return Boolean.class;
}
}
but the value in your model in this column is a String
public Object getValueAt(int row,int column)
{
(..)
switch(column)
{
(...)
case XX: return (a String);
}
}
To debug this problem, you may want to consider biting the bullet and putting a breakpoint in the JTable$BooleanRenderer.getTableCellRendererComponent() on the line that makes the cast
setSelected((value != null && ((Boolean)value).booleanValue()));
(from JTable.java 1.288 06/11/15)
and check the class type of value. when you find a String, you can identify the offending column and row from your model. That will at least give you a start on identifying the problem.
Sorry to dig up an old question, but I ran into this issue myself & this post came up in a search and this is what I ran into.
I had JUnits tests fail (and actually throwing runtime exceptions) but I continued to run add/removes on my JTable (in the JUnit test) which put the GUI application in a bad state, and I would see the ClassCastException come up exactly as Chris had described.
So the "fix" for me was to make sure that all unit tests catch their exceptions and return failure instead of proceeding to run more unit tests.
I had the same problem, and the cause was exactly as Avrom specified. In my case, I had the getValueAt implemented as:
#Override
synchronized public Object getValueAt(int row, int col) {
if (row < m_rows.size()) {
return m_rows.get(row).getValueAt(col);
}
else
{
return ""; // THIS IS THE BUG
}
}
The problem here is that, is a row does not exist, a String is returned, for every column. However some of my columns has the class type, Boolean, and hence the exception:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at javax.swing.JTable$BooleanRenderer.getTableCellRendererComponent(JTable.java:5409)
at javax.swing.JTable.prepareRenderer(JTable.java:5736)
The solution was simply to change the return value to:
return null;

Categories

Resources