I wrote a code which gives a Java null pointer exception in JavaFX8. There are two classes: one that does a processing to an image Mat and another one that shows the image processed, in a different window. The code is:
public class ImagineComprimata
{
public Mat imComp;
#FXML
private ImageView imagineCompresata;
#FXML
private Button bSalveaza;
#FXML
private TextArea campRC;
#FXML
private TextArea campEMP;
#FXML
public void salveaza(ActionEvent eveniment)
{
//this will be edited later
}
public void arata() throws IOException
{
Stage scena = new Stage();
FXMLLoader fl = new FXMLLoader(getClass().getResource("/fxml/ImagineComprimata.fxml"));
AnchorPane p = (AnchorPane) fl.load();
Scene s = new Scene(p, 742, 495);
scena.setScene(s);
scena.showAndWait();
}
public void setMat(Mat imagine)
{
this.imComp = imagine;
}
public void setImagineCompresata(Image imagine)
{
this.imagineCompresata.setImage(imagine);
}
}
Now in the main window from which i make a call of this class to be displayed on screen:
public class Compresia
{
private Mat imagine;
private int parametru;
#FXML
public Button bSelecteaza;
#FXML
public Button bComprima;
#FXML
public Button bIntrodu;
#FXML
private ImageView foto;
#FXML
private TextField valoarea;
private String denumireFotografie;
private Matrix[] desc;
#FXML
public TextArea campRang;
private int rang;
#FXML
public void comprima(ActionEvent eveniment) throws InterruptedException, IOException
{
if (imagine == null)
{
Notificare.informeaza("Notificare", "Nu ai selectat o imagine!");
}
else
{
double[][] mc = AlgoritmDeCompresie.comprimaImaginea(desc, Util.extragereValori(imagine), parametru);
Mat im = Util.construiesteImagine(mc);
ImagineComprimata ic = new ImagineComprimata();
ic.setMat(im);
ic.setImagineCompresata(Util.conversieMat2Image(im));
ic.arata();
}
}
#FXML
public void cautaFisier(ActionEvent eveniment) throws InterruptedException
{
Matrix[] desc;
Mat im;
String denumire;
FileChooser f = new FileChooser();
File fotoSelectat = f.showOpenDialog(null);
if (fotoSelectat != null)
{
denumire = fotoSelectat.getPath();
im = Highgui.imread(denumire);
Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2GRAY);
this.desc = AlgoritmDeCompresie.descompune(Util.extragereValori(im));//////
rang = Util.returneazaRangul(Util.extragereValori(im));
imagine = im;
campRang.setText(Integer.toString(rang));
foto.setImage(Util.conversieMat2Image(im));
}
}
#FXML
public void seteazaParametru(ActionEvent eveniment)
{
int p = Integer.parseInt(this.valoarea.getText());
if (p >= this.rang)
{
Notificare.informeaza("Notificare", "Introdu un parametru mai mic decat rangul!");
this.valoarea.setText(null);
}
else
{
this.parametru = p;
Notificare.informeaza("Notificare", "parametru setat :" + p);
}
///////////////
}
public void start() throws Exception
{
Stage scena = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Compresia.fxml"));
AnchorPane b = (AnchorPane) loader.load();
Scene s = new Scene(b, 955, 586);
scena.setScene(s);
scena.setTitle("Compresie");
scena.setResizable(false);
scena.show();
}
public Matrix[] getDescompunere()
{
return this.desc;
}
public void setDescompunere(Matrix[] descompunere)
{
this.desc = descompunere;
}
}
It gives me an error at setImageCompressed(im) which traces to the setImageCompressed(Mat im). ImageCompressed is the JavaFX controller which shows the image proccessed. Where did I do wrong? The error report looks like this:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(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.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$355(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$149(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 49 more
Caused by: java.lang.NullPointerException
at interfata.ImagineComprimata.setImagineCompresata(ImagineComprimata.java:56)
at interfata.Compresia.comprima(Compresia.java:66)
... 58 more
It may be the case that "private ImageView imagineCompresata" instance of ImagineComprimata class is not getting initialized and remains pointing to a null , as a result of which when you are calling this.imagineCompresata.setImage(imagine) a NullPointerException is being raised.
Related
I have three SWT group control with the same name apart from the number (i.e. 'grp1','grp2','grp3').
I want to make visible the group control in a for cycle; for this I have created an Array that contains the Group control.
This is the code:
Group [] grpArray = new Group[3];
grpArray[0] = grp1;
grpArray[1] = grp2;
grpArray[2] = grp3;
txtLvl = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
txtLvl.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
for (int i = 1; i <= Integer.parseInt(txtLvl.getText()); i++) {
grpArray[i-1].setVisible(true);
}
}
}
);
This is the error code:
at it.anabasibdg.viste.AnagPdc$4.modifyText(AnagPdc.java:296)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Text.wmCommandChild(Unknown Source)
at org.eclipse.swt.widgets.Control.WM_COMMAND(Unknown Source)
at org.eclipse.swt.widgets.Control.windowProc(Unknown Source)
at org.eclipse.swt.widgets.Display.windowProc(Unknown Source)
at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method)
at org.eclipse.swt.internal.win32.OS.CallWindowProc(Unknown Source)
at org.eclipse.swt.widgets.Text.callWindowProc(Unknown Source)
at org.eclipse.swt.widgets.Control.windowProc(Unknown Source)
at org.eclipse.swt.widgets.Text.windowProc(Unknown Source)
at org.eclipse.swt.widgets.Display.windowProc(Unknown Source)
at org.eclipse.swt.internal.win32.OS.SetWindowTextW(Native Method)
at org.eclipse.swt.internal.win32.OS.SetWindowText(Unknown Source)
at org.eclipse.swt.widgets.Text.setText(Unknown Source)
at it.anabasibdg.viste.AnagPdc$3.widgetSelected(AnagPdc.java:213)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at it.anabasibdg.viste.Main.open(Main.java:58)
at it.anabasibdg.viste.LoginForm$3.widgetSelected(LoginForm.java:191)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at it.anabasibdg.viste.LoginForm.open(LoginForm.java:110)
at it.anabasibdg.viste.LoginForm$1.run(LoginForm.java:59)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:338)
at it.anabasibdg.viste.LoginForm.main(LoginForm.java:55)
I have just solved my problem in this way:
private ArrayList<Group> grpArray1 = new ArrayList<Group>();
txtLvl.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
groupArray(grp1, grp2,grp3);
for (Group grp : grpArray1) {
grp.setVisible(true);
}
public void groupArray(Group... c) {
for (Group group : c) {
grpArray1.add(group);
}
}
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)
The code is supposed to get an order and its price and save them in their respective ArrayLists.
public class SetMenu0{
private double price;
private int size;
private String output;
private String priceOutput;
String next;
JTextField orderIn;
JTextField priceIn;
private JFrame orderInput;
JPanel txtFldPanel;
JPanel btnPanel;
ArrayList orderList = new ArrayList<String>();
ArrayList priceList = new ArrayList<Double>();
public SetMenu0()
{
orderInput = new JFrame();
orderInput.setTitle("Input Order and Price");
orderInput.setSize(200,350);
orderInput.getContentPane();
orderInput.setLayout(new BorderLayout());
orderInput.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel txtFldPanel = new JPanel();
orderIn = new JTextField(10);
priceIn = new JTextField(5);
txtFldPanel.add(orderIn);
txtFldPanel.add(priceIn);
JPanel btnPanel = new JPanel();
JButton addBtn = new JButton("ADD");
btnPanel.add(addBtn);
addBtn.addActionListener(new ButtonListener());
addBtn.setActionCommand("add");
JButton fnshBtn = new JButton("FINISH");
btnPanel.add(fnshBtn);
addBtn.addActionListener(new ButtonListener());
fnshBtn.setActionCommand("fnsh");
size = orderList.size();
Container cont = orderInput.getContentPane();
cont.add(txtFldPanel,BorderLayout.NORTH);
cont.add(btnPanel,BorderLayout.SOUTH);
orderInput.pack();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String actionEnter = e.getActionCommand();
if(actionEnter.equals("add"))
{
orderList.add(orderIn.getText());
priceList.add(Double.parseDouble(priceIn.getText()));
orderIn.setText("");
priceIn.setText("");
}
else if(actionEnter.equals("fnsh"))
{
orderInput.dispose();
}
}
}
public JFrame getFrame()
{
return orderInput;
}
public ArrayList getOrd()
{
return orderList;
}
public ArrayList getPri()
{
return priceList;
}
public int getSize()
{
return size;
}
}
When i press the ADD button it shows a NumberFormatException. Why is this? I could add the rest of the code from the main but why is it not saving in the ArrayList?
This is the error:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.howtodoinjava.demo.poi.SetMenu0$ButtonListener.actionPerformed(SetMenu0.java:84)
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$400(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)
It's probably due to this line:
priceList.add(Double.parseDouble(priceIn.getText()));
You want to make sure that priceIn text field contains a number before you try to parse the text.
You have to use (on button add click)
if(!(priceIn.isEmpty || orderIn.isEmpty)){
//Do your adding
}
This code checks if there is something in the JTextFiels
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.
This only happens around about 1/10 runs and I'm not exactly sure why it is happening the Exception isn't giving me an error I know
Here is my class that extends JFrame
private StyledDocument debug;
private JScrollPane debugSP;
private StyledDocument chat;
private JScrollPane chatSP;
public DapBotGUI()
{
super("JFrame");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
JTextPane debug = new JTextPane();
debugSP = new JScrollPane(debug);
debugSP.setBounds(0, 0, this.getWidth() - 20, this.getHeight() / 2 - 20);
debugSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
debugSP.setAutoscrolls(true);
JTextPane chat = new JTextPane();
chatSP = new JScrollPane(chat);
chatSP.setBounds(0, this.getHeight() / 2 - 20, this.getWidth() - 20, this.getHeight() / 2 - 20);
chatSP.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
chatSP.setAutoscrolls(true);
this.getContentPane().add(debugSP);
this.getContentPane().add(chatSP);
this.setVisible(true);
this.debug = debug.getStyledDocument();
this.chat = chat.getStyledDocument();
}
public void debug(String message)
{
debug(message, Color.BLACK);
}
public synchronized void debug(String message, Color color)
{
SimpleAttributeSet formatter = new SimpleAttributeSet();
StyleConstants.setForeground(formatter, color);
StyleConstants.setBackground(formatter, Color.WHITE);
try
{
debug.insertString(debug.getLength(), message + System.lineSeparator(), formatter);
JScrollBar vertical = debugSP.getVerticalScrollBar();
vertical.setValue(vertical.getMaximum());
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
public void chatMessage(String message)
{
chatMessage(message, Color.BLACK);
}
public synchronized void chatMessage(String message, Color color)
{
SimpleAttributeSet formatter = new SimpleAttributeSet();
StyleConstants.setForeground(formatter, color);
StyleConstants.setBackground(formatter, Color.WHITE);
try
{
chat.insertString(chat.getLength(), message + System.lineSeparator(), formatter);
JScrollBar vertical = chatSP.getVerticalScrollBar();
vertical.setValue(vertical.getMaximum());
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
and then here is the error but from what I can see there are no direct issues with my code causing this error (That I can see).
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.text.FlowView$FlowStrategy.layoutRow(Unknown Source)
at javax.swing.text.FlowView$FlowStrategy.layout(Unknown Source)
at javax.swing.text.FlowView.layout(Unknown Source)
at javax.swing.text.BoxView.setSize(Unknown Source)
at javax.swing.text.BoxView.updateChildSizes(Unknown Source)
at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
at javax.swing.text.BoxView.layout(Unknown Source)
at javax.swing.text.BoxView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paintSafely(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.paint(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.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$3.run(Unknown Source)
at javax.swing.RepaintManager$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.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$1100(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$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.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)