Google Tag Manager

2017/04/28

aterai

Disable any items in JList

Code

Set disableIndexSet = new HashSet<>();

JList list = new JList<>(model);
list.setCellRenderer(new DefaultListCellRenderer() {
  @Override public Component getListCellRendererComponent(
      JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Component c;
    if (disableIndexSet.contains(index)) {
      c = super.getListCellRendererComponent(
          list, value, index, false, false);
      c.setEnabled(false);
    } else {
      c = super.getListCellRendererComponent(
          list, value, index, isSelected, cellHasFocus);
    }
    return c;
  }
});

initDisableIndex(disableIndexSet);
ActionMap am = list.getActionMap();
am.put("selectNextRow", new AbstractAction() {
  @Override public void actionPerformed(ActionEvent e) {
    int index = list.getSelectedIndex();
    for (int i = index + 1; i < list.getModel().getSize(); i++) {
      if (!disableIndexSet.contains(i)) {
        list.setSelectedIndex(i);
        break;
      }
    }
  }
});
am.put("selectPreviousRow", new AbstractAction() {
  @Override public void actionPerformed(ActionEvent e) {
    int index = list.getSelectedIndex();
    for (int i = index - 1; i >= 0; i--) {
      if (!disableIndexSet.contains(i)) {
        list.setSelectedIndex(i);
        break;
      }
    }
  }
});
//...
protected final void initDisableIndex(Set set) {
  set.clear();
  try {
    set.addAll(Arrays.stream(field.getText().split(","))
      .map(String::trim).filter(s -> !s.isEmpty())
      .map(Integer::valueOf).collect(Collectors.toSet()));
  } catch (NumberFormatException ex) {
    Toolkit.getDefaultToolkit().beep();
    JOptionPane.showMessageDialog(
        field, "invalid value.\n" + ex.getMessage(),
        "Error", JOptionPane.ERROR_MESSAGE);
  }
}

References

No comments:

Post a Comment