I was trying to troubleshoot the code that why JList prints same values x2 times on console, but on GUI it shows only x1 time. I need ID on backend to do more functions, but it comes x2 time. The values are retrieving from DB.
JList Initialization & calling: -
CustomListModel listModel;
listModel = new CustomListModel(getListOfRoutes());
routeList = new JList<tbl_bom_route>(listModel);
ListSelectionListener myListener = new listListeners();
routeList.addListSelectionListener(myListener);
routeList.setCellRenderer(new routeListCellRenderer());
scrollPaneList.setViewportView(routeList);
class CustomListModel extends AbstractListModel<tbl_bom_route> {
private static final long serialVersionUID = 1L;
private ArrayList<tbl_bom_route> items;
public CustomListModel(ArrayList<tbl_bom_route> items) {
this.items = items;
}
@Override
public int getSize() {
return items.size();
}
@Override
public tbl_bom_route getElementAt(int index) {
return items.get(index);
}
}
private ArrayList<tbl_bom_route> getListOfRoutes() {
ArrayList<tbl_bom_route> itemsList = new ArrayList<>();
try {
itemsList = daoBomRouteObject.getAllListOfRoutes();
} catch (Exception e) {
e.printStackTrace();
}
return itemsList;
}
class routeListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof tbl_bom_route) {
tbl_bom_route item = (tbl_bom_route) value;
setText(item.getRouteName());
}
return this;
}
}
Console Output: -
- Route00476R1020ARDWN_No 4 Draw Bench
- ID186
- Route00476R1020ARDWN_No 4 Draw Bench
- ID186
Updated: -
private class RouteListListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int selectedIndex = routeList.getSelectedIndex();
if (selectedIndex != -1) {
tbl_bom_route selectedListValue = routeList.getSelectedValue();
SANDBOX_GROUP_ID = selectedListValue.getRouteGroupID();
}
}
}
}