I have as a task to simulate how queues evolve in a supermarket and I have to use timers to output whenever a client enters or exists the store. In the supermarket I have 3 queues that should process customers. At each client, they should output in my GUI the arrival time and the leaving time. Can I use the same timer for each queue? (they should not start outputting simultaneously or for the same period of time). I tried to pass the timer as a parameter in the event class but I get a Null Pointer exception. Help pls.
public void simulationPrep (Queue q,JPanel p,int time,Timer t, int selection)
{
TimeClass tc;
int queueCapacity=0;
float queueProcTime=0;
float tempSTMin, float tempSTMax;
tempSTMin=getServiceTimeMin();
tempSTMax=getServiceTimeMax();
queueCapacity = 10 + (int)( Math.random()*20);
queueProcTime = tempSTMin + (float)(Math.random()*tempSTMax);
q1.setCapacity(queueCapacity);
q1.setProcessingTime(queueProcTime);
tc = new TimeClass((int)(queueProcTime/queueCapacity),p,selection);
t = new Timer(time, tc);
t.start();
}
public void simulate()
{
if(getSelection()>=1)
{
simulationPrep(q1,p21,1000,timer1,1);
if(getSelection()>=2)
{
simulationPrep(q2,p22,1500,timer2,2);
if(getSelection()==3)
{
simulationPrep(q3,p23,1700,timer3,3);
}
}
}
}
public class TimeClass implements ActionListener
{
int counter;
JPanel p;
int selection;
public TimeClass(int counter,JPanel p,int selection)
{
this.counter = counter;
this.p = p;
this.selection = selection;
}
public void actionPerformed(ActionEvent e)
{
counter--;
if(counter>=1)
{
p.add(new JLabel("Hi "+counter));
p.updateUI();
}
if(counter<1)
{
p.add(new JLabel("Done"));
p.updateUI();
timer1.stop();
timer2.stop();
timer3.stop();
}
}
}
If one does not understand the code please ask, I'll be more specific, but this is my first post here and I'm kind of new to Java.
This is what I get in the output window :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at simulation.Simulation$TimeClass.actionPerformed(Simulation.java:229)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.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$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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at simulation.Simulation$TimeClass.actionPerformed(Simulation.java:229)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.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$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)
Line 229 of your Simulation.java file is causing a NullPointerException. Specifically it is in the actionPerformed(...) method of your TimeClass inner class.
Go to that line, and there you'll have your problem.
I suspect it is one of these 3 lines:
timer1.stop();
timer2.stop();
timer3.stop();
One of these timer variables is probably null.
A quick fix (although probably not addressing the real problem) is this:
if (timer1 != null) {
timer1.stop();
}
and so on with the other two timer variables.
Related
As a follow-up to this question that I posted earlier, I am wondering about the cause of the issue I had.
The problem was that I was getting this error when updating a JLabel with a lot of HTML text.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.html.StyleSheet$ListPainter.paint(Unknown Source)
at javax.swing.text.html.ListView.paintChild(Unknown Source)
at javax.swing.text.BoxView.paint(Unknown Source)
at javax.swing.text.html.BlockView.paint(Unknown Source)
at javax.swing.text.html.ListView.paint(Unknown Source)
at javax.swing.text.BoxView.paintChild(Unknown Source)
at javax.swing.text.BoxView.paint(Unknown Source)
at javax.swing.text.html.BlockView.paint(Unknown Source)
at javax.swing.text.BoxView.paintChild(Unknown Source)
at javax.swing.text.BoxView.paint(Unknown Source)
at javax.swing.text.html.BlockView.paint(Unknown Source)
at javax.swing.text.BoxView.paintChild(Unknown Source)
at javax.swing.text.BoxView.paint(Unknown Source)
at javax.swing.text.html.BlockView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicHTML$Renderer.paint(Unknown Source)
at javax.swing.plaf.basic.BasicLabelUI.paint(Unknown Source)
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1200(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The HTML that's being set is generated by a StringBuilder and the converted .toString. Something like this, but more extensive:
public static String entityOverviewHTML() {
StringBuilder sb = new StringBuilder();
List<Entity> entities = Entity.getEntities();
sb.append("<html><div style='padding: 12px;'>");
sb.append("<h1>People: alive</h1>");
// A lot of appending: also loop through getEntities (dynamic, can change)
// and get contents from each entity in #getEntityInfo below
if (entities.size() > 0) {
sb.append("<ul>");
for (Entity e: entities) {
getEntityInfo(e);
}
sb.append("</ul>");
}
sb.append("</div></html>");
return sb.toString();
}
private static StringBuilder getEntityInfo(Entity e) {
StringBuilder sbInfo = new StringBuilder();
// A lot of appending: append info of Entity e such as e.getFirstName()
sbInfo.append("<li>");
sbInfo.append(e.getFirstName())
sbInfo.append("</li>");
return sbInfo;
}
After some events, the HTML will change after which I call a custom refresh method:
public static void bringToFront() {
getInstance().setVisible(true);
getInstance().setExtendedState(JFrame.ICONIFIED);
getInstance().setExtendedState(JFrame.NORMAL);
}
public static void refresh() {
// text is a JLabel
text.setText(entityOverviewHTML());
bringToFront();
}
And it's then that the errors at the top of this post happen, however not always! I haven't figured out why this happens, but I did find that when resetting the text to an empty string and then calling entityOverviewHTML solves the issue.
public static void refresh() {
text.setText(""); // Here we go
text.setText(entityOverviewHTML());
bringToFront();
}
text is defined as a Class variable:
private static JLabel text = new JLabel();
What I like to know is: why? How can this single line of seemingly obsolete code solve the problem? Exactly what is the problem?
The problem is that your refresh() method is not called on the Swing EDT.
Swing is not threadsafe (https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) which means that the call text.setText(entityOverviewHTML()); corrupts the internal data structures that your JLabel instance uses to display the text.
Your refresh-method needs to be rewritten like this:
public static void refresh() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
text.setText(entityOverviewHTML());
bringToFront();
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
Usually when JLabel is instantiated, it has no width , if it is instantiated with empty text width is zero. When JLabel text is updated it won't show up as its size is not set properly.
Use preferred size: text.setPreferredSize(new Dimension(x, y)); then text.setText(html)
I try to make Test code about JTable input and refresh.
Insert and delete is working well,
but if I delete or insert data after sort the table, it make's exception:
"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException : 9>=0" ..
Here's my test code.
How do I fix it?
and.. any other advice?
public class Test extends JFrame{
private DefaultTableModel modelTest = new DefaultTableModel();
private JTable tableTest = new JTable(modelTest);
private JScrollPane paneTest = new JScrollPane(tableTest);
private JButton button1 = new JButton("pattern1");
private JButton button2 = new JButton("pattern2");
private JButton button3 = new JButton("delete");
private void compInit(){
paneTest.setBounds(0, 0,778, 300);
button1.setBounds(250, 320,80,20);
button2.setBounds(450,320,80,20);
button3.setBounds(300,400,80,20);
DefaultTableModel tmp = modelTest;
tmp.addColumn(" ");
tmp.addColumn("col1");
tmp.addColumn("col2");
tmp.addColumn("col3");
tmp.addColumn("col4");
tmp.addColumn("col5");
tmp.addColumn("col6");
tmp.addColumn("col7");
try {
tableTest.setDefaultRenderer(Class.forName("java.lang.String"), new DefaultTableCellRenderer());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
tableTest.setAutoCreateRowSorter(true);
tableTest.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableTest.getColumnModel().getColumn(0).setPreferredWidth(20);
tableTest.getColumnModel().getColumn(1).setPreferredWidth(45);
tableTest.getColumnModel().getColumn(2).setPreferredWidth(110);
tableTest.getColumnModel().getColumn(3).setPreferredWidth(60);
tableTest.getColumnModel().getColumn(4).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(5).setPreferredWidth(227);
tableTest.getColumnModel().getColumn(6).setPreferredWidth(100);
tableTest.getColumnModel().getColumn(7).setPreferredWidth(100);
tableTest.getTableHeader().setForeground(new Color(105,105,105));
this.add(button1);
this.add(button2);
this.add(button3);
this.add(paneTest);
}
private void pattern1(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("a : " + i);
rowData.add("b : " + i);
rowData.add("c : " + i);
rowData.add("d : " + i);
rowData.add("e : " + i);
rowData.add("f : " + i);
modelTest.addRow(rowData);
}
}
private void pattern2(){
for(int i = 0;i<10;i++){
Vector rowData = new Vector<>();
rowData.add(false);
rowData.add(i+1);
rowData.add("z : " + i);
rowData.add("y : " + i);
rowData.add("x : " + i);
rowData.add("w : " + i);
rowData.add("v : " + i);
rowData.add("u : " + i);
modelTest.addRow(rowData);
}
}
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
private void eventInit(){
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern1();
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
pattern2();
}
});
button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
delete();
}
});
}
public Test(){
this.setLayout(null);
this.compInit();
this.eventInit();
this.setSize(778, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] ar){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Test();
}
});
}
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 1
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getValueAt(Unknown Source)
at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getStringValueAt(Unknown Source)
at javax.swing.DefaultRowSorter.compare(Unknown Source)
at javax.swing.DefaultRowSorter.access$100(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
at java.util.Arrays.binarySearch0(Unknown Source)
at java.util.Arrays.binarySearch(Unknown Source)
at javax.swing.DefaultRowSorter.insertInOrder(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern1(Test.java:77)
at timer.Test.access$0(Test.java:66)
at timer.Test$1.actionPerformed(Test.java:106)
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$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.DefaultRowSorter.getViewToModelAsInts(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted0(Unknown Source)
at javax.swing.DefaultRowSorter.rowsInserted(Unknown Source)
at javax.swing.JTable.notifySorter(Unknown Source)
at javax.swing.JTable.sortedTableChanged(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsInserted(Unknown Source)
at javax.swing.table.DefaultTableModel.insertRow(Unknown Source)
at javax.swing.table.DefaultTableModel.addRow(Unknown Source)
at timer.Test.pattern2(Test.java:92)
at timer.Test.access$1(Test.java:81)
at timer.Test$2.actionPerformed(Test.java:111)
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$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Whenever you change your model vector directly, make sure to notify the container about this. You fail to do that in the following method:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tableTest.repaint();
}
After the removeAllElements() you should call tmp.fireTableDataChanged(). Something like:
private void delete(){
DefaultTableModel tmp = modelTest;
tmp.getDataVector().removeAllElements();
tmp.fireTableDataChanged();
tableTest.repaint();
}
Reason: Changes directly to the Model's underlying data vector are not automatically propagated to the View. You are changing a Vector this way, not a Model. Changes to the Model are propagated to the View. Your calls to Model.addRow() inform the View that a row was added. Your Vector.removeAllElements() call is not informed to the View so after that call View and Model are out of sync (that is, if they weren't both empty before). The call to Model.fireTableDataChanged informs the View that the whole table data in the Model has changed. After this call they are in sync again. When Model and View are out of sync, you can expect ArrayOutOfBoundException's to occur e.g. during sorting.
I also had this problem recently - a NullPointerException caused by DefaultRowSorter.getViewToModelAsInts.
The problem for me is that I was trying to directly update the GUI when an exception was thrown in SwingWorker's doInBackground() method. I found the exact solution to my particular problem here. Maybe that will help you or at least point you in the right direction as I wouldn't be surprised if your problem was because you are trying to manipulate the GUI from the wrong thread.
I'm writing a code that involves JFrame, and a thread.
The thread should take the text from a text field and write it into text area.
I have 4 buttons as follows:
"Start" to start the thread.
"Stop" which stops the thread.
"Pause" which pause and continues the thread.
and "Exit" which stops the thread and exits the program.
I've created the thread and implemented "run()" function in frame's constructor, here it is:
WritingThread = new Thread(new Runnable() {
#Override
public void run() {
String s = WrittenText.getText();
while(true)
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < s.length(); j++)
{
WritingArea.append("" + s.charAt(j));
try {
Thread.sleep((int)ThreadSpeedSpinner.getValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
WritingArea.append("\n");
}
WritingArea.setText("");
}
}
});
and these are the buttons:
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(!WritingThread.isAlive())
WritingThread.start();
}
});
JButton btnStop = new JButton("Stop");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(WritingThread.isAlive())
WritingThread.stop();
}
});
btnPause = new JButton("Pause");
btnPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(!isPaused)
{
if(WritingThread.isAlive())
{
WritingThread.suspend();
btnPause.setText("Continue");
isPaused = true;
}
}
else
{
WritingThread.resume();
btnPause.setText("Pause");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WritingThread.stop();
System.exit(0);
}
});
I have two problems showing up:
When I use stop(), suspend(), or resume(), I get a warning says "The method from the type Thread is deprecated".
When I run the program, I start the thread, then stop it, then try to start it I have this exception
Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at com.HomeWork.HomeWork5$6.actionPerformed(HomeWork5.java:140)
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$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I don't want direct answers, I want to understand why I'm getting these errors, and if there any resources I should go through.
P.S. I searched for an answer a lot and didn't get anything explaining this problem.
Thanks
Threads acquire lock on objects. And the most important part of multithreading
is to safely interweave the threads, so that all the threads can use the resource (object).
If not dealt with correctly, it leads to deadlock.
When you use stop(), you are killing the thread. That thread is gone forever. It
may lead the objects, that stopped thread had acquired, in a inconsistent state.
suspend() is deprecated, because once the thread is suspended other threads won't get the
resource, since the suspended thread holds a lock on it.
The image below describes how threads should be correctly used.
Use sleep(), wait(), and notify() for interleaving the threads efficiently.
today I'm having a bit of a slight, see, I'm trying to run my code and I'm getting a NullPointerException. The clues in the exception leads me to this function right here:
private void irGuiJuego(JFrame frame){
SwingConsole.run(new GUIJuego(), 800, 600, true);
frame.dispose();
}
Where SwingConsole would have this code:
package utiles;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class SwingConsole {
public static void run(final JFrame frame, final int width, final int height, final boolean exitOnClose) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (exitOnClose)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
//frame.setResizable(false);
frame.setVisible(true);
}
});
}
public static void run(final JFrame frame, final int width, final int height, final boolean exitOnClose, final String title) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
if (exitOnClose)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title);
frame.setSize(width, height);
frame.setVisible(true);
}
});
}
}
It is kind of odd, considering that I'm using the same method to open up another frame, in this function to be specific:
private void volverMenuInicio(JFrame frame){
SwingConsole.run(new MenuInicio(), 300, 150, true);
frame.dispose();
}
I'll leave you guys a pastebin of the GUIJuego Frame, since it's sort of excessive to post it here: http://pastebin.com/LSXbc7KE , have the pastebin of the other frame too, in case you need it: http://pastebin.com/hbdd7j84
Edit: Here's the stacktrace, sorry for the lack of it before!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source) at
java.awt.Container.add(Unknown Source) at
gui.GUIJuego.(GUIJuego.java:113) at
gui.MenuNuevoJuego.irGuiJuego(MenuNuevoJuego.java:95) at
gui.MenuNuevoJuego.access$2(MenuNuevoJuego.java:94) at
gui.MenuNuevoJuego$2.actionPerformed(MenuNuevoJuego.java:74) 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$200(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.awt.EventQueue$3.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue$4.run(Unknown Source) at
java.awt.EventQueue$4.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown
Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at
java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at
java.awt.EventDispatchThread.run(Unknown Source)
Thanks for reading, by the way!
The NPE is being thrown from line 113 in GUIJuego.java, as the stack trace indicates:
panelDatosCiudad.add(arcaLabel);
It's happening because arcaLabel, defined in line 35, is never set to a value, and so you're adding a null JLabel to the container.
I have a java program that creates a JFrame like this:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui.setFrame(new gui(), 1000, 300);
}
});
I also have a class (gui.java) that implements setFrame:
public static void setFrame(final JFrame frame, final int width, final int height) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f1=frame;
frame.setTitle("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
});
}
If the user tries to click Submit (a button I created) and the fields in the JFrame are not filled in then it throws an error. The code for the error message is:
submit.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {
//check to make sure all values filled in
if(chooser.getSelectedFile().toString()!=null&&saveChooser.getSelectedFile().toString()!=null)
parseFile.readFile(chooser.getSelectedFile(),saveChooser.getSelectedFile(),startSpanText.getText(),(String)col2.getSelectedItem(),(String)col3.getSelectedItem(),(String)col4.getSelectedItem(),(String)col5.getSelectedItem(),(String)col6.getSelectedItem());
else
JOptionPane.showMessageDialog(f1,"Bad");
}
});
//Note: f1 is a static version of the frame I initially received
The error I get is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at gui$3.mouseReleased(gui.java:133)
at java.awt.AWTEventMulticaster.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$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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
What did I do wrong?
One of the variables is null. It could be:
chooser
chooser.getSelectedFile()
saveChooser
saveChooser.getSelectedFile()
parseFile
startSpanText
col2 to col6
Use the line number in the stack trace, and a debugger or traces in the code to know which one. My guess would be one of the selected files, since it makes no sense to call
chooser.getSelectedFile().toString() != null
Either there is no selected file, and it throws an NPE because getSelectedFile() returns null, or there is one, and its toString() will never be null.
Also, you shouldn't use a mouse listener to do something when a button is pressed. That's what an ActionListener is for. It will be simpler, and also work when the user presses the button with its keyboard.
Your exception message should point you to the answer. One of the items you are using in your mouseReleased method is null:
#Override
public void mouseReleased(MouseEvent e) {
//check to make sure all values filled in
if(chooser.getSelectedFile().toString()!=null &&
saveChooser.getSelectedFile().toString()!=null)
parseFile.readFile(chooser.getSelectedFile(), saveChooser.getSelectedFile(),
startSpanText.getText(), (String)col2.getSelectedItem(),
(String)col3.getSelectedItem(), (String)col4.getSelectedItem(),
(String)col5.getSelectedItem(), (String)col6.getSelectedItem());
else
JOptionPane.showMessageDialog(f1,"Bad");
}
Use a debugger to inspect which variables are set. Use the line number in the exception message to help you.