I am writing an application in Java and part of what it needs to do is serialize some objects so they can be imported later. When I wrote the serialization code, it did not work correctly. After much tinkering, I believe I have narrowed it down to only a few attributes and included the minimum possible code to trigger the error in this SSCEE:
import java.io.*;
import java.util.prefs.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
//main class
public class SerializeFail extends JFrame implements Serializable, ActionListener {
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem item = new JMenuItem("Click to Fail");
HashMap<String, Preferences> prefs = new HashMap<String, Preferences>();
public SerializeFail () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
file.add(item);
bar.add(file);
item.addActionListener(this);
prefs.put("root", Preferences.userRoot().node(this.getClass().getName()));
setJMenuBar(bar);
pack();
setVisible(true);
}
//triggers the failure
public void actionPerformed (ActionEvent e) {
TestObject gr = new TestObject();
try {
FileOutputStream fileOutput = new FileOutputStream("testing.gradecalc");
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(gr);
fileOutput.close();
System.out.println("serialized");
} catch (FileNotFoundException fileNotFound) {
System.out.println("The file was not found");
fileNotFound.printStackTrace();
} catch (IOException io) {
System.out.println("There was some type of io exception");
System.out.println("Stack Trace");
io.printStackTrace();
System.out.println("Message Trace");
io.getMessage();
System.out.println("Cause Trace");
io.getCause();
}
}
public static void main(String[] args) {
new SerializeFail();
}
class TestObject implements Serializable {
int attribute;
public TestObject () {
attribute = 47;
}
}
}
The error I get's stack trace is:
There was some type of io exception
Stack Trace
java.io.NotSerializableException: com.apple.laf.AquaMenuBarBorder
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:439)
at javax.swing.JComponent.writeObject(JComponent.java:5525)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1375)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1171)
at java.io.ObjectOutputStream.access$300(ObjectOutputStream.java:162)
at java.io.ObjectOutputStream$PutFieldImpl.writeFields(ObjectOutputStream.java:1700)
at java.io.ObjectOutputStream.writeFields(ObjectOutputStream.java:479)
at java.awt.Container.writeObject(Container.java:3681)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1375)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1171)
at java.io.ObjectOutputStream.access$300(ObjectOutputStream.java:162)
at java.io.ObjectOutputStream$PutFieldImpl.writeFields(ObjectOutputStream.java:1700)
at java.io.ObjectOutputStream.writeFields(ObjectOutputStream.java:479)
at java.awt.Container.writeObject(Container.java:3681)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at java.awt.AWTEventMulticaster.save(AWTEventMulticaster.java:946)
at java.awt.Component.writeObject(Component.java:8645)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Message Trace
Cause Trace
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at SerializeFail.actionPerformed(SerializeFail.java:34)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at com.apple.laf.AquaMenuItemUI.doClick(AquaMenuItemUI.java:157)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
On an interesting note, if the graphics related objects are eliminated such that the SSCEE is:
import java.io.*;
import java.util.prefs.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
//main class
public class SerializeFail implements Serializable {
HashMap<String, Preferences> prefs = new HashMap<String, Preferences>();
public SerializeFail () {
prefs.put("root", Preferences.userRoot().node(this.getClass().getName()));
TestObject gr = new TestObject();
try {
FileOutputStream fileOutput = new FileOutputStream("testing.gradecalc");
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(gr);
fileOutput.close();
System.out.println("serialized");
} catch (FileNotFoundException fileNotFound) {
System.out.println("The file was not found");
fileNotFound.printStackTrace();
} catch (IOException io) {
System.out.println("There was some type of io exception");
System.out.println("Stack Trace");
io.printStackTrace();
System.out.println("Message Trace");
io.getMessage();
System.out.println("Cause Trace");
io.getCause();
}
}
public static void main(String[] args) {
new SerializeFail();
}
class TestObject implements Serializable {
int attribute;
public TestObject () {
attribute = 47;
}
}
}
then the output (containing the stack trace of the exception) is:
There was some type of io exception
Stack Tracejava.io.NotSerializableException: java.util.prefs.MacOSXPreferences
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at java.util.HashMap.writeObject(HashMap.java:1100)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1541)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1506)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1429)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1175)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at SerializeFail.<init>(SerializeFail.java:16)
at SerializeFail.main(SerializeFail.java:35)
Message Trace
Cause Trace
I have looked around and researched serialization, but to no avail. Could someone please make it so the instance of TestObject serializes without fail with the graphics related components (first SSCEE) included because that is what the master application has (or at least point me in the right direction)?
Thank you. If there is anything else I can provide that would be of assistance, please just ask.
All of your non-static fields have to be either transient or transitively Serializable for the default serializer to work. In your case, the Apple look-and-feel and MacOSXPreferences, which are referenced by the fields you declare directly, aren't serializable.
Oddly enough, even though the Swing components all implement Serializable, the actual runtime implementations don't, and making Swing stuff Serializable is widely regarded to have been a mistake. Instead, you need to encapsulate the state (model) separately from the UI (view/controller). Serialize just the model object and have your client code rebuild the UI and then populate it from the saved model.
Similarly, Preferences is not Serializable, and so the runtime can't use default serialization for it. How you handle serializing the preferences depends on what you're trying to do; it's not clear from your example.
Related
I am trying to take data from a GUI and also from arraylists in my model class and then want to put them into another arraylist. Everytime the code runs, it works fine but then when I close the application and the serializer code runs the IOException gets thrown.
The only thing I access from the model class is an arraylist but I am accessing this array list in other classes and I don't have a problem.
Orginally I had the arraylist that I am adding to in the model class, I assumed that was what was throwing the exception so I moved it to another class, however the exception is still being thrown.
I have tried the rest of the event handlers on the form but this is the only one that causes the exception.
Here is the code that is causing the exception to occur:
private void btnRequestAppointmentActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<IAccountStrategy> observers;
observers = model.getObservers();
IAccountStrategy xx;
xx = observers.get(accountIndex);
ArrayList<Appointments> appointment;
appointment = xx.getAppointments();
Appointments app = new Appointments();
setAppointmentDates(appointment, app);
setAppointmentPatient(appointment, app);
xx.getAppointments().add(app);
JOptionPane.showMessageDialog(null, "Appointment Requested. A Secretary will check the request shortly");
}
And the classes that it is calling:
public void setAppointmentDates(ArrayList<Appointments> appointment, Appointments app){
String doctorsName = null;
String sDate;
Date appointmentDate = null;
Date formattedDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try{
doctorsName = cboDoctor.getSelectedItem().toString();
sDate = cboDate.getSelectedItem().toString();
appointmentDate = sdf.parse(sDate);
formattedDate = sdf.parse(sdf.format(appointmentDate));
}
catch(ParseException ex){
System.out.println("ParseException has been caught");
}
app.setAppointmentDate(appointmentDate);
app.setPreferredDoctor(doctorsName);
}
public void setAppointmentPatient(ArrayList<Appointments> appointment, Appointments app){
ArrayList<IAccountStrategy> observers;
observers = model.getObservers();
IAccountStrategy xx;
xx = observers.get(accountIndex);
app.setPatientID(xx.getAccountID());
app.setPatientName(xx.getFirstname() +" "+ xx.getLastname());
app.setPatientAge(xx.getAge());
app.setPatientSex(xx.getSex());
}
This is the code for my serialization, it works on all my other classes:
private void formWindowClosing(java.awt.event.WindowEvent evt) {
String filename = "accounts.txt";
try{
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(model);
out.close();
file.close();
}
catch(IOException ex){
System.out.println("IOException has been caught");
}
}
Here is the stack trace:
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.ArrayList.writeObject(ArrayList.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at java.util.ArrayList.writeObject(ArrayList.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294)
at patientmanagementsystemv2.gui.PatientHomePage.access$000(PatientHomePage.java:28)
at patientmanagementsystemv2.gui.PatientHomePage$1.windowClosing(PatientHomePage.java:133)
at java.awt.Window.processWindowEvent(Window.java:2054)
at javax.swing.JFrame.processWindowEvent(JFrame.java:305)
at java.awt.Window.processEvent(Window.java:2013)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I'm trying to get this program completed for tonight but I've been trying to fix this for hours. Any help is apprieciated.
Stacktrace
Like #Stultuske mention in the comments, you can find the reason inside the stacktrace
Finding Strategy
Lookup the first entry with the naming of your package. In your case look for patientmanagementsystemv2.gui
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
...
at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294)
at patientmanagementsystemv2.gui.PatientHomePage.access$000(PatientHomePage.java:28)
at patientmanagementsystemv2.gui.PatientHomePage$1.windowClosing(PatientHomePage.java:133)
...
At the top of your stacktrace you can see that you have a NotSerializableException at patientmanagementsystemv2.gui.PatientHomePage.formWindowClosing(PatientHomePage.java:294.
The Problem
java.io.NotSerializableException: patientmanagementsystemv2.items.Appointments
The reference type Appointments seems not to implement Serializable and the error raises because you try to serialize in the method formWindowClosing with out.writeObject(model) an instance of Appointments.
Modify Appointments
If you own the class just write
public class Appointments implements Serializable {
// ...
}
But you expected an IOException
With catch(IOException ex) you catch an IOException and all subclasses of it including NotSerializableException.
I'm testing out the SwingX AutoCompleteDecorator, the code I'm using is this:
import javax.swing.text.JTextComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JList;
import org.jdesktop.swingx.autocomplete.*;
public class Test extends JFrame
{
public Test()
{
this.setTitle("Testing");
JPanel pan = new JPanel();
JTextComponent test = new JTextField();
((JTextField)test).setColumns(20);
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
AutoCompleteDecorator.decorate(dataList, test);
pan.add(test);
this.setContentPane(pan);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setBounds(280,150,500,200);
}
public static void main(String[] args)
{
Test t = new Test();
}
}
I wind up getting a massive runtime error message that I don't really want to post the stack trace for about an Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.jdesktop.swingx.autocomplete.ListAdaptor.valueChanged(ListAdaptor.java:77)
at javax.swing.JList.fireSelectionValueChanged(JList.java:1798)
at javax.swing.JList$ListSelectionHandler.valueChanged(JList.java:1812)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)
at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:405)
at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:415)
at javax.swing.DefaultListSelectionModel.setSelectionInterval(DefaultListSelectionModel.java:459)
at javax.swing.JList.setSelectedIndex(JList.java:2212)
at javax.swing.JList.setSelectedValue(JList.java:2362)
at org.jdesktop.swingx.autocomplete.ListAdaptor.setSelectedItem(ListAdaptor.java:99)
at org.jdesktop.swingx.autocomplete.AutoCompleteDocument.setSelectedItem(AutoCompleteDocument.java:355)
at org.jdesktop.swingx.autocomplete.AutoCompleteDocument.insertString(AutoCompleteDocument.java:303)
at javax.swing.text.JTextComponent.replaceSelection(JTextComponent.java:1386)
at javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction.actionPerformed(DefaultEditorKit.java:884)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2926)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
at java.awt.Component.processEvent(Component.java:6282)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1895)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:762)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1027)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:899)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:727)
at java.awt.Component.dispatchEventImpl(Component.java:4731)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
What have I missed?
It's a bug: the culprit is a null ObjectToStringConverter in decorating a textComponent with the items of a JList, using the two-parameter method:
public static void decorate(JList list, JTextComponent textComponent) {
decorate(list, textComponent, null);
}
A quick fix is to use the three-parameter method and pass-in the default converter:
JTextComponent test = new JTextField(20);
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
AutoCompleteDecorator.decorate(dataList, test, ObjectToStringConverter.DEFAULT_IMPLEMENTATION);
Filed Issue #1570 - fixed as of revision #4305
Morning Musings (can safely be ignored :-)
The technical reason is improper constructor chaining: inserting the default should be handled by the do-it-all constructor (alternatively it should throw a NPE)
public ListAdaptor(JList list, JTextComponent textComponent) {
this(list, textComponent, ObjectToStringConverter.DEFAULT_IMPLEMENTATION);
}
public ListAdaptor(JList list, JTextComponent textComponent, ObjectToStringConverter stringConverter) {
this.list = list;
this.textComponent = textComponent;
this.stringConverter = stringConverter;
// when a new item is selected set and mark the text
list.addListSelectionListener(this);
}
The underlying reason is a subtle shift in ownership of the converter: its usual owner is the custom document which handles the autoComplete, this document guards itself against a null. With a JList variant, its the ListAdaptor which is not accustomed to that burden ... The shift is not incorrect (in fact, the exact way to go), just introduces an ever so slight inconsistency which is easy to overlook.
AutoCompleteDecorator.decorate(dataList, test, false)
just add false settings
or just like these
boolean strictMatching = false;
AutoCompleteDecorator.decorate(UName,items,strictMatching);
I have written the following code. Basically I want to activate autocomplete (in a RSyntaxTextArea environment) if the entered character is not space. Everything is working smoothly, but the fact that sometimes I will get the AWT-EventQueue-0 error. The program will still run and function but the error message shows up.
I have other elements in my code, but I am quite sure it is from this bit of added code. Any particular reason for this? I have noticed this error happening when I move the mouse to a second screen.
public static CompletionProvider provider = createModelCompletionProvider();
public static AutoCompletion ac = new AutoCompletion(provider);
public static KeyListener ListenerTOntology = new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {
dumpInfo("Typed", e);}
private void dumpInfo(String s, KeyEvent e) {
char temp = e.getKeyChar();
if(temp!=' ' )
ac.doCompletion();}
};
Error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.fife.ui.rtextarea.FoldIndicator.findOpenFoldClosestTo(FoldIndicator.java:162)
at org.fife.ui.rtextarea.FoldIndicator.access$300(FoldIndicator.java:60)
at org.fife.ui.rtextarea.FoldIndicator$Listener.mouseMoved(FoldIndicator.java:671)
at java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:329)
at java.awt.Component.processMouseMotionEvent(Component.java:6550)
at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:3339)
at java.awt.Component.processEvent(Component.java:6274)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4505)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
So, I discovered what caused this. You need to use a CaretListener instead of KeyListener. Since RSyntaxTextArea does not contain a DocumentListner.
I have created a GUI for plotting a reporting:
GUI:
package aatmPackage;
import java.awt.Color;
import java.awt.Shape;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.util.ShapeUtilities;
public class GuiAATM extends javax.swing.JFrame {
...
private void reportButtonActionPerformed(java.awt.event.ActionEvent evt) {
report Report = new report();
setReportLog("Report Generated Successfully\n");
}
}
I created another project and tested it which works fine to generate a report. Now When I am adding that class to my GuiAATM project , (where the user when clicks report button should generate the report) I am getting below error:
log4j:WARN Parsing warning 2 and column 38
log4j:WARN URI was not reported to parser for entity [dtd]
log4j:WARN Parsing warning 2 and column 38
log4j:WARN missing system ID, using log4j.dtd
log4j:ERROR Could not parse url [jar:file:/D:/Glaswegian/Java/DynamicCharts/dynamicreports-3.1.0-project-with-dependencies%20(1)/dynamicreports-3.1.0/dist/dynamicreports-examples-3.1.0-sources.jar!/log4j.xml].
gnu.xml.dom.DomEx: The operation violates XML Namespaces.
More Information: xmlns is reserved
Node Name: #document
at gnu.xml.dom.DomDocument.createAttributeNS(DomDocument.java:589)
at gnu.xml.dom.DomDocument.createAttribute(DomDocument.java:561)
at gnu.xml.dom.DomDocument.defaultAttributes(DomDocument.java:456)
at gnu.xml.dom.DomDocument.createElementNS(DomDocument.java:440)
at gnu.xml.pipeline.DomConsumer$Handler.startElement(DomConsumer.java:602)
at gnu.xml.dom.Consumer$Backdoor.startElement(Consumer.java:203)
at gnu.xml.pipeline.EventFilter.startElement(EventFilter.java:570)
at gnu.xml.pipeline.ValidationConsumer.startElement(ValidationConsumer.java:1177)
at gnu.xml.aelfred2.SAXDriver.startElement(SAXDriver.java:836)
at gnu.xml.aelfred2.XmlParser.parseElement(XmlParser.java:1037)
at gnu.xml.aelfred2.XmlParser.parseDocument(XmlParser.java:416)
at gnu.xml.aelfred2.XmlParser.doParse(XmlParser.java:167)
at gnu.xml.aelfred2.SAXDriver.parse(SAXDriver.java:320)
at gnu.xml.aelfred2.XmlReader.parse(XmlReader.java:294)
at gnu.xml.dom.JAXPFactory$JAXPBuilder.parse(JAXPFactory.java:186)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177)
at org.apache.log4j.xml.DOMConfigurator$2.parse(DOMConfigurator.java:612)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:711)
at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:618)
at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:470)
at org.apache.log4j.LogManager.<clinit>(LogManager.java:122)
at org.apache.log4j.Logger.getLogger(Logger.java:104)
at org.apache.commons.logging.impl.Log4JLogger.getLogger(Log4JLogger.java:289)
at org.apache.commons.logging.impl.Log4JLogger.<init>(Log4JLogger.java:109)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.apache.commons.logging.impl.LogFactoryImpl.createLogFromClass(LogFactoryImpl.java:1116)
at org.apache.commons.logging.impl.LogFactoryImpl.discoverLogImplementation(LogFactoryImpl.java:914)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:604)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:336)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:310)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685)
at net.sf.dynamicreports.report.defaults.Defaults.<clinit>(Defaults.java:42)
at net.sf.dynamicreports.design.transformation.TemplateTransform.getPageHeight(TemplateTransform.java:663)
at net.sf.dynamicreports.design.transformation.PageTransform.transform(PageTransform.java:44)
at net.sf.dynamicreports.design.base.DRDesignReport.transform(DRDesignReport.java:132)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:107)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:99)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperReportDesign(JasperReportBuilder.java:260)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.getJasperParameters(JasperReportBuilder.java:287)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:298)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.show(JasperReportBuilder.java:327)
at aatmPackage.report.build(report.java:70)
at aatmPackage.report.<init>(report.java:26)
at aatmPackage.GuiAATM.reportButtonActionPerformed(GuiAATM.java:1214)
at aatmPackage.GuiAATM.access$400(GuiAATM.java:34)
at aatmPackage.GuiAATM$5.actionPerformed(GuiAATM.java:968)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "AWT-EventQueue-0" java.lang.AbstractMethodError: gnu.xml.dom.DomElement.getTextContent()Ljava/lang/String;
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.parseExportFonts(SimpleFontExtensionHelper.java:317)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.parseFontFamily(SimpleFontExtensionHelper.java:285)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.parseFontFamilies(SimpleFontExtensionHelper.java:232)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.loadFontFamilies(SimpleFontExtensionHelper.java:193)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.loadFontFamilies(SimpleFontExtensionHelper.java:162)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.getExtensions(FontExtensionsRegistry.java:56)
at net.sf.jasperreports.extensions.DefaultExtensionsRegistry.getExtensions(DefaultExtensionsRegistry.java:110)
at net.sf.jasperreports.engine.util.JRStyledTextParser.<clinit>(JRStyledTextParser.java:83)
at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:121)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:88)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:103)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:61)
at net.sf.jasperreports.engine.fill.JRFiller.createFiller(JRFiller.java:153)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:82)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:653)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:969)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:308)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.show(JasperReportBuilder.java:327)
at aatmPackage.report.build(report.java:70)
at aatmPackage.report.<init>(report.java:26)
at aatmPackage.GuiAATM.reportButtonActionPerformed(GuiAATM.java:1214)
at aatmPackage.GuiAATM.access$400(GuiAATM.java:34)
at aatmPackage.GuiAATM$5.actionPerformed(GuiAATM.java:968)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
BUILD SUCCESSFUL (total time: 6 seconds)
My report.java file is:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package aatmPackage;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Color;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.dynamicreports.report.builder.style.FontBuilder;
public class report {
public report() {
build();
}
private void build() {
StyleBuilder boldStyle = stl.style().bold();
// FontBuilder boldFont = stl.fontArialBold().setFontSize(12);
Color MAROON = new Color(122, 5, 5);
StyleBuilder titleLineOne = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.RIGHT).setFontSize(15).setForegroundColor
(MAROON);
StyleBuilder titleNextLine = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.RIGHT).setFontSize(12).setForegroundColor
(MAROON);
StyleBuilder bodyTitleStyle = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.LEFT).setFontSize(12);
StyleBuilder bodyStyle = stl.style().setFontSize(11);
StyleBuilder signatureStyle = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.RIGHT);
StyleBuilder footerLeft = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.LEFT).setForegroundColor
(MAROON) ;
StyleBuilder footerRight = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.RIGHT).setForegroundColor
(MAROON) ;
//BufferedImage img = new BufferedImage(1200,1200,BufferedImage.TYPE_INT_RGB);
BufferedImage img = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
img = ImageIO.read(new File("D:/Hysteresis.png"));
} catch (IOException e) {
}
BufferedImage logo = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
logo = ImageIO.read(new File("D:/Logo.jpg"));
} catch (IOException e) {
}
try {
report()//create new report design
// .setColumnTitleStyle(boldStyle)
// .setColumnStyle(boldStyle)
.highlightDetailEvenRows()
.columns(//add columns
col.column(null,"Col_1", type.stringType())
.setStyle(bodyStyle),
col.column(null,"Col_2", type.stringType())
.setStyle(bodyStyle)
)
.summary(
cmp.verticalList()
// .add(cmp.filler().setStyle(stl.style().setTopBorder(stl.pen2Point())).setFixedHeight(10))
.add(
cmp.text("\n"),
cmp.filler().setStyle(stl.style().setTopBorder(stl.pen1Point())),
cmp.text("\nHYSTERISIS PLOT\n").setStyle(bodyTitleStyle),
cmp.text(" 1.\n").setStyle(
bodyStyle),
// .add(cmp.image(getClass().getResourceAsStream
// ("D:/Hysteresis.png")).setFixedDimension(300, 300))
cmp.horizontalList()
.add(cmp.image(img).setFixedDimension(350, 250),
//cmp.text("ANALYSIS\n").setStyle(bodyTitleStyle),
cmp.text("Right Lobe Change:160.04%\n").setStyle(bodyStyle),
cmp.text("Left Lobe Change: 35.38%\n").setStyle(bodyStyle),
cmp.text("Hysteresis Change: 81.50%\n").setStyle(bodyStyle)),
//cmp.filler().setStyle(stl.style().setTopBorder(stl.pen1Point())),
cmp.text("REMARKS\n\n\n\n\n\n\n\n").setStyle(bodyTitleStyle),
cmp.text("Doctor Signature").setStyle(signatureStyle))
)
.title(
cmp.horizontalList()
.add(
cmp.image(logo).setFixedDimension(70, 70),
cmp.verticalList()
.add(
cmp.text(" Ltd").setStyle(titleLineOne),
cmp.text(", ").setStyle(titleNextLine),
cmp.text("Mobile +").setStyle(titleNextLine))
)
/* cmp.horizontalList()
.add( cmp.text("Allahabad Bypass Varanasi").setStyle(boldCenteredStyle))
*/
.newRow()
.add(cmp.filler().setStyle(stl.style().setTopBorder(stl.pen2Point())).setFixedHeight(10))
)//shows report title
// .pageFooter(cmp.pageXofY())//shows number of page at page footer
.pageFooter(
Templates.footerComponent,
//cmp.text(" \t\t\t\t\t\t\t\t"
// + " ")
cmp.horizontalList()
.add(cmp.text("Emsol Software Solution").setStyle(footerLeft),
cmp.text("copyright: gauravbvelex#gmail.com").setStyle(footerRight))
)
.setDataSource(createDataSource())//set datasource
.show();//create and show report
} catch (DRException e) {
e.printStackTrace();
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("Col_1", "Col_2");
dataSource.add("Name","Sample");
dataSource.add("Age","26");
dataSource.add("Sex","Female");
dataSource.add("Weight","53 Kg");
dataSource.add("BMI","20");
dataSource.add("Massage Duration (Mins)","4.5");
dataSource.add("RPM","26");
dataSource.add("Doctor Attended","Doctor");
dataSource.add("Date","24-Feb-2013");
return dataSource;
}
}
This report works fine when run as a separate project, then I tried creating a sample jFrame and then added this .java file and run it. When I clicked the button it created the report. But the actual project (which I developed in 20 days GUI and the functionalities) it throws the error shown. I even tried to put the report code in the gui file itself but got the same error. I am not able to resolve the issue.
Can anyone please help?
Thanks
Ok I got the resolution...
It seems Dynamic Charts uses jFreeChart Libraries. I was manually importing libraries for dynamic Charts as well as jFreeChart.
Resolution was : Delted all libraries and then imported only for dynamic charts.
I guess .xml for both libraries were conflicting.
Looks like you have multiple implementations .jar files for XML parsing (maybe multiples versions of xerces in classpath ?).
gnujaxp.jar also could be the source of the problem.
First, this is my first time with Apache Derby. I am using netbeans, willing to use embedded apache derby, and I followed the following tutorial for configuring and installing the database
http://netbeans.org/kb/docs/ide/java-db.html#starting
The attached image will show my database status in netbeans
My database name is "contact". Table name is "FRIENDS".
Following is my test code
DatabaseConnector.java
import java.sql.*;
public class DataBaseConnector
{
private Connection con;
public DataBaseConnector()
{
}
private void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby:contact","yohan","xyz");
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void closeConnection()
{
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void insertData(int id, String firstName, String lastName)
{
createConnection();
try
{
PreparedStatement ps = con.prepareStatement("insert into FRIENDS values(?,?,?)");
ps.setInt(1, id);
ps.setString(1, firstName);
ps.setString(2, lastName);
int result = ps.executeUpdate();
if(result>0)
{
System.out.println("Data Inserted");
}
else
{
System.out.println("Something happened");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
closeConnection();
}
}
}
DatabaseUI.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class DatabaseUI extends JFrame
{
private JLabel firstName, id, lastName;
private JTextField idTxt, firstNameTxt, lastNameTxt;
private JButton ok;
public DatabaseUI()
{
firstName = new JLabel("First Name: ");
lastName = new JLabel("Last Name: ");
id = new JLabel("ID: ");
firstNameTxt = new JTextField(10);
lastNameTxt = new JTextField(10);
idTxt = new JTextField(10);
ok = new JButton("OK");
ok.addActionListener(new OKAction());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(4,2));
centerPanel.add(id);
centerPanel.add(idTxt);
centerPanel.add(firstName);
centerPanel.add(firstNameTxt);
centerPanel.add(lastName);
centerPanel.add(lastNameTxt);
centerPanel.add(new JPanel());
centerPanel.add(ok);
getContentPane().add(centerPanel,"Center");
this.pack();
this.setVisible(true);
}
private class OKAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
DataBaseConnector db = new DataBaseConnector();
int id = Integer.parseInt(idTxt.getText());
db.insertData(id, firstNameTxt.getText().trim(), lastNameTxt.getText().trim());
}
}
public static void main(String[]args)
{
new DatabaseUI();
}
}
But, when I am trying to insert data into the database, it is giving me the following error
run:
java.sql.SQLException: Database 'contact' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at DataBaseConnector.createConnection(DataBaseConnector.java:17)
at DataBaseConnector.insertData(DataBaseConnector.java:40)
at DatabaseUI$OKAction.actionPerformed(DatabaseUI.java:52)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6504)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6269)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4860)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.sql.SQLException: Database 'contactDB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 53 more
java.lang.NullPointerException
at DataBaseConnector.insertData(DataBaseConnector.java:43)
at DatabaseUI$OKAction.actionPerformed(DatabaseUI.java:52)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6504)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6269)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4860)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
java.lang.NullPointerException
at DataBaseConnector.closeConnection(DataBaseConnector.java:29)
at DataBaseConnector.insertData(DataBaseConnector.java:65)
at DatabaseUI$OKAction.actionPerformed(DatabaseUI.java:52)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6504)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6269)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4860)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Please help me. Thanks
The connection URL "jdbc:derby:contact" specifies that the 'contact' database should be found in the current working directory of your process, but that's probably not where it's actually located. When your Java program is run, the current working directory is probably been set somewhere else. You can confirm this by printing out the current working directory at the start of your program.
To get around this for now, you can specify the full path to your database: "jdbc:derby:/path/to/my/db/contact".
If that gets you farther, then you can keep going, but at some point you'll have to think more about where you want your database to be permanently located and how you want to specify that in your program.
Kindly look at your derby/jdbc connection,
This line here:
con = DriverManager.getConnection("jdbc:derby:contact","yohan","xyz");
Check if it looks similar to:
"jdbc:derby://localhost:1527/contact"
Or, as what I've seen, the name of your database is ContactDB... Kindly check...
Thanks...