java.util.ConcurrentModificationException when trying to use setSelectionPath in JTree - java

I have been trying after clicking a button to set the selection path in a JTree. The code sets the path correctly, but each time I click it I get a
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at com.treeview.main.iui.SelectableTree.actionPerformed(SelectableTree.java:225)
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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(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.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
And I have no idea what causes it. I read that it happens when you multiple threads try to access the same resource but I can't see the problem.
Here is the code I'm trying to run:
/**
* Handles the event when a button is clicked.
*/
#Override
public void actionPerformed(ActionEvent arg0) {
// If button "Force adaptation is clicked"
if (arg0.getSource() == forceAdapt) {
// ModelContainer.getInstance().getAdaptedTree().removeAllChildren();
// tree.setModel(new DefaultTreeModel(ModelContainer.getInstance()
// .getAdaptedTree()));
// treeModel.reload();
} else if (arg0.getSource() == showAll) {
expandFullTree(tree, ModelContainer.getInstance().getAdaptedTree());
// If button "Show All" is clicked
// tree.setModel(new DefaultTreeModel(ModelContainer.getInstance()
// .getFullTree()));
// treeModel.reload();
}
// In case recommendation button was clicked.
for (JButton button : recommendButtons) {
if (arg0.getSource() == button) {
TreeHandler th = new TreeHandler();
TreeItem node = th.getNodeByName(ModelContainer.getInstance()
.getAdaptedTree(), button.getText());
tree.setSelectionPath(new TreePath(node.getPath()));
}
}
}
Those two methods populate the ArrayList with buttons:
/**
* Handles tree selection event.
*/
public void valueChanged(TreeSelectionEvent event) {
selectedNode = (TreeItem) tree.getLastSelectedPathComponent();
// If there's predecessors.
if (!lastSelectedNode.getId().equals("-1")) {
// Display selection in bottom bar.
currentSelectionField.setText("Current Selection: "
+ selectedNode.toString() + " Prev Node : "
+ lastSelectedNode.toString());
/*
* Increase the clicks in the transition matrix and updates the
* probability transition matrix.
*/
ModelContainer.getInstance().increaseClicksOnElement(
Integer.parseInt(selectedNode.getId()) - 1,
Integer.parseInt(lastSelectedNode.getId()) - 1);
// Recalculate the Markovian matrix.
ModelContainer.getInstance().recalculateMarkovian();
// Display recommendations
displayRecommendations(ModelContainer.getInstance()
.getNextMarkovians(
(Integer.parseInt(selectedNode.getId()) - 1) + "",
5));
}
lastSelectedNode = selectedNode;
}
public void displayRecommendations(ArrayList<TreeItem> recommend) {
recommendation.removeAll();
int place = 2;
for (TreeItem treeItem : recommend) {
JButton aButton = new JButton(treeItem.toString());
aButton.setPreferredSize(new Dimension(recommendation.getWidth(),
recommendation.getHeight() / place));
aButton.addActionListener(this);
recommendButtons.add(aButton);
recommendation.add(aButton);
System.out.println(aButton.getText());
place = place * 2;
}
recommendation.revalidate();
recommendation.repaint();
}

Related

Cannot call constructor component from ActionPerformed

When executing bottomLabel.setVisible(true); I get an unresolved compilation problem:
The type Assignment1 must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
It is like that I should create a new variable as it is not readable from the constructor. Where is my mistake? Here is the code simplified as much as possible:
public class Assignment1 extends JFrame implements ActionListener{
//declare variables
int x= 101;
int low = 0;
int high = 100;
int guess = (high + low) / 2;
int counter = 0;
private static final long serialVersionUID = 1L;
//main method
//...some code...
//constructor
public Assignment1(){
//...some code...
//declare buttons
JButton correct = new JButton("correct!");
//add buttons
//...some code...
//declare TextField and Labels
JTextField numberTextField = new JTextField(20);
JLabel topLabel = new JLabel("T");
JLabel bottomLabel = new JLabel("G");
//add TextField and Labels and position them on the layout
//...some code...
bottomLabel.setBounds(110, 300, 400, 20);
add(bottomLabel);
bottomLabel.setVisible(false);
//add ActionListener to each button
//...some code...
correct.addActionListener(this);
}
#Override
//define ActionPerformed when an Event is parsed
public void actionPerformed(ActionEvent e) {
String buttonClicked = e.getActionCommand();
if(buttonClicked.equals("Yes, correct!")){
System.out.println("correct");
bottomLabel.setVisible(true);
}
}
}
Here's the full stack trace:
at Assignment1.Assignment1.actionPerformed(Assignment1.java:12)
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)
bottomLabel is visible only inside the constructor, as it's not declared at class-level.
Declare it at class-level (as you did with x, low, high, etc) to make it work:
public class Assignment1 extends JFrame implements ActionListener {
// declare variables
int x = 101;
int low = 0;
int high = 100;
int guess = (high + low) / 2;
int counter = 0;
JLabel bottomLabel; // <==
public Assignment1() {
// [...] other assignments
bottomLabel = new JLabel("Game Over, your number is NN, i got it in N times. Wanna play again?");
// [...] rest of class

Getting Checked Exception while running a SQL Program

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.PrintWriter;
import java.sql.*;
import java.net.*;
public class connection {
JTextField textfeild;
JButton button;
String text;
Socket sock;
PrintWriter writer;
JButton button1;
public static void main(String[] args) {
connection user1 = new connection();
user1.go();
}//main method close
public void go() {
JFrame frame12 = new JFrame();
JPanel centerpanel12 = new JPanel();
centerpanel12.setLayout(new BoxLayout(centerpanel12, BoxLayout.Y_AXIS));
textfeild = new JTextField(20);
centerpanel12.add(textfeild);
//textfeild.addActionListener(new textfeildlitner());
frame12.add(centerpanel12);
button = new JButton("Click Me");
centerpanel12.add(button);
button.addActionListener(new buttonlitner());
button1 = new JButton("DataDisplay");
centerpanel12.add(button1);
button1.addActionListener(new buttonlitner1());
frame12.getContentPane().add(BorderLayout.CENTER, centerpanel12);
frame12.pack();
frame12.setVisible(true);
frame12.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//go method close
/*class textfeildlitner implements ActionListener{
public void actionPerformed(ActionEvent ev){
}
}//inner class textfeildlitner close*/
class buttonlitner implements ActionListener {
public void actionPerformed(ActionEvent ev) {
button.setText("I AM Clicked");
String name = textfeild.getText();
System.out.println(name);
textfeild.setText("");
textfeild.requestFocus();
}//method close
}//inner class close
class buttonlitner1 implements ActionListener {
void connection() {
try {
String user = "SQlUI";
String pass = "123456";
String db = "jdbc:sqlserver://localhost:1234;" + ";databaseName=SQlUI";
Class.forName("com.microsoft.sqlserver.jdbc");
Connection con = DriverManager.getConnection(db, user, pass);
Statement s1 = con.createStatement();
ResultSet r1 = s1.executeQuery("select * from Table_1");
String[] result = new String[20];
if (r1 != null) {
while (r1.next()) {
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result.length; j++) {
result[j] = r1.getString(i);
System.out.println(result[j]);
}//for j
}//for i
}//if
}//try
} catch (Exception ex) {
ex.printStackTrace();
}//catch
}//connection()
public void actionPerformed(ActionEvent ev) {
button1.setText("Processing");
new buttonlitner1().connection();
}//method close
}//inner class close
}// outer class close
While running this code i am getting following exception----
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at connection$buttonlitner1.connection(connection.java:66)
at connection$buttonlitner1.actionPerformed(connection.java:89)
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)
Don't know why its happening. I have added the sqlserver.jar in eclipse external library.
The connection name
String db="jdbc:sqlserver://localhost:1234;"+";databaseName=SQlUI";
is correct. i am attaching the screenshot of the sqlserver.jar which i have added to external library.
The driver class is com.microsoft.sqlserver.jdbc.SQLServerDriver and not com.microsoft.sqlserver.jdbc. Try to use:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

How to add picture into JButton using JFilechooser

JFileChooser won't work I got an error on line:
btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
Please help me , I'm a beginner. It gives me this error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at RecordManagementSystem.addRecord$1.actionPerformed(addRecord.java:185)
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$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(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.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)
Code:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
File file = fc.getSelectedFile();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
try {
btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
You're getting the file from the JFileChooser before it has been selected, and so fc.getSelectedFile() will return null.
Solution: get the File in the if block after the JFileChooser has been displayed.
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fc.getSelectedFile(); // **** line added ****
btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
}
as an aside, I like to avoid over-compression of my code to ease my finding errors if any occur. So instead I'd do something like so:
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fc.getSelectedFile();
Image image = ImageIO.read(file);
Icon icon = new ImageIcon(image);
btnNewButton.setIcon(icon);
} catch (IOException e) {
// log error
}
}

Swing Jlist with searchButton NullPointerException

It is an application that, among other things, a list of personalities. Once launched, the data of a personality are displayed on the left side, there are two lists: one comprising all categories of personalities and another incorporating all the names in this list.The user select a row in each JList, he clicks on the button "search" ... The code then makes a call to findByCriteria .... But here, I have a NullPointerException ... After some research, I realized that this is because my lists are poorly or not initialized ... I look at my code but I do not understand how it is because the call to the methods that must be initialized before the call is to listener on my Button ... The strangest thing is that when I run the application, the lists are filled. I used the MVC pattern with the method update...
Here is the code from my view:
modelListCat = new DefaultListModel();
listCategories = new JList();
listCategories.setName("category");
scrollPaneCat.setViewportView(listCategories);
listCategories.setPreferredSize(new Dimension(0, 90));
listCategories.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listCategories.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listCategories.setVisibleRowCount(-1);
PersonalitiesController.getInstance().setJListForCategories(personalitiesListCat, listCategories, modelListCat);
and a little further:
modelListNames = new DefaultListModel();
listNames = new JList();
listNames.setName("name");
scrollPaneN.setViewportView(listNames);
listNames.setPreferredSize(new Dimension(0, 110));
listNames.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listNames.setSelectedIndex(0);
listNames.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listNames.setVisibleRowCount(-1);
PersonalitiesController.getInstance().setJListForNames(personalitiesListNames, listNames, modelListNames);
btnSearch = new JButton("Rechercher");
btnSearch.setActionCommand("search");
btnSearch.setName("search");
GridBagConstraints gbc_btnSearch = new GridBagConstraints();
gbc_btnSearch.insets = new Insets(0, 0, 5, 5);
gbc_btnSearch.gridx = 0;
gbc_btnSearch.gridy = 4;
westPanel.add(btnSearch, gbc_btnSearch);
this.btnSearch.addActionListener(PersonalitiesController.getInstance());
The method code to initialize the JList class (this is the same for the JList names) in PersonalitiesController:
public void setJListForCategories(List<TPersonalities> personalitiesListCat, JList listCategories, DefaultListModel modelListCat){
modelListCat = new DefaultListModel();
modelListCat.addElement("Toute");
for(int i = 0; i < personalitiesListCat.size(); i++){
modelListCat.addElement(personalitiesListCat.get(i));
}
listCategories.setModel(modelListCat);
setListNames(listCategories);
}
Here is the code of ActionPerformed in PersonalitiesController:
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
//JButton button = (JButton)ev.getSource();
if("search".equals(ev.getActionCommand())){
DefaultListModel modelListCat = (DefaultListModel)listCategories.getModel();
DefaultListModel modelListNames = (DefaultListModel)listNames.getModel();
int selected = this.listCategories.getSelectedIndex( );
if(selected != -1){
for(int i = 0; i != listCategories.getSelectedIndex(); i++){
this.category = (String)modelListCat.getElementAt(selected);
}
}
int selected2 = this.listNames.getSelectedIndex( );
if(selected2 != -1){
for(int j =0; j != listNames.getSelectedIndex(); j++){
this.name = (String)modelListNames.getElementAt(selected2);
}
}
if(category.equalsIgnoreCase("Toute") && category == ""){
if(!name.equalsIgnoreCase("Tout") && name != ""){
model.findPersonalitiesByCriteria(name, null, null);
}
}else{
if(!name.equalsIgnoreCase("Tout") && name != ""){
model.findPersonalitiesByCriteria(name, category, null);
}else{
model.findPersonalitiesByCriteria(null, category, null);
}
}
}
}
And here is the error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.cultureAtBrussels.controller.PersonalitiesController.actionPerformed(PersonalitiesController.java:54)
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$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
the ligne 54 is:
DefaultListModel modelListCat = (DefaultListModel)listCategories.getModel();

Exception on deleting JList items on keypress

I'm getting a NullPointerException in my JList, but the source of the exception seems to be the Swing event handling code. The JList has a key listener which will delete the selected item when the Delete key is pressed. The exception is only thrown on the second and all subsequent deletions from the list. Any ideas on how to fix it?
Sample code to reproduce the problem and the exception that is produced are included below:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
public class Sample {
public static void main(String[] args) {
final JFrame frame = new JFrame();
final Vector<String> list = new Vector<String>();
for (int i = 0; i < 5; ++i) {
list.add("String " + i);
}
final JList listView = new JList(list);
listView.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
list.remove(listView.getSelectedIndex());
listView.updateUI();
}
}
#Override
public void keyReleased(KeyEvent e) { }
#Override
public void keyTyped(KeyEvent e) { }
});
frame.add(listView);
frame.pack();
frame.setVisible(true);
}
}
Here's the exception being thrown:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.plaf.basic.BasicListUI$Handler.isNavigationKey(Unknown Source)
at javax.swing.plaf.basic.BasicListUI$Handler.keyPressed(Unknown Source)
at java.awt.AWTEventMulticaster.keyPressed(Unknown Source)
at java.awt.Component.processKeyEvent(Unknown Source)
at javax.swing.JComponent.processKeyEvent(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.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(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.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 in this line:
listView.updateUI();
Calling this method causes the current UI to be uninstalled from the JList, yet it is still being used to process events. This results in the NullPointerException you see. This isn't the method you want to call.
Try
listView.revalidate();
instead to cause the component to re-layout or perhaps just repaint() to get it to repaint.
list.registerKeyboardAction(this,
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), JComponent.WHEN_FOCUSED);
EDIT: remove unrelated code
Instead of the updateUI() you should call the revalidate() and repaint() method. And probably a check if the element in the list really exists wouldn't be a bad idea.
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A) {
if(list.get(listView.getSelectedIndex()) != null) {
list.remove(listView.getSelectedIndex());
listView.revalidate();
listView.repaint();
}
}
}

Categories