Google Tag Manager

Showing posts with label JList. Show all posts
Showing posts with label JList. Show all posts

2018/06/29

aterai

Move items by copying and pasting between JLists

Code

class ListPopupMenu extends JPopupMenu {
  private final JMenuItem cutItem;
  private final JMenuItem copyItem;
  protected ListPopupMenu(JList list) {
    super();
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    TransferHandler handler = list.getTransferHandler();
    cutItem = add("cut");
    cutItem.addActionListener(e -> {
      handler.exportToClipboard(list, clipboard, TransferHandler.MOVE);
    });
    copyItem = add("copy");
    copyItem.addActionListener(e -> {
      handler.exportToClipboard(list, clipboard, TransferHandler.COPY);
    });
    add("paste").addActionListener(e -> {
      handler.importData(list, clipboard.getContents(null));
    });
    addSeparator();
    add("clearSelection").addActionListener(e -> list.clearSelection());
  }
  @Override public void show(Component c, int x, int y) {
    if (c instanceof JList) {
      boolean isSelected = !((JList) c).isSelectionEmpty();
      cutItem.setEnabled(isSelected);
      copyItem.setEnabled(isSelected);
      super.show(c, x, y);
    }
  }
}

// ...
private static int getIndex(TransferHandler.TransferSupport info) {
  JList target = (JList) info.getComponent();
  int index; // = dl.getIndex();
  if (info.isDrop()) { // Mouse Drag & Drop
    System.out.println("Mouse Drag & Drop");
    TransferHandler.DropLocation tdl = info.getDropLocation();
    if (tdl instanceof JList.DropLocation) {
      index = ((JList.DropLocation) tdl).getIndex();
    } else {
      index = target.getSelectedIndex();
    }
  } else { // Keyboard Copy & Paste
    index = target.getSelectedIndex();
  }
  DefaultListModel listModel = (DefaultListModel) target.getModel();
  // boolean insert = dl.isInsert();
  int max = listModel.getSize();
  // int index = dl.getIndex();
  index = index < 0 ? max : index; // If it is out of range, it is appended to the end
  index = Math.min(index, max);
  return index;
}

References

2018/04/26

aterai

Move large numbers of items to another JList as fast as possible

Code

private static <E> void move1(JList<E> from, JList<E> to) {
  ListSelectionModel sm = from.getSelectionModel();
  int[] selectedIndices = from.getSelectedIndices();

  DefaultListModel<E> fromModel = (DefaultListModel<E>) from.getModel();
  DefaultListModel<E> toModel = (DefaultListModel<E>) to.getModel();
  List<E> unselectedValues = new ArrayList<>();
  for (int i = 0; i < fromModel.getSize(); i++) {
    if (!sm.isSelectedIndex(i)) {
      unselectedValues.add(fromModel.getElementAt(i));
    }
  }
  if (selectedIndices.length > 0) {
    for (int i: selectedIndices) {
      toModel.addElement(fromModel.get(i));
    }
    fromModel.clear();
    unselectedValues.forEach(fromModel::addElement);
  }
}

References

2018/03/29

aterai

Create Week Calendar in JList and display contribution activity heatmap

Code

JList< Contribution> weekList = new JList< Contribution>() {
  @Override public void updateUI() {
    setCellRenderer(null);
    super.updateUI();
    setLayoutOrientation(JList.VERTICAL_WRAP);
    setVisibleRowCount(DayOfWeek.values().length); // ensure 7 rows in the list
    setFixedCellWidth(size.width);
    setFixedCellHeight(size.height);
    setCellRenderer(new ContributionListRenderer());
    getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
  }
};
//...
private class ContributionListRenderer implements ListCellRenderer< Contribution> {
  private final Icon emptyIcon = new ColorIcon(Color.WHITE);
  private final ListCellRenderer< ? super Contribution> renderer
    = new DefaultListCellRenderer();
  @Override public Component getListCellRendererComponent(
      JList< ? extends Contribution> list, Contribution value, int index,
      boolean isSelected, boolean cellHasFocus) {
    JLabel l = (JLabel) renderer.getListCellRendererComponent(
        list, null, index, isSelected, cellHasFocus);
    if (value.date.isAfter(currentLocalDate)) {
      l.setIcon(emptyIcon);
      l.setToolTipText(null);
    } else {
      l.setIcon(activityIcons.get(value.activity));
      String actTxt = value.activity == 0 ? "No" : Objects.toString(value.activity);
      l.setToolTipText(actTxt + " contribution on " + value.date.toString());
    }
    return l;
  }
}

References

2018/02/26

aterai

Create a range selectable calendar with JList

Code

public final LocalDate realLocalDate = LocalDate.now();
public LocalDate currentLocalDate;
public final Dimension size = new Dimension(40, 26);

//...
JLabel yearMonthLabel = new JLabel("", SwingConstants.CENTER);
JList< LocalDate> monthList = new JList< LocalDate>(new CalendarViewListModel(realLocalDate)) {
  @Override public void updateUI() {
    setCellRenderer(null);
    super.updateUI();
    setLayoutOrientation(JList.HORIZONTAL_WRAP);
    setVisibleRowCount(CalendarViewListModel.ROW_COUNT); // ensure 6 rows in the list
    setFixedCellWidth(size.width);
    setFixedCellHeight(size.height);
    setCellRenderer(new CalendarListRenderer<>());
    getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
  }
};

monthList.getActionMap().put("selectNextIndex", new AbstractAction() {
  @Override public void actionPerformed(ActionEvent e) {
    int index = monthList.getLeadSelectionIndex();
    if (index < monthList.getModel().getSize() - 1) {
      monthList.setSelectedIndex(index + 1);
    } else {
      LocalDate d = monthList.getModel()
        .getElementAt(monthList.getModel().getSize() - 1)
        .plusDays(1);
      updateMonthView(currentLocalDate.plusMonths(1));
      monthList.setSelectedValue(d, false);
    }
  }
});
//...
class CalendarViewListModel extends AbstractListModel< LocalDate> {
  public static final int ROW_COUNT = 6;
  private final LocalDate startDate;
  private final WeekFields weekFields = WeekFields.of(Locale.getDefault());
  protected CalendarViewListModel(LocalDate date) {
    super();
    LocalDate firstDayOfMonth = YearMonth.from(date).atDay(1);
    int dowv = firstDayOfMonth.get(weekFields.dayOfWeek()) - 1;
    startDate = firstDayOfMonth.minusDays(dowv);
  }
  @Override public int getSize() {
    return DayOfWeek.values().length * ROW_COUNT;
  }
  @Override public LocalDate getElementAt(int index) {
    return startDate.plusDays(index);
  }
}

References

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

2016/12/27

aterai

Change the shape of JToolTip to balloon

Code

class BalloonToolTip extends JToolTip {
  private HierarchyListener listener;
  @Override public void updateUI() {
    removeHierarchyListener(listener);
    super.updateUI();
    listener = e -> {
      Component c = e.getComponent();
      if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) {
        Window w = SwingUtilities.getWindowAncestor(c);
        if (w instanceof JWindow) {
          ((JWindow) w).setBackground(new Color(0x0, true));
        }
      }
    };
    addHierarchyListener(listener);
    setOpaque(false);
    setBorder(BorderFactory.createEmptyBorder(8, 5, 0, 5));
  }
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.height = 28;
    return d;
  }
  @Override public void paintComponent(Graphics g) {
    Shape s = makeBalloonShape();
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(getBackground());
    g2.fill(s);
    g2.setColor(getForeground());
    g2.draw(s);
    g2.dispose();
    super.paintComponent(g);
  }
  private Shape makeBalloonShape() {
    Insets i = getInsets();
    int w = getWidth() - 1;
    int h = getHeight() - 1;
    int v = i.top / 2;
    Polygon triangle = new Polygon();
    triangle.addPoint(i.left + v + v, 0);
    triangle.addPoint(i.left + v, v);
    triangle.addPoint(i.left + v + v + v, v);
    Area area = new Area(new RoundRectangle2D.Float(
        0, v, w, h - i.bottom - v, i.top, i.top));
    area.add(new Area(triangle));
    return area;
  }
}
//...
JList list = new JList(model) {
  @Override public JToolTip createToolTip() {
    JToolTip tip = new BalloonToolTip();
    tip.setComponent(this);
    return tip;
  }
};

References

2016/11/24

aterai

Filtering JList items by Regex

Code

DefaultListModel model = new DefaultListModel<>();
JList list = new JList(model) {
  @Override public void updateUI() {
    setSelectionForeground(null);
    setSelectionBackground(null);
    setCellRenderer(null);
    super.updateUI();
    setLayoutOrientation(JList.HORIZONTAL_WRAP);
    setVisibleRowCount(0);
    setFixedCellWidth(82);
    setFixedCellHeight(64);
    setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
    setCellRenderer(new ListItemListCellRenderer());
    getSelectionModel().setSelectionMode(
        ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  }
};
private Optional getPattern() {
  try {
    return Optional.ofNullable(field.getText())
                   .filter(s -> !s.isEmpty())
                   .map(Pattern::compile);
  } catch (PatternSyntaxException ex) {
    return Optional.empty();
  }
}
private void filter() {
  getPattern().ifPresent(pattern -> {
    List selected = list.getSelectedValuesList();
    model.clear();
    Stream.of(defaultModel)
          .filter(item -> pattern.matcher(item.title).find())
          .forEach(model::addElement);
    for (ListItem item : selected) {
      int i = model.indexOf(item);
      list.addSelectionInterval(i, i);
    }
  });
}

References

2015/08/13

aterai

Create a custom drag ghost image

Code

class ListItemTransferHandler extends TransferHandler {
  @Override public int getSourceActions(JComponent c) {
    System.out.println("getSourceActions");
    if (!(c instanceof JList)) {
      return NONE;
    }
    JList source = (JList) c;
    Point pt;
    if (compact) {
      int w = source.getFixedCellWidth();
      int h = source.getFixedCellHeight() - 20; //TODO
      setDragImage(createCompactDragImage(source, w, h));
      pt = new Point(w / 2, h);
    } else {
      setDragImage(createDragImage(source));
      pt = c.getMousePosition();
    }
    if (pt != null) {
      setDragImageOffset(pt);
    }
    return MOVE; //TransferHandler.COPY_OR_MOVE;
  }
  private static BufferedImage createDragImage(JList source) {
    int w = source.getWidth();
    int h = source.getHeight();
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.getGraphics();
    DefaultListCellRenderer renderer =
      (DefaultListCellRenderer) source.getCellRenderer();
    for (int i : source.getSelectedIndices()) {
      Component c = renderer.getListCellRendererComponent(
          source, source.getModel().getElementAt(i), i, false, false);
      Rectangle rect = source.getCellBounds(i, i);
      SwingUtilities.paintComponent(g, c, source, rect);
    }
    g.dispose();
    return bi;
  }
  private BufferedImage createCompactDragImage(JList source, int w, int h) {
    BufferedImage br = null;
    if (w > 0 && h > 0) {
      br = source.getGraphicsConfiguration().createCompatibleImage(
          w, h, Transparency.TRANSLUCENT);
    } else {
      return null;
    }
    int[] selectedIndices = source.getSelectedIndices();
    int length = selectedIndices.length;
    Graphics g = br.getGraphics();
    DefaultListCellRenderer renderer =
      (DefaultListCellRenderer) source.getCellRenderer();
    int idx = selectedIndices[0];
    Object valueAt = source.getModel().getElementAt(idx);
    Component c = renderer.getListCellRendererComponent(
        source, valueAt, idx, false, false);
    Rectangle rect = source.getCellBounds(idx, idx);
    SwingUtilities.paintComponent(g, c, source, 0, 0, rect.width, rect.height);
    if (length > 1) {
      LABEL.setText(String.valueOf(length));
      Dimension d = LABEL.getPreferredSize();
      SwingUtilities.paintComponent(
          g, LABEL, source, (w - d.width) / 2, (h - d.height) / 2, d.width, d.height);
    }
    g.dispose();
    br.coerceData(true);
    return br;
  }
//...

References

2013/10/15

aterai

Scrollable list of JCheckBoxes

Code

JList

class CheckBoxCellRenderer extends JCheckBox
    implements ListCellRenderer, MouseListener, MouseMotionListener {
  @Override public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus) {
    this.setOpaque(true);
    if(isSelected) {
      this.setBackground(list.getSelectionBackground());
      this.setForeground(list.getSelectionForeground());
    }else{
      this.setBackground(list.getBackground());
      this.setForeground(list.getForeground());
    }
    if(value instanceof CheckBoxNode) {
      this.setSelected(((CheckBoxNode)value).selected);
      this.getModel().setRollover(index==rollOverRowIndex);
    }
    this.setText(value.toString());
    return this;
  }
  private int rollOverRowIndex = -1;
  @Override public void mouseExited(MouseEvent e) {
    JList l = (JList)e.getSource();
    if(rollOverRowIndex>=0) {
      l.repaint(l.getCellBounds(rollOverRowIndex, rollOverRowIndex));
      rollOverRowIndex = -1;
    }
  }
  @SuppressWarnings("unchecked")
  @Override public void mouseClicked(MouseEvent e) {
    if(e.getButton()==MouseEvent.BUTTON1) {
      JList l = (JList)e.getComponent();
      DefaultListModel m = (DefaultListModel)l.getModel();
      Point p = e.getPoint();
      int index  = l.locationToIndex(p);
      if(index>=0) {
        CheckBoxNode n = (CheckBoxNode)m.get(index);
        m.set(index, new CheckBoxNode(n.text, !n.selected));
        l.repaint(l.getCellBounds(index, index));
      }
    }
  }
  @Override public void mouseMoved(MouseEvent e) {
    JList l = (JList)e.getSource();
    int index = l.locationToIndex(e.getPoint());
    if(index != rollOverRowIndex) {
      rollOverRowIndex = index;
      l.repaint();
    }
  }
  @Override public void mouseEntered(MouseEvent e) {}
  @Override public void mousePressed(MouseEvent e) {}
  @Override public void mouseReleased(MouseEvent e) {}
  @Override public void mouseDragged(MouseEvent e) {}
}

JTree

class CheckBoxNodeRenderer extends JCheckBox implements TreeCellRenderer {
  private TreeCellRenderer renderer = new DefaultTreeCellRenderer();
  @Override public Component getTreeCellRendererComponent(
      JTree tree, Object value, boolean selected, boolean expanded,
      boolean leaf, int row, boolean hasFocus) {
    if(leaf && value != null && value instanceof DefaultMutableTreeNode) {
      this.setOpaque(false);
      Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
      if(userObject!=null && userObject instanceof CheckBoxNode) {
        CheckBoxNode node = (CheckBoxNode)userObject;
        this.setText(node.text);
        this.setSelected(node.selected);
      }
      return this;
    }
    return renderer.getTreeCellRendererComponent(
        tree, value, selected, expanded, leaf, row, hasFocus);
  }
}

class CheckBoxNodeEditor extends JCheckBox implements TreeCellEditor {
  private final JTree tree;
  public CheckBoxNodeEditor(JTree tree) {
    super();
    this.tree = tree;
    setOpaque(false);
    setFocusable(false);
    addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        stopCellEditing();
      }
    });
  }
  @Override public Component getTreeCellEditorComponent(
      JTree tree, Object value, boolean isSelected, boolean expanded,
      boolean leaf, int row) {
    if(leaf && value != null && value instanceof DefaultMutableTreeNode) {
      Object userObject = ((DefaultMutableTreeNode)value).getUserObject();
      if(userObject!=null && userObject instanceof CheckBoxNode) {
        this.setSelected(((CheckBoxNode)userObject).selected);
      } else {
        this.setSelected(false);
      }
      this.setText(value.toString());
    }
    return this;
  }
  @Override public Object getCellEditorValue() {
    return new CheckBoxNode(getText(), isSelected());
  }
  @Override public boolean isCellEditable(EventObject e) {
    return (e != null && e instanceof MouseEvent);
  }
  //Copid from AbstractCellEditor
  //protected EventListenerList listenerList = new EventListenerList();
  //transient protected ChangeEvent changeEvent = null;
  @Override public boolean shouldSelectCell(java.util.EventObject anEvent) {
//...

References

2012/10/29

aterai

Delete button in a JComboBox popup menu items

Code

class CellButtonsMouseListener extends MouseAdapter {
  private int prevIndex = -1;
  private JButton prevButton;
  private static void listRepaint(JList list, Rectangle rect) {
    if (Objects.nonNull(rect)) {
      list.repaint(rect);
    }
  }
  @Override public void mouseMoved(MouseEvent e) {
    JList list = (JList) e.getComponent();
    Point pt = e.getPoint();
    int index = list.locationToIndex(pt);
    if (!list.getCellBounds(index, index).contains(pt)) {
      if (prevIndex >= 0) {
        Rectangle r = list.getCellBounds(prevIndex, prevIndex);
        listRepaint(list, r);
      }
      index = -1;
      prevButton = null;
      return;
    }
    if (index >= 0) {
      JButton button = getButton(list, pt, index);
      ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer();
      if (Objects.nonNull(button)) {
        renderer.rolloverIndex = index;
        if (!button.equals(prevButton)) {
          Rectangle r = list.getCellBounds(prevIndex, index);
          listRepaint(list, r);
        }
      } else {
        renderer.rolloverIndex = -1;
        Rectangle r = null;
        if (prevIndex == index) {
          if (prevIndex >= 0 && Objects.nonNull(prevButton)) {
            r = list.getCellBounds(prevIndex, prevIndex);
          }
        } else {
          r = list.getCellBounds(index, index);
        }
        listRepaint(list, r);
        prevIndex = -1;
      }
      prevButton = button;
    }
    prevIndex = index;
  }
  @Override public void mousePressed(MouseEvent e) {
    JList list = (JList) e.getComponent();
    Point pt = e.getPoint();
    int index = list.locationToIndex(pt);
    if (index >= 0) {
      JButton button = getButton(list, pt, index);
      if (Objects.nonNull(button)) {
        listRepaint(list, list.getCellBounds(index, index));
      }
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    JList list = (JList) e.getComponent();
    Point pt = e.getPoint();
    int index = list.locationToIndex(pt);
    if (index >= 0) {
      JButton button = getButton(list, pt, index);
      if (Objects.nonNull(button)) {
        button.doClick();
        Rectangle r = list.getCellBounds(index, index);
        listRepaint(list, r);
      }
    }
  }
  @Override public void mouseExited(MouseEvent e) {
    JList list = (JList) e.getComponent();
    ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer();
    renderer.rolloverIndex = -1;
  }
  @SuppressWarnings("unchecked")
  private static JButton getButton(JList list, Point pt, int index) {
    Container c = (Container) list.getCellRenderer().getListCellRendererComponent(
        list, "", index, false, false);
    Rectangle r = list.getCellBounds(index, index);
    c.setBounds(r);
    // c.doLayout(); // may be needed for other layout managers (eg. FlowLayout)
    pt.translate(-r.x, -r.y);
    Component b = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y);
    if (b instanceof JButton) {
      return (JButton) b;
    } else {
      return null;
    }
  }
}

References

2012/04/26

aterai

Select multiple items in a JList by clicking and dragging

Code

JList list = new JList(model) {
  private ClearSelectionListener listener;
  @Override public void setSelectionInterval(int anchor, int lead) {
    if(anchor==lead && lead >= 0 && anchor >= 0) {
      if(listener.isDragging) {
        addSelectionInterval(anchor, anchor);
      }else if(!listener.isInCellDragging) {
        if(isSelectedIndex(anchor)) {
          removeSelectionInterval(anchor, anchor);
        }else{
          addSelectionInterval(anchor, anchor);
        }
        listener.isInCellDragging = true;
      }
    }else{
      super.setSelectionInterval(anchor, lead);
    }
  }
};

References

2011/01/20

aterai

JTable RowHeader

Code

class RowHeaderList extends JList {
  private final JTable table;
  private final ListSelectionModel tableSelection;
  private final ListSelectionModel rListSelection;
  public RowHeaderList(ListModel model, JTable table) {
    super(model);
    this.table = table;
    setFixedCellHeight(table.getRowHeight());
    setCellRenderer(new RowHeaderRenderer(table.getTableHeader()));
    RollOverListener rol = new RollOverListener();
    addMouseListener(rol);
    addMouseMotionListener(rol);
    tableSelection = table.getSelectionModel();
    rListSelection = getSelectionModel();
  }
  class RowHeaderRenderer extends JLabel implements ListCellRenderer {
    private final JTableHeader header;
    public RowHeaderRenderer(JTableHeader header) {
      this.header = header;
      this.setOpaque(true);
      this.setBorder(BorderFactory.createMatteBorder(0,0,1,2,Color.GRAY));
      this.setHorizontalAlignment(CENTER);
      this.setForeground(header.getForeground());
      this.setBackground(header.getBackground());
      this.setFont(header.getFont());
    }
    public Component getListCellRendererComponent(JList list, Object value,
               int index, boolean isSelected, boolean cellHasFocus) {
      if(index==pressedRowIndex) {
        setBackground(Color.GRAY);
      }else if(index==rollOverRowIndex) {
        setBackground(Color.WHITE);
      }else if(isSelected) {
        setBackground(Color.GRAY.brighter());
      }else{
        setForeground(header.getForeground());
        setBackground(header.getBackground());
      }
      setText((value==null)?"":value.toString());
      return this;
    }
  }
}

References

2010/08/09

aterai

Drag and Drop between JLists

Code

class ListItemTransferHandler extends TransferHandler {
  private JList source = null;
  @Override protected Transferable createTransferable(JComponent c) {
    source = (JList) c;
    indices = source.getSelectedIndices();
    transferedObjects = source.getSelectedValues();
    return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
  }
  @Override public boolean importData(TransferHandler.TransferSupport info) {
    if (!canImport(info)) return false;
    JList target = (JList)info.getComponent();
    JList.DropLocation dl = (JList.DropLocation)info.getDropLocation();
    DefaultListModel listModel = (DefaultListModel)target.getModel();
    int index = dl.getIndex();
    int max = listModel.getSize();
    if(index < 0 || index > max) index = max;
    addIndex = index;
    try{
      Object[] values = (Object[])info.getTransferable().getTransferData(localObjectFlavor);
      for(int i=0;i < values.length;i++) {
        int idx = index++;
        listModel.add(idx, values[i]);
        target.addSelectionInterval(idx, idx);
      }
      addCount = (target==source)? values.length : 0;
      return true;
    }catch(UnsupportedFlavorException ufe) {
      ufe.printStackTrace();
    }catch(java.io.IOException ioe) {
      ioe.printStackTrace();
    }
    return false;
  }
//......

References

2009/06/26

aterai

Disable Right Click In JComboBox-Dropdown-List

Code

class BasicComboPopup2 extends BasicComboPopup {
  private Handler2 handler2;
  @Override
  public void uninstallingUI() {
    super.uninstallingUI();
    handler2 = null;
  }
  public BasicComboPopup2(JComboBox combo) {
    super(combo);
  }
  protected MouseListener createListMouseListener() {
    if(handler2==null) handler2 = new Handler2();
    return handler2;
  }
  private class Handler2 implements MouseListener{
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e)  {}
    public void mouseClicked(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {
      if(e.getSource() == list) {
        if(list.getModel().getSize() > 0) {
          if(!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled()) return; // <-- ins
          // JList mouse listener
          if(comboBox.getSelectedIndex() == list.getSelectedIndex()) {
            comboBox.getEditor().setItem(list.getSelectedValue());
          }
          comboBox.setSelectedIndex(list.getSelectedIndex());
        }
        comboBox.setPopupVisible(false);
        // workaround for cancelling an edited item (bug 4530953)
        if(comboBox.isEditable() && comboBox.getEditor() != null) {
          comboBox.configureEditor(comboBox.getEditor(), comboBox.getSelectedItem());
        }
      }
    }
  }
}

References

2008/10/14

aterai

rubber band selection, drag and drop reordering

Code

JList list = new JList(model);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(0);
list.setFixedCellWidth(62);
list.setFixedCellHeight(62);
list.setCellRenderer(new IconListCellRenderer());
RubberBandingListener rbl = new RubberBandingListener();
list.addMouseMotionListener(rbl);
list.addMouseListener(rbl);
list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setTransferHandler(new ListItemTransferHandler());
list.setDropMode(DropMode.INSERT);

References

2008/10/09

aterai

using rubber band selection in JList

Code

class RubberBandingListener extends MouseInputAdapter {
  @Override public void mouseDragged(MouseEvent e) {
    setFocusable(true);
    if(srcPoint==null) srcPoint = e.getPoint();
    Point destPoint = e.getPoint();
    polygon.reset();
    polygon.addPoint(srcPoint.x,  srcPoint.y);
    polygon.addPoint(destPoint.x, srcPoint.y);
    polygon.addPoint(destPoint.x, destPoint.y);
    polygon.addPoint(srcPoint.x,  destPoint.y);
    //setSelectedIndices(getIntersectsIcons(polygon));
    if(srcPoint.getX()==destPoint.getX() || srcPoint.getY()==destPoint.getY()) {
      line.setLine(srcPoint.getX(),srcPoint.getY(),destPoint.getX(),destPoint.getY());
      setSelectedIndices(getIntersectsIcons(line));
    }else{
      setSelectedIndices(getIntersectsIcons(polygon));
    }
    repaint();
  }
  @Override
  public void mouseReleased(MouseEvent e) {
    setFocusable(true);
    srcPoint = null;
    repaint();
  }
  @Override
  public void mousePressed(MouseEvent e) {
    int index = locationToIndex(e.getPoint());
    Rectangle rect = getCellBounds(index,index);
    if(!rect.contains(e.getPoint())) {
      getSelectionModel().setLeadSelectionIndex(getModel().getSize());
      clearSelection();
      setFocusable(false);
    }else{
      setFocusable(true);
    }
  }
  private int[] getIntersectsIcons(Shape p) {
    ListModel model = getModel();
    Vector< Integer > list = new Vector< Integer >(model.getSize());
    for(int i=0;i < model.getSize();i++) {
      Rectangle r = getCellBounds(i,i);
      if(p.intersects(r)) {
        list.add(i);
      }
    }
    int[] il = new int[list.size()];
    for(int i=0;i < list.size();i++) {
      il[i] = list.get(i);
    }
    return il;
  }
}

References