Dynamically changing number of columns in a JTable - java

I have a JTable and a TableModel that extends AbstractTableModel. I would like to dynamically set the number of columns in the table. I implemented this by adding an attribute to my TableModel named, column_count, and having getColumnCount return the column_count. I also added a method, setColumnCount, that sets column_count and calls fireTableStructureChanged. Unfortunately, when I ran the program, I kept getting ArrayIndexOutOfBounds exceptions. Can anyone tell me what I did wrong, or suggest a better solution?
Here's a stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintGrid(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.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.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)

I think the exception is caused as follows:
You set internal column_count to +1
You cause events to be fired which will cause the table to be updated visually
When the JTable update code accesses the last column the internal Vector in the column model throws the exception.
The reason is probably because the underlying code of DefaultTableColumnModel does not know about the new column, and its Vector has not properly been altered.
To fix this you should probably write your own custom TableColumnModel which can deal with changing dimensions properly.

Where does your getValueAt() method takes data? If it is an ArrayList and you increase column size, than the table will try to fetch that column from the list and throw an exception.
If that is not the problem, either use DefaultTableModel and DefaultTableModel.addColumn() to add columns, or make sure that you make any changes to the table model from the Event Dispatch Thread.

Calling to method setModel(tm) of JTable with tm the changed TableModel
solved a similar error in my case.

Related

"null" in Java drawImage()

I mean the drawImage() method is not working for me. People say to do like
g.drawImage(image, 0, 0, null);
But eclipse actually deny it. It said:
The method drawImage(Image, int, int, ImageObserver) in the type Graphics is not applicable for the arguments (Image, int, int, null)
This actually make my really confused, I have read some answers from others, which they always say to put it to null.
I tried to run it, and it give me this:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
The method drawImage(Image, int, int, ImageObserver) in the type Graphics is not applicable for the arguments (Image, int, int, null)
at me.danielshe.graphics.DrawComponent.paintComponent(DrawComponent.java:29)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.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$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(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)
Can anyone help me, or is that a way to put something instead of "null"? I have tried to put "this" and even implementing the ImageObserver. But neither of them works.
Thanks.
You need an object that implements the ImageObserver interface. Normally
this is would be the component associated with the graphics object.
Using null as an ImageObserver it's not wrong. Is equivalent to this:
ImageObserver obs = null;
drawImage( img, x , y , obs );
Null can be used anywhere you would use a reference (Object). The problem arises when you need to use this reference/object, you will get a runtime exception as the object would be empty. In your example as long as your image is fully loaded when you call drawImage(), you won't have a problem, therefore you should only use null on drawImage() if you know for sure that your image is fully loaded. Now I haven't had this problem with the compiler, but I don't use eclipse, just a text editor and the command line. Try compiling with the command line or use the two lines of code from above on eclipse.
"this" will only work if the class where you are using drawImage implements the ImageObserver interface or if it extends a class that implements it, like a Jcomponent for example.

Java: "unknown source" error with unfolding maps package

BACKGROUND
I'm trying to build a map of earthquake events with data parsed from an RSS feed using the "Unfolding maps" library in Java (this is part of the Coursera course on OOP with Java). In theory, the data from the feed gets parsed into properties of the earthquake (location, magnitude, ...) which then form the basis for these marker objects that get displayed on a map. The libraries that are used are "Processing" and the "Unfolding Maps" library.
PROBLEM
Theres an "Unknown Source" error in the part, where I want to set the color property of the earthquake marker, depending on the magnitude of the event (ie. magnitude > 3 is "yellow").
Here's the error message:
Exception in thread "Animation Thread" java.lang.NullPointerException
at de.fhpotsdam.unfolding.marker.AbstractMarker.getProperty(Unknown Source)
at module3.EarthquakeCityMap.setup(EarthquakeCityMap.java:101)
at processing.core.PApplet.handleDraw(PApplet.java:2365)
at processing.opengl.PJOGL$PGLListener.display(PJOGL.java:873)
at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:690)
at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:672)
at javax.media.opengl.awt.GLCanvas$10.run(GLCanvas.java:1383)
at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1277)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1131)
at javax.media.opengl.awt.GLCanvas$11.run(GLCanvas.java:1394)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(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)
And here is the code
for (Marker marker:markers) {
if ((int) (marker.getProperty("magnitude")) > 3) {
System.out.println("trying to set the colour to yellow");
//marker.setColor(yellow);
}
}
The line with "setColor(yellow)" is commented out, as it seems that this is a problem of its own (may or may not have to do with it).
Anybody have an idea where this may come from and what I could read up on to better understand the problem? I'm pretty new to programming so any advice on how to learn the process of tracing errors / finding out the cause of a problem would be fantastic.

MATLAB reports "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"

I wonder about a Java error that is repeatedly occurs in MATLAB. It typically occurs when MATLAB is doing some heavy stuff with Java. This can for example be holding Ctrl + Z or Ctrl + Y.
I did by mistake erase the error message before I copied it, but I think that I can pass the core of the problem anyway.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Why did this error occur? I have found some information about this from MATLAB r2007, this due to that Java Swing is thread unsafe and MATLAB lacked support to ensure thread safety. However, that is supposed to have been fixed in MATLAB r2008b. So why do I get it now?
Here is the full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.netbeans.editor.BaseDocument.notifyUnmodify(BaseDocument.java:1465)
at org.netbeans.editor.BaseDocument.notifyModifyCheckEnd(BaseDocument.java:816)
at org.netbeans.editor.BaseDocumentEvent.redo(BaseDocumentEvent.java:336)
at javax.swing.undo.UndoManager.redoTo(Unknown Source)
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
at org.netbeans.editor.ActionFactory$RedoAction.actionPerformed(ActionFactory.java:767)
at org.netbeans.editor.BaseAction.actionPerformed(BaseAction.java:259)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at com.mathworks.widgets.SyntaxTextPaneBase.processKeyEvent(SyntaxTextPaneBase.java:1187)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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)
Well, based on your stack trace, probably there isn’t any definitive answer to your question, as you have already seen in MATLAB's forum, but given this line, I think there's a possible explanation:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at javax.swing.undo.UndoManager.redoTo(Unknown Source) // <-- here!
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
...
UndoManager class keeps an internal collection of UndoableEdit objects. This collection is actually inherithed from its superclass: CompoundEdit.
The internal implementation of UndoManager#redo() and UndoManager#redoTo(UndoableEdit edit) looks like this:
public class UndoManager extends CompoundEdit implements UndoableEditListener {
...
public synchronized void redo() throws CannotRedoException {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
if (edit == null) {
throw new CannotRedoException();
}
redoTo(edit);
} else {
super.redo();
}
}
...
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
boolean done = false;
while (!done) {
UndoableEdit next = edits.elementAt(indexOfNextAdd++);
next.redo(); // NPE here?
done = next == edit;
}
}
...
}
Considering this implementation and given that Swing's Event Dispatch Thread (EDT) is prone to cause troubles, I think it's probably a threading issue between MATLAB threads and the EDT. Specifically speaking this MATLAB-invoked method could be the source of the problem:
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
Since you say MATLAB needs to do heavy work, it's not unreasonable to think this method is trying to redo some edit that might well not be available anymore or might not be available yet, due to synchronization problems with the EDT.
You can find the ~/.matlab folder which contains MATLAB settings, etc. Use ls -la to show all hidden files and folders.
Open a terminal and execute sudo chmod 757 -R ~/.matlab.
Similarly there is a folder, MATLAB, in Documents.
Execute sudo chmod 757 -R ~/Documents/MATLAB.
Now restart MATLAB without root privileges. It worked for me on Ubuntu 14.04 (Trusty Tahr) and MATLAB 2015a.

Java applet throws error in remove object from Iterator array

Welcome, i am programming a simple RPG game in java applet. It is getting more and more complicated and many errors are thrown to my face. Today i have problem with .remove(); method.
Exception in thread "AWT-EventQueue-1" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.remove(Unknown Source)
at rpg.main.paint(main.java:365)
at rpg.main.update(main.java:331)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(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)
That's how error log looks like. Code of program:
main.java
As we can see error appears in paint methid in the end of program, but i dont know maybe it is caused by wrong initiation in the beginning of program?
public void initLocatables()
public void initLocatables2()
And i have to admit that they are called in main while loop in run method.
These is place where error apears, and below in comment i have included previous method that has also thrown error, both in remove();
for (Iterator i = locatablesArray.listIterator(); i.hasNext();) {
Locatable l = (Locatable) i.next();
l.draw(g);
i.remove();
}
/*while(itrLocatables.hasNext())
{
Locatable l = itrLocatables.next();
l.draw(g);
l.remove();
}*/
Thank you for any reply.
Maybe when you call repaint() in run(), paint() is queued to EDT and called as soon as possible; while iterating locatablesArray a call to initLocatables2() in run() is done another time and the re-init of locatablesArray in the same time the code of paint() will produce the error.
My advice is to separate init operation in a specific init section and call it once, the run your main loop.
Just another thing: why are you init a Iterator (class field itrLocatables) in initLocatables2()? Use iterator when needed if possible.
Hope to be clear, English is not my native language.
You cannot remove objects from a list/map while you are iterating them. That's the cause of the ConcurrentModificationException
i.remove();
If you will draw all the Locatable elements, and then clear the collection, maybe you should draw them all first, and then clear the collection, instead of removing them on the fly.
for (Iterator i = locatablesArray.listIterator(); i.hasNext();) {
Locatable l = (Locatable) i.next();
l.draw(g);
}
// Clear everything from the list
locatablesArray.clear();
java.util.ConcurrentModificationException
Another approach is to use a for loop through the locatablesArray starting at the end vs the beginning. That way any elements that are removed won't change the location of elements of the array that are yet to be scanned.

Are multiple calls to java SaxParser.parse(String, Handler) Legal?

I have a java SAX parser which I would like to call multiple times on the same Handler with different XML files. I am using this in conjunction with iText to create a multi-page PDF document where some pages have one XML tag map and other pages have another. For example,
parser.parse("xmlFile1", handler);
parser.parse("xmlFile2", handler);
When I try to do this, I get a java.lang.RuntimeException thrown with the following stacktrace:
DocumentException: java.lang.RuntimeException: The document is not open.
at com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:695)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.carriageReturn(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.add(Unknown Source)
at com.lowagie.text.Document.add(Unknown Source)
at myClass.myCode(Unknown Source)
org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:223)
at myClass.myCode(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
Does the SaxParser.parse method implicitly call document.close()? Or is there some other problem in my code which I need to isolate and correct?
Reusing the same parser is legal (as long as it is not used concurrently)
The parser triggers an "endDocument". This seems to close the iText document here.. But this is not done by the parser - this is code from your handler.

Categories