|
| 1 | +package club.bytecode.the.jda.gui.components; |
| 2 | + |
| 3 | +import javax.swing.*; |
| 4 | +import javax.swing.border.Border; |
| 5 | +import javax.swing.border.EmptyBorder; |
| 6 | +import java.awt.*; |
| 7 | +import java.awt.event.MouseAdapter; |
| 8 | +import java.awt.event.MouseEvent; |
| 9 | + |
| 10 | +/** |
| 11 | + * Copied from somewhere online. |
| 12 | + */ |
| 13 | +public class CheckboxList extends JList { |
| 14 | + protected static Border noFocusBorder = |
| 15 | + new EmptyBorder(1, 1, 1, 1); |
| 16 | + |
| 17 | + public CheckboxList() { |
| 18 | + setCellRenderer(new CellRenderer()); |
| 19 | + |
| 20 | + addMouseListener(new MouseAdapter() { |
| 21 | + public void mousePressed(MouseEvent e) { |
| 22 | + int index = locationToIndex(e.getPoint()); |
| 23 | + |
| 24 | + if (index != -1) { |
| 25 | + JCheckBox checkbox = (JCheckBox) |
| 26 | + getModel().getElementAt(index); |
| 27 | + checkbox.setSelected( |
| 28 | + !checkbox.isSelected()); |
| 29 | + repaint(); |
| 30 | + } |
| 31 | + } |
| 32 | + }); |
| 33 | + setSelectionMode(ListSelectionModel.SINGLE_SELECTION); |
| 34 | + } |
| 35 | + |
| 36 | + protected class CellRenderer implements ListCellRenderer { |
| 37 | + public Component getListCellRendererComponent( |
| 38 | + JList list, Object value, int index, |
| 39 | + boolean isSelected, boolean cellHasFocus) { |
| 40 | + JCheckBox checkbox = (JCheckBox) value; |
| 41 | + checkbox.setBackground(isSelected ? |
| 42 | + getSelectionBackground() : getBackground()); |
| 43 | + checkbox.setForeground(isSelected ? |
| 44 | + getSelectionForeground() : getForeground()); |
| 45 | + checkbox.setEnabled(isEnabled()); |
| 46 | + checkbox.setFont(getFont()); |
| 47 | + checkbox.setFocusPainted(false); |
| 48 | + checkbox.setBorderPainted(true); |
| 49 | + checkbox.setBorder(isSelected ? |
| 50 | + UIManager.getBorder( |
| 51 | + "List.focusCellHighlightBorder") : noFocusBorder); |
| 52 | + return checkbox; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public void addCheckbox(JCheckBox checkBox) { |
| 57 | + ListModel currentList = this.getModel(); |
| 58 | + JCheckBox[] newList = new JCheckBox[currentList.getSize() + 1]; |
| 59 | + for (int i = 0; i < currentList.getSize(); i++) { |
| 60 | + newList[i] = (JCheckBox) currentList.getElementAt(i); |
| 61 | + } |
| 62 | + newList[newList.length - 1] = checkBox; |
| 63 | + setListData(newList); |
| 64 | + } |
| 65 | +} |
0 commit comments