First of all, please do not mark this question as duplicate & close it without going through the whole problem. I have searched for problems similar to mine, but couldn't find any. So I request that you kindly direct me to the post that has a similar problem & then close it.
Now the problem.
I have created a popup window in a JavaFX application. I have two buttons on the main window/stage, pressing either of which generates a new window/stage. However when I close the newly generated popup window and press those buttons on the original window again, it results in JavaFX application thread exception.
Here is the code for the buttons & the action associated with them & it is in the MAIN WINDOW:
public class FirstScene
{
//.....usual code.....//
//Creating the buttons
Button leftClick = new Button("",lftIcon);
Button rightClick = new Button("", rghtIcon);
//Adding ACTION to the buttons
add.setOnAction(ae->LoginFunc.loginHandler("add"));
remove.setOnAction(ae ->LoginFunc.loginHandler("remove"));
Here's the code for LoginFunc that handles the event & it is in the popup window
public class LoginFunc
{
private static String userID, password, button;
private static Stage loginStage = new Stage();
static Button login = new Button("Login");
Scene addScene, removeScene;
public static void loginHandler(String bttn)
{
button = bttn;
loginStage.setTitle("Movie Database Login");
loginStage.setMaxHeight(400);
loginStage.setMaxWidth(400);
GridPane loginLayout = new GridPane();
loginLayout.getChildren().add(login);
Scene loginScene = new Scene(loginLayout,400,400);
login.setOnAction(eh -> ButtonClicked(eh));
loginStage.setScene(loginScene);
loginStage.initStyle(StageStyle.UTILITY);
loginStage.initModality(Modality.APPLICATION_MODAL);
loginStage.show();
}
private static void ButtonClicked (ActionEvent eh)
{
if(button == "add")
{
FirstScene.mainStage.setTitle("Add Window");
loginStage.close();
}
if(button == "remove")
{
FirstScene.mainStage.setTitle("Remove Window");
loginStage.close();
}
}
}
THE PROBLEM IS, once I close the newly generated popup window & press any of the buttons again, it results in the following exception:
Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: Cannot set style once stage has been set visible
at javafx.stage.Stage.initStyle(Unknown Source)
at MovieDataBase.LoginFunc.loginHandler(LoginFunc.java:34)
at MovieDataBase.FirstScene.lambda$0(FirstScene.java:101)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I want to be able to repeat the same window every time the button is pressed.
I'm sorry if this is a very simple problem & a solution already exists, I'm a beginner in Java & what my search resulted in, I couldn't find a single problem that related to mine.
Thank you for your valuable time & input
Your method call to LoginFunc is static and it uses static members of the class. That means that they are initialized and setup when you run through the method for the first time. The second time you call the method, they are already initialized. There are some methods (initStyle is one of them) that can only be called once in the lifecycle of the object.
However there is an easy solution to that: Remove the static modifiers from LoginFunc and create an instance in the event handler before you call the method loginHandler, however retain a reference to it, so you can pass it on the remove method.
Or even better separate the logic for adding and removing out of LoginFunc as it is not good decision to trigger behavior upon an input parameter.
You can have a factory method that will provide the event handlers for add and remove and use a boolean to decide which event handler the factory method should return.
public EventHandler<MouseEvent> createButtonClickEventHandler(boolean add) {
...
}
Then you can implement the buttons like this:
EventHandler<MouseEvent> addEventHandler = creatButtonClickEventHandler(true);
add.setOnAction(ae->new LoginFunc().loginHandler(addEventHandler));
EventHandler<MouseEvent> removeEventHandler = creatButtonClickEventHandler(false);
remove.setOnAction(ae->new LoginFunc().loginHandler(removeEventHandler));
Related
I created a program with windows builder to make a custom classifier using IBM Watson services and everything works fine but I have problems with the classification of an image using that classifier's ID from a text fie.
When I put the custom classifiers ID inside the code it works fine but when I am trying to take that ID from a TextField it won't work.
Here is the code inside the button's action event. The variable String id outputs exactly What is inside the parameters method but it replaces the id (cats_599303326) with the id that is in the TextField but when I put id as an argument in the parameters method, program won't run successfully.
On the other hand, if I comment everything and just output the id String, copy and paste it inside the parameters method, It worked fine.
Why it won't work when I pass the variable id through?
VisualRecognition service = new VisualRecognition(
VisualRecognition.VERSION_DATE_2016_05_20
);
service.setEndPoint("https://gateway-a.watsonplatform.net/visual-recognition/api");
service.setApiKey("{api-key}");
File imagesStream = new File(textField.getText());
ClassifyOptions classifyOptions = null;
String id = String.format("\"{\\\"classifier_ids\\\": [\\\"%s\\\"]}\"", textField_1.getText());
System.out.println(id);
try {
classifyOptions = new ClassifyOptions.Builder()
.imagesFile(imagesStream)
.imagesFilename("Image ")
.parameters("{\"classifier_ids\": [\"cats_599303326\"]}") //inside the parameters method, the goal is to replace cats_599303326 with an id given from a textfield
.build();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
ClassifiedImages result = service.classify(classifyOptions).execute();
System.out.println(result);
Error log when putting the variable id as an argument in the parameters method, and as I said before, if I just print the id String, copy it and paste it as an argument in the parameters method program will run successfully but it won't run if i put it as a variable:
Jan 10, 2018 6:07:55 AM okhttp3.internal.platform.Platform log
INFO: --> POST https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?version=2016-05-20&api_key=aca4433597018de62edafdeebceb2bdc1482496a http/1.1 (-1-byte body)
Jan 10, 2018 6:08:06 AM okhttp3.internal.platform.Platform log
INFO: <-- 400 Bad Request https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?version=2016-05-20&api_key=aca4433597018de62edafdeebceb2bdc1482496a (10214ms, 167-byte body)
Jan 10, 2018 6:08:06 AM com.ibm.watson.developer_cloud.service.WatsonService processServiceCall
SEVERE: POST https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?version=2016-05-20&api_key=aca4433597018de62edafdeebceb2bdc1482496a, status: 400, error: {
"images_processed": 0,
"error": {
"code": 400,
"description": "Invalid form data 'parameters'",
"error_id": "parameter_error"
}
}
Exception in thread "AWT-EventQueue-0" com.ibm.watson.developer_cloud.service.exception.BadRequestException: {
"images_processed": 0,
"error": {
"code": 400,
"description": "Invalid form data 'parameters'",
"error_id": "parameter_error"
}
}
at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:408)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:174)
at visualRecognitionSecondTry.ClassifyInterface$3.actionPerformed(ClassifyInterface.java:129)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
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.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(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.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.security.ProtectionDomain$JavaSecurityAccessImpl.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$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)
This error indicates the service was unable to parse your JSON parameters object. I suspect you are either missing the quotation marks or not submitting the classifier_ids as an array when taking the value from your textfield, but cannot tell without more code for how you do that.
If stackoverflow guys ban me for life and then come to my house and murder me, i would totally understand!! Solution was so simple it's embarrassing i did't think of it. Basically the String I created had extra quotation marks. The solution is :
String id = String.format("{\"classifier_ids\": [\"%s\"]}", textField_1.getText());
In my PhoneBook applcation after sorting by a column , when i remove a row and cal updateUI() i got a java.lang.IndexOutOfBoundsException in my model . But if not sorting there is no exeption
I guess the object has removed but in updateUI procedure it doesnt know that and somewhere return old getRowCount() ,according to stacktrace.
private void delete(int[] selectedIndexes) {
ArrayList<Contact> arlDeleting = new ArrayList<Contact>();
for (int i = selectedIndexes.length - 1; i >= 0; i--) {
int realIndex = tblPhonebook.convertRowIndexToModel(selectedIndexes[i]);
tblMdlAllContacts.getData().remove(realIndex);
}
tblPhonebook.updateUI();
}
here is stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at com.TableModelPhoneBook.getValueAt(TableModelPhoneBook.java:73) ***
at javax.swing.JTable.getValueAt(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) *** i think getRowCount called here
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.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JViewport.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.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$700(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$000(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.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 model.getvalueat:
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Contact temp = data.get(rowIndex); // here is where error occurs
switch (columnIndex) {
case 0:
return temp.getFirstName();
case 1:
return temp.getLastName();
case 2:
return temp.getMobile();
case 3:
return temp.getHome();
case 4:
return temp.getAddress();
default:
break;
}
return null;
}
Don't call updateUI() as this should only be called when L&F is changed. Your delete row method is part of your model right? Are you firing the model's fireXXX() notification methods after deleting? You should be. Also, I wonder if you should be using an iterator to do your deleting.
Edit
You state:
No delet method is part of my controller (is it wrong?).
Wrong. The method should be part of your table model, and controller can call this method on the model, but shouldn't have this method. The table model should extend AbstractTableModel and should call the proper fireXXX method when data is removed, added, or changed. For delete, call fireTableRowsDeleted method, and definitely check the AbstractTableModel API for the details on all such available notification methods.
I removed 'updateUI()' line ,its ok until i click on a cell of table ,when i do this he exeption thrwon . means that actually 'firexxx()' cuase it ,right?
No. I have no idea what your code is doing or the cause of your exceptions right now. Consider creating and posting an sscce.
Oh youre right . but Why when i call 'table.getModel()' i dont see fireXXX()'but by with a refernce to model instance it will be seen. 'mymodel.fireTableDataChanged()'
Outside classes should not call the fire methods. The model itself should be the only object calling its own notification methods.
If you haven't gone through the JTable tutorial, I suggest that you consider doing this without delay. It will help you a great deal.
I am making a calculator for an AP Computer Science Final. I built the GUI in Eclipse using Jigloo, and I quickly tried to learn about Action Listeners so you can hit the buttons to make numbers appear. The problems started occurring when I started enter the actual code to make calculations. I keep getting the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NewJFrame.<init>(NewJFrame.java:82)
at NewJFrame$1.run(NewJFrame.java:73)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$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)
I'm pretty new to Java, and I've never attempted a project like this before. I would love if you guys can help me fix this problem. Here is a link to my actual code, it won't fit in the code box for some reason: Link to code
You button variables aren't assigned until you call initGUI(), which is at the bottom of your constructor. So, when you do this:
jButton3.addActionListener(new ListenToOne());
... Java sees this:
null.addActionListener(new ListenToOne());
... which is obviously a problem.
I developed an app with a GUI, with buttons, relative actionListeners, and exceptions.
Today I had this problem. In an actionEvent relative to a button of my GUI, I inserted this code, with some JOptionPane.showInputDialog:
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==b1){
try{//FIRST `JOptionPane.showInputDialog`
int load = Integer.parseInt(JOptionPane.showInputDialog(null,"Insert current load value: "));
auto.setCurrentLoad(load);
//other `JOptionPane.showInputDialog`
int choiceDep = Integer.parseInt(JOptionPane.showInputDialog(null, "Does the truck transport perishable goods? 1: YES 2: NO"));
if(choiceDep==1) {
//here we have to insert expiration date
int day = Integer.parseInt(JOptionPane.showInputDialog(null,"Insert value"));
int month = Integer.parseInt(JOptionPane.showInputDialog(null,"Insert value"));
int year = Integer.parseInt(JOptionPane.showInputDialog(null,"Insert value"));
auto.setPerishable(day,month,year);
}
else if(choiceDep==2)
auto.setNotPerishable();
String choiceAv = JOptionPane.showInputDialog(null, "Available Truck? Yes or no?");
if(choiceAv.equals("Yes")) auto.setAvailable();
else auto.setNotAvailable();
}
//the exception
catch (Exception e) { System.out.println("Exception!");}
}
Where setAvailable, setNotAvailable,setPerishable,setCurrentLoad are methods of the external class, with reference auto.
When I execute this code, it appears the GUI, then I click on button b1. It appears the first JOptionPane.showInputDialog, to insert a value stored in a int load.
I entered a value, but no other JOptionPane.showInputDialog appeared (but there are other input dialog) and I got the exception in the command-line.
I noticed that the value inserted in the JOptionPane.showInputDialog is never passed to the line auto.setCurrentLoad(load);.
Why does it happen? Never seen this error before. Why do I always get the exception immediately after the first JOptionPane.showInputDialog Maybe the JVM doesn't accept many of this JOptionPane.showInputDialog in the same statement/method? Or maybe(as I think) is a programming error of mine?
Thanks for your help. Cheers.
EDIT: I forgot to insert the exception I got in the command-line:
java.lang.NullPointerException
at AutoCom.actionPerformed(AutoCom.java:50)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown So
ce)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
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.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(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)
Most likely, the auto object is not initialized before you pressed the button. I'm assuming auto is a member variable of the AutoCom class. In that case, you should probably change the auto definition to:
protected <TypeOfAutoHere> auto = new <TypeOfAutoHere>();
Based on your description it looks like the auto variable is null.
I have created a jar file which throws the below error, it's a simple swing app which inserts a row when I press a button, not sure where I am going wrong please advise.
private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
setatmid(jTextField2.getText());
setaa10(Integer.parseInt(jTextField3.getText()));
setaa20(Integer.parseInt(jTextField4.getText()));
setaa50(Integer.parseInt(jTextField5.getText()));
setaa100(Integer.parseInt(jTextField6.getText()));
try{
System.err.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "agents";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
con = DriverManager.getConnection(url+db,"root","");
Statement st = con.createStatement();
String query="INSERT INTO schedule_data (`s_ID`, `schedule_date`, `atmID`, `notification`) VALUES ('"+System.currentTimeMillis()+"','2010-09-15','"+getatmid()+"','null')";
st.executeUpdate(query);
System.err.println("1 row affected");
} catch(Exception e) {
e.printStackTrace();
}
}
Error:
java.lang.IllegalStateException: zip file closed
at java.util.zip.ZipFile.ensureOpen(Unknown Source)
at java.util.zip.ZipFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getEntry(Unknown Source)
at java.util.jar.JarFile.getJarEntry(Unknown Source)
at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
at sun.misc.URLClassPath.getResource(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at atmguis.atm.jButton20ActionPerformed(atm.java:588)
at atmguis.atm.access$1600(atm.java:25)
at atmguis.atm$17.actionPerformed(atm.java:226)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
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.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(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)
The method involved is being called from the Event Dispatch Thread. I'm sure this is a part of the problem. You are trying to access the JAR file containing the com.mysql.jdbc.Driver class from this thread. This is where the error is being thrown. I have to wonder if there is some sort of concurrency issue here. Here are a couple of general notes, things that should be addressed. Once you have addressed these issues, see if you are still having a problem.
You should not be doing a database query from inside the EDT. You should collect the information you need from the swing components and then use a Runnable object to execute the SQL query on a different thread. Do a search on SO for executing code on or off the EDT to find examples of how to do this. This will ensure that your UI doesn't lock up while you wait for your SQL results.
Opening and closing a database connection every time you need one is something better left to the SQL driver and its built-in connection pooling abilities. This method should be declared on some sort of controller object which already has a reference to the SQL connection. Then, when this method is called, you call your thread as in the last step, and that thread uses the reference to the SQL connection that it already has.
This will take the line that's throwing the exception and move it out of the EDT into some sort of setup phase, presumably where you will have better luck accessing the class file. Certainly it will be a much more controlled environment than within the EDT. If there continues to be a problem accessing it, it will be easier to debug in the more controlled environment.
As an added bonus, you will also be designing your application in much more robust way.