I am working on a school project and am trying to get the position and values of a selected item in a list. When attempting to do so, I get the error 'Cannot invoke "javax.swing.JList.getSelectedIndex()" because "this.newList" is null'. I'm pretty sure this has to do with the cell renderer not actually adding the item to the list, but am unsure how to fix it.
class OrderHandlePanel extends JPanel implements ActionListener {
private DefaultListModel newModel, cancelModel;
private JButton right, left;
private JList newList, cancelledList;
OrderHandlePanel() {
newModel = new DefaultListModel();
setLayout(new GridLayout(1,3));
JPanel newOrders = new JPanel(new GridLayout(3,1));
JLabel newOrder = new JLabel("New Order");
JLabel orderAmount = new JLabel("Ordered Amt: ");
JList newList = new JList(newModel);
newList.setCellRenderer(new listCellRenderer());
JScrollPane newScrollPane = new JScrollPane(newList);
JPanel buttons = new JPanel();
JButton right = new JButton("=>");
JButton left = new JButton("<=");
newOrders.add(newOrder);
newOrders.add(newScrollPane);
newOrders.add(orderAmount);
right.addActionListener(this);
left.addActionListener(this);
right.setActionCommand("moveRight");
left.setActionCommand("moveLeft");
buttons.add(right);
buttons.add(left);
add(newOrders);
add(buttons);
}
private class listCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Order order = (Order) value;
String orderText = "<html>Name: " order.getName()
"<br/>Quantity: " order.getQuantity()
"<br/>Price" order.getPrice()
"<br/>Total Cost: " order.getTotalCost()
"<br/> ";
setText(orderText);
return this;
}
}
public void update() {
newModel.clear();
cancelModel.clear();
for (byte i = 0; i < OrderContainer.getPosition(); i ) {
Order order = OrderContainer.getOrder(i);
if (order.getType().equals("New"))
newModel.addElement(order);
else if (order.getType().equals("Cancelled"))
cancelModel.addElement(order);
}
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
switch (actionCommand) {
case "moveRight":
int newIndex = newList.getSelectedIndex();
System.out.println(newList.getSelectedValue());
break;
case "moveLeft":
int cancelIndex = cancelledList.getSelectedIndex();
System.out.println(cancelledList.getSelectedValue());
break;
}
}
}
CodePudding user response:
Remove the Jlist from JList newList. You're defining a local variable when you want to set the class variable to that new object.
Thus
JList newList = new JList(newModel);
Will become
newList = new JList(newModel);