I'm new to programming and I was making a calculator with only 1 textfield.
I need a method which can recognize which string characters from these (+ , - , * , /)
to send the result to a variable and when i click the = button it shows the result.
I have tried to write something like that (1+2) and save it to variable then then when I try to press = button to settext the variable it shows a privilage error.
Here is the code
JButton btnOne = new JButton("1");
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=1;
txtoprtn.setText(txtoprtn.getText()+"1");
JButton btnTwo = new JButton("2");
btnTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=2;
txtoprtn.setText(txtoprtn.getText()+"2");
}
});
JButton btnAdd = new JButton("+");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtoprtn.setText(txtoprtn.getText()+"+");
}
});
JButton btnEqual = new JButton("=");
btnEqual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = Integer.parseInt(txtoprtn.getText());
txtoprtn.setText(Integer.toString(x));
}
}
);
and this is the error
**Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1+2"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.jadv.day01.tasks.AdvCalc$11.actionPerformed(AdvCalc.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$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$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)**
any suggestions????
First problem
When you try to just write a string statement of "1+2", what do you expect will happen? It can't simply just be evaluated like that. You would have to first use Integer.parseInt() to each of your # buttons after the number insertion is done(say, when you click the +/-///*, or =. That means the number is done and you'll get say
Integer.parseInt("123") instead of Integer.parseInt("1")+Integer.parseInt("2")+Integer.parseInt("3")
What you're trying to do is parsing a + in the middle of the parse. Keep the integer parse to the numbers and the operators stored somewhere else(explained in second problem)
Second problem
When you say "+", that doesn't parse into any operation. You would have to store the values into their individual variables and when clicked a + button, you would get a correct answer. If you want to do this without any external imports, then you would have to store the operations in a list and evaluate when = is clicked.
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
operations.add("+");//operations is a list
}
});
Solving both problems at once using an import
If you want to evaluate using a package, then use this:
ScriptEngine evaluationMachine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(foo); //evaluates something like "2+1" into 3.
with the following imports:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
EDIT: By the way, though the second way is much faster, you should probably try and write it without external imports since you're new to programming. There will be inevitable situations where you're going to have to think about the problem.
The cause of the exception is that you are trying to parse a String like "1+2" to an Integer in the line:
x = Integer.parseInt(txtoprtn.getText());
You should store the numbers somewhere else, i.e. in an ArrayList.
Related
So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.
I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.
When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.
Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.
This is the code:
private String cValue;
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;
/**
* Create the frame.
*/
public CelsiusConverter() {
setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
setBounds(100, 100, 194, 134);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCelsius = new JLabel("Celsius");
lblCelsius.setBounds(10, 11, 61, 14);
contentPane.add(lblCelsius);
celsiusField = new JTextField();
celsiusField.setBounds(81, 8, 86, 20);
contentPane.add(celsiusField);
celsiusField.setColumns(10);
JLabel lblFahrenheit = new JLabel("Fahrenheit:");
lblFahrenheit.setBounds(10, 73, 70, 14);
contentPane.add(lblFahrenheit);
JLabel lblResult = new JLabel();
lblResult.setText(String.valueOf(result));
lblResult.setBounds(81, 73, 87, 14);
contentPane.add(lblResult);
cValue = celsiusField.getText();
convertButton = new JButton("Convert");
convertButton.setBounds(10, 39, 157, 23);
contentPane.add(convertButton);
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int parsed = Integer.parseInt(cValue);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CelsiusConverter frame = new CelsiusConverter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And this is the error:
Exception in thread "AWT-EventQueue-0" 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 learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
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)
cValue = celsiusField.getText();
You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.
You need to get the text from the text field in your ActionListener
String cValue = celsiusField.getText();
int parsed = Integer.parseInt(cValue);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I want to create an application which chooses the number to be guessed by selecting an integer at random in the range 1-1000.The application then displays the following in a label: I have a number between 1-1000.Can you guess my number?Please enter your first guess. As each guess is input,the background color should change to either red or blue.Red indicates that the user is getting "warmer" ,and blue,"colder".
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class GuessNumber extends JFrame{
private JLabel topLabel;
private JLabel colorLabel;
private JLabel correctLabel;
private JTextField numberText;
private JTextField inputText;
private JButton playBtn;
private int num;
GuessNumber(){
setSize(600,300);
setTitle("Guess the number");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
topLabel=new JLabel("I have a number between 1 and 1000.Can you guess my number?",JLabel.CENTER);
add("North",topLabel);
playBtn=new JButton("Play");
inputText=new JTextField();
inputText.setEditable(false);
correctLabel=new JLabel();
colorLabel=new JLabel();
//Read a random number when play button is clicked
playBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
Random r=new Random();
num=r.nextInt(1001);
numberText.setText(Integer.toString(num));
inputText.setEditable(true);
}
});
//Show whether your guess is close to the number or not
inputText.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
if(Integer.parseInt(inputText.getText())>num/2){
colorLabel.setText("Warmer");
colorLabel.setBackground(Color.red);
colorLabel.setOpaque(true);
}else{
colorLabel.setText("Colder");
colorLabel.setBackground(Color.blue);
colorLabel.setOpaque(true);
}
if(Integer.parseInt(inputText.getText())==num){
correctLabel.setText("Correct!");
correctLabel.setVisible(true);
inputText.setEditable(false);
}
}
});
JPanel centerPanel=new JPanel();
centerPanel.setLayout(new GridLayout(3,1));
centerPanel.add(inputText);
centerPanel.add(colorLabel);
centerPanel.add(correctLabel);
add(centerPanel);
add("South",playBtn);
setVisible(true);
}
}
class Example{
public static void main(String args[]){
new GuessNumber();
}
}
The program will compile but I get an exception in run time.I can't find the error in my program.How can I fix this?
Here is the error I get:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GuessNumber$1.actionPerformed(Example.java:34)
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 Sour
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.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.doIntersectionP
rivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionP
rivilege(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.doIntersectionP
rivilege(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)
you forgot numberText = new JTextField();. You need to initialize a reference-variable before you can use it.
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 am trying to design a three cascade JComboBox in JAVA:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class ThreeCascadeJComboBox {
private JComboBox combo1;
private JComboBox combo2;
private JComboBox combo3;
public static void main(String[] args) {
new ThreeCascadeJComboBox();
}
public ThreeCascadeJComboBox() {
JFrame v = new JFrame();
v.getContentPane().setLayout(new FlowLayout());
combo1 = new JComboBox();
loadCombo1();
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadCombo2((String) combo1.getSelectedItem());
}
});
combo2 = new JComboBox();
loadCombo2((String) combo1.getSelectedItem());
combo2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadCombo3((String) combo2.getSelectedItem());
}
});
combo3 = new JComboBox();
loadCombo3((String) combo2.getSelectedItem());
v.getContentPane().add(combo1);
v.getContentPane().add(combo2);
v.getContentPane().add(combo3);
v.pack();
v.setVisible(true);
v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private void loadCombo1() {
combo1.addItem("letters");
combo1.addItem("numbers");
}
private void loadCombo2(String seleccionEnCombo1) {
combo2.removeAllItems();
if (seleccionEnCombo1.equals("letters")) {
combo2.addItem("A");
combo2.addItem("B");
combo2.addItem("C");
} else if (seleccionEnCombo1.equals("numbers")) {
combo2.addItem("1");
combo2.addItem("2");
combo2.addItem("3");
}
}
private void loadCombo3(String seleccionEnCombo2) {
combo3.removeAllItems();
if (seleccionEnCombo2.equals("A")) {
combo3.addItem("A-1");
combo3.addItem("A-2");
combo3.addItem("A-3");
} else if (seleccionEnCombo2.equals("B")) {
combo3.addItem("B-1");
combo3.addItem("B-2");
combo3.addItem("B-3");
} else if (seleccionEnCombo2.equals("C")) {
combo3.addItem("C-1");
combo3.addItem("C-2");
combo3.addItem("C-3");
} else if (seleccionEnCombo2.equals("1")) {
combo3.addItem("1-a");
combo3.addItem("1-b");
combo3.addItem("1-c");
} else if (seleccionEnCombo2.equals("2")) {
combo3.addItem("2-a");
combo3.addItem("2-b");
combo3.addItem("2-c");
} else if (seleccionEnCombo2.equals("3")) {
combo3.addItem("3-a");
combo3.addItem("3-b");
combo3.addItem("3-c");
}
}
}
But I get the next Exception when I select the numbers value in the jcombo1:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at es.mycompany.MyView.ThreeCascadeJComboBox.loadCombo3(ThreeCascadeJComboBox.java:78)
at es.mycompany.MyView.ThreeCascadeJComboBox.access$3(ThreeCascadeJComboBox.java:76)
at es.mycompany.MyView.ThreeCascadeJComboBox$2.actionPerformed(ThreeCascadeJComboBox.java:40)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.JComboBox.intervalRemoved(Unknown Source)
at javax.swing.AbstractListModel.fireIntervalRemoved(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeAllElements(Unknown Source)
at javax.swing.JComboBox.removeAllItems(Unknown Source)
at es.mycompany.MyView.ThreeCascadeJComboBox.loadCombo2(ThreeCascadeJComboBox.java:63)
at es.mycompany.MyView.ThreeCascadeJComboBox.access$1(ThreeCascadeJComboBox.java:62)
at es.mycompany.MyView.ThreeCascadeJComboBox$1.actionPerformed(ThreeCascadeJComboBox.java:30)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$1.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$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(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.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)
The exception is thrown because at that point seleccionEnCombo2 is null.
You could add a check for null in the combo2 ActionListener and it will work fine:
if (combo2.getSelectedItem() != null) {
loadCombo3((String) combo2.getSelectedItem());
}
The problem is that the ActionListener for combo1 is triggering an ActionEvent for combo2 which will not have any selected item (as it is empty). You could add a check:
if (combo2.getSelectedItem() != null) {
loadCombo3((String) combo2.getSelectedItem());
}
As the other posts have mentioned, the selected value for the combo is null in some cases. This is occurring because you probably do not realize the ActionListener for combo2 is getting called twice. The first time it gets called is during the call to removeAllElements. This is where the null value is coming from. The second time is what you are assuming in your code to be the only call--this is in response to both population of the combo box as well as user interaction.
When you load the second combo box, that fires the action event for that box (because an action has taken place [actions are not limited to selection]. The 2nd combo box's actionPerformed attempts to load the 3rd combo box based on the 2nd combo box's selection, and there isn't any. That's your null pointer, the non-existent selection from the second combo box.
Update: If I move the code to be within the mouseclick event (i.e. instead of calling initMarksScreen() I just put the code directly in) it works as expected. So my problem is calling the code in its own method. Does this mean if I want to perform the same steps at another point or on a different button that I have to have the code directly in there instead of in a method I can call?
I am fairly new to Java and trying to create a button that adds a JScrollPane which contains a JTable.
It is called by:
public void mouseClicked(java.awt.event.MouseEvent evt) {
initMarksScreen();
}
The code is:
public final void initMarksScreen() {
String[] columnNames = {"Student ID",
"Last Name",
"Firstname",
"Status",
"Degree",
"Candidate No.",
"Stage",
"Year",
"Code",
"Title",
"Grade Mode",
"Mark",
"Result"};
Object[][] data = {
{"100123456", "Cooper","Sheldon", "Signed Up", "BSc Physics","1201234","1","12","PH1001","Blackholes and Revelations","D",new Integer(99),"P"},
{"100123456", "Cooper","Sheldon", "Signed Up", "BSc Physics","1201234","1","12","PH1025","Astrophysics","D",new Integer(95),"P"}
};
JTable tMarks = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(tMarks);
tMarks.setFillsViewportHeight(true);
panelCentral.add(scrollPane); --!!ERROR AT THIS LINE!!
panelCentral.revalidate();
}
The panel is declared as:
private static final Container panelCentral = null;
As I'm quite new to Java I imagine there is an easy fix but if I need to add an SSCCE.
Everything displays fine until I click the button then the error I get is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI.mainScreen.initMarksScreen(mainScreen.java:312)
at GUI.mainScreen$2.mouseClicked(mainScreen.java:183)
at java.awt.AWTEventMulticaster.mouseClicked(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)
if panelCentral is JPanel and its not initialized, initialize before add
panelCentral = new JPanel();
panelCentral.add(scrollPane);