I am getting .ArrayIndexOutOfBoundsException when i try to delete a row from my JTable.
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Vector.java:734)
at java.util.Vector.elementAt(Vector.java:477)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at Test$1.valueChanged(Test.java:34)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)
at javax.swing.DefaultListSelectionModel.removeIndexInterval(DefaultListSelectionModel.java:677)
at javax.swing.JTable.tableRowsDeleted(JTable.java:4509)
at javax.swing.JTable.tableChanged(JTable.java:4412)
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:261)
at javax.swing.table.DefaultTableModel.removeRow(DefaultTableModel.java:463)
at Test$2.actionPerformed(Test.java:39)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
First, I select the row I want to delete and then when I fire the action the delete button it freezes a bit and gives me exception.
Here is my complete code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class Test extends JFrame{
private static JTable table;
private DefaultTableModel model = new DefaultTableModel();;
private JButton del = new JButton("DELETE");
public Test(){
JPanel pan= new JPanel();
JTextField numeField = new JTextField(30);
model.addColumn("Id");
model.addColumn("Nume");
table = new JTable(model);
JScrollPane pen = new JScrollPane(table);
del.setEnabled(false);
pan.add(pen);
pan.add(numeField);
pan.add(del);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
del.setEnabled(true);
numeField.setText(model.getValueAt(table.getSelectedRow(), 1).toString());
}
});
del.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.removeRow(table.getSelectedRow());
}
});
Object[] row = {"1","NAME"};
model.addRow(row);
add(pan);
setExtendedState(MAXIMIZED_BOTH);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) throws IOException {
new Test();
}
}
Full stack trace :
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Unknown Source)
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
at Test$1.valueChanged(Test.java:34)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
at javax.swing.DefaultListSelectionModel.removeIndexInterval(Unknown Source)
at javax.swing.JTable.tableRowsDeleted(Unknown Source)
at javax.swing.JTable.tableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(Unknown Source)
at javax.swing.table.DefaultTableModel.removeRow(Unknown Source)
at Test$2.actionPerformed(Test.java:39)
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)
The problem is not in the ActionListener, the problem is in the ListSelectionListener; when you delete the row, the row that you're deleting no longer exists; if you want to change the selected row, you have to use the new selected row from the event; probably by using getFirstIndex().
You also need to ensure that the row exists, so that when you delete a row, there's still a valid value to select.
In other words, change your ListSelectionListener to this:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
int firstIndex = e.getFirstIndex();
if(firstIndex >= 0 && firstIndex < model.getRowCount()) {
del.setEnabled(true);
numeField.setText(model.getValueAt(firstIndex, 1).toString());
} else {
del.setEnabled(false);
}
}
});
Related
I'm basically building a simple GUI for a simple baking program.
The problem is that after creating a model for JTable, adding a row of data
model.addRow(new String[] {"data", "data","data", "data"});
does not work inside of an actionlistener:
public void actionPerformed(ActionEvent event) {
String buttonText = event.getActionCommand();
if (buttonText.equals("Create Savings Account")) {
createSavingsAccount();
public void createCreditAccount() {
logic.createCreditAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
If I try to create an account I get this message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createSavingsAccount(GUImain.java:145)
at svimag6.GUImain.actionPerformed(GUImain.java:124)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createSavingsAccount(GUImain.java:145)
at svimag6.GUImain.actionPerformed(GUImain.java:124)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createCreditAccount(GUImain.java:140)
at svimag6.GUImain.actionPerformed(GUImain.java:128)
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)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at svimag6.GUImain.createCreditAccount(GUImain.java:140)
at svimag6.GUImain.actionPerformed(GUImain.java:128)
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)
However, if I hardcode the adding of new rows into the table, (in the constructor) it works. But I can't add data dynamically.
Here's the code:
package gui;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.awt.*;
//YOU NEED TO ADD A FIELD in the GUI FOR NAME, LASTNAME AND PNR
public class GUImain extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private BankLogic logic;
private JList<Object> customerList;
private JTable accountTable;
private JTable transactionTable;
private JTextField nameField;
private JTextField lastnameField;
private JTextField pNrField;
private DefaultTableModel model;
private DefaultTableModel model1;
private JButton addButton = new JButton("Add Customer");
private JButton showButton = new JButton("Show");
private JButton clearButton = new JButton("Rensa");
private JButton createSavingsAccountButton = new JButton("Create Savings Account");
private JButton createCreditAccountButton = new JButton("Create Credit Account");
private JButton deleteAccountButton = new JButton("Delete Account");
private JButton withdrawButton = new JButton("Withdraw");
private JButton depositButton = new JButton("Deposit");
String[] accountColumns = { "ID", "Account Type", "Balance", "Interest" };
String[] transactionColumns = { "Date", "Time", "Amount", "Balance" };
String testdata[][] = { { "101", "Amit", "670000" }, { "102", "Jai", "780000" }, { "101", "Sachin", "700000" } };
public GUImain() {
initiateInstanceVariables();
buildFrame();
}
private void initiateInstanceVariables() {
logic = new BankLogic();
customerList = new JList<Object>();
accountTable = new JTable();
DefaultTableModel model = new DefaultTableModel(0, 0);
model.setColumnIdentifiers(accountColumns);
accountTable.setModel(model);
transactionTable = new JTable();
DefaultTableModel model1 = new DefaultTableModel(0, 0);
model1.setColumnIdentifiers(transactionColumns);
transactionTable.setModel(model1);
model.addRow(new String[] {"data", "data","data", "data"});
nameField = new JTextField();
lastnameField = new JTextField();
pNrField = new JTextField();
nameField.setBorder(BorderFactory.createTitledBorder("Name"));
lastnameField.setBorder(BorderFactory.createTitledBorder("Lastname"));
pNrField.setBorder(BorderFactory.createTitledBorder("pNr"));
}
private void buildFrame() {
setTitle("Bank");
setSize(300, 250);
setLayout(new GridLayout(1, 2));
JPanel bankpanel = new JPanel(new GridLayout(5, 1));
bankpanel.add(nameField);
bankpanel.add(lastnameField);
bankpanel.add(pNrField);
bankpanel.add(addButton);
bankpanel.add(showButton);
bankpanel.add(clearButton);
bankpanel.add(createSavingsAccountButton);
bankpanel.add(createCreditAccountButton);
createSavingsAccountButton.setVisible(false);
createCreditAccountButton.setVisible(false);
addButton.addActionListener(this);
showButton.addActionListener(this);
clearButton.addActionListener(this);
createSavingsAccountButton.addActionListener(this);
createCreditAccountButton.addActionListener(this);
deleteAccountButton.addActionListener(this);
// // ACCOUNT TABLE
accountTable.setCellSelectionEnabled(true);
ListSelectionModel select = accountTable.getSelectionModel();
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// // ACCOUNT TABLE
add(bankpanel);
add(customerList);
add(new JScrollPane(accountTable), BorderLayout.CENTER);
add(new JScrollPane(transactionTable), BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
// UI LOGIC. This activated the functions below.
public void actionPerformed(ActionEvent event) {
String buttonText = event.getActionCommand();
if (buttonText.equals("Add Customer")) {
addCustomer();
showAccountButtons();
}
if (buttonText.equals("Show")) {
showSelected();
}
if (buttonText.equals("Clear")) {
clear();
}
if (buttonText.equals("Create Savings Account")) {
createSavingsAccount();
}
if (buttonText.equals("Create Credit Account")) {
createCreditAccount();
}
}
private void addCustomer() {
logic.createCustomer(nameField.getText(), lastnameField.getText(), pNrField.getText());
customerList.setListData(logic.getAllCustomers().toArray());
clear();
}
public void createCreditAccount() {
logic.createCreditAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
public void createSavingsAccount() {
logic.createSavingsAccount(pNrField.getText());
model.addRow(new String[] {"data", "data","data", "data"});
}
private void showSelected() {
int position = customerList.getSelectedIndex();
if (position > -1) {
nameField.setText(logic.getNameForPersonAt(position));
lastnameField.setText(logic.getLastNameForPersonAt(position));
pNrField.setText(logic.getpNrAt(position));
} else {
JOptionPane.showMessageDialog(null, "You need a person in the list!");
}
}
private void showAccountButtons() {
createSavingsAccountButton.setVisible(true);
createCreditAccountButton.setVisible(true);
}
private void clear() {
nameField.setText("");
lastnameField.setText("");
pNrField.setText("");
}
}
You have "shadowed variables".
You try to define instance variables but they are null:
private DefaultTableModel model;
private DefaultTableModel model1;
And then you create a local variable which is not null
DefaultTableModel model = new DefaultTableModel(0, 0);
...
DefaultTableModel model1 = new DefaultTableModel(0, 0);
The ActionListener can only access the instance variable but it is null so you get a NPE.
Get rid of the local variables:
model = new DefaultTableModel(0, 0);
...
model1 = new DefaultTableModel(0, 0);
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'm just starting out with swing, but I've been stuck on this issue for about a week and I've tried everything I can think. I'm trying to update the table model as the result of a click on a column header and getting an ArrayIndexOutOfBoundsException.
I've simplified the code here, but can someone please explain why this:
package gradebook.model.courseTable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class CourseTableTest extends JTable {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new JFrame();
frame.add(new JScrollPane(new CourseTable()));
frame.setVisible(true);
frame.pack();
frame.setLocationRelativeTo(null);
}
});
}
public CourseTableTest(){
super(3, 3);
this.tableHeader.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
setModel(new DefaultTableModel(3, 3));
}
});
}
}
throws this when clicked?:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Unknown Source)
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
at javax.swing.JTable.getCellRenderer(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintDraggedArea(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.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.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$700(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Unknown Source)
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
at javax.swing.JTable.getCellRenderer(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintDraggedArea(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.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.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$700(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Edit
Some of you have asked why I would change the model during a click of the column header. In my application, the table columns represent a school assignment. When the header is clicked it opens a dialog box that allows the user to either modify or delete the assignment. If the user clicks delete I would like to remove the column from the table. But any time I try to change the table structure within the click handler I get this error.
The MouseListener must be doing some processing and doesn't like you changing the data in the middle of the processing.
Try:
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
setModel(new DefaultTableModel(3, 3));
}
});
This will let the MouseListener code finish executing before you change the model.
The real question is why would you change the model when you click on the header?
Edit:
As noted by MadProgrammer the first suggestion doesn't work.
As another hack if you are just trying to clear the data in the model you can use:
#Override
public void mousePressed(MouseEvent e)
{
model.setRowCount(0);
model.setRowCount(3);
}
If you want a table with a completely different structure then I would suggest you do something like:
#Override
public void mousePressed(MouseEvent e)
{
scrollPane.setViewportView( new JTable(4, 4) );
}
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 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.