-
Notifications
You must be signed in to change notification settings - Fork 156
/
MainPanel.java
472 lines (425 loc) · 16.1 KB
/
MainPanel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DragSource;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.MouseInputListener;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
DefaultListModel<ListItem> model = new DefaultListModel<>();
// [XP Style Icons - Download](https://xp-style-icons.en.softonic.com/)
model.addElement(new ListItem("wi0009", "example/wi0009-32.png"));
model.addElement(new ListItem("12345", "example/wi0054-32.png"));
model.addElement(new ListItem("wi0062-32", "example/wi0062-32.png"));
model.addElement(new ListItem("test", "example/wi0063-32.png"));
model.addElement(new ListItem("32.png", "example/wi0064-32.png"));
model.addElement(new ListItem("67890.jpg", "example/wi0096-32.png"));
model.addElement(new ListItem("6896", "example/wi0111-32.png"));
model.addElement(new ListItem("t467467est", "example/wi0122-32.png"));
model.addElement(new ListItem("test123", "example/wi0124-32.png"));
model.addElement(new ListItem("test(1)", "example/wi0126-32.png"));
add(new JScrollPane(new ReorderableList<>(model)));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException ignored) {
Toolkit.getDefaultToolkit().beep();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
ex.printStackTrace();
return;
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ReorderableList<E extends ListItem> extends JList<E> {
private transient MouseInputListener rbl;
private Color rubberBandColor;
protected final Path2D rubberBand = new Path2D.Double();
protected ReorderableList(ListModel<E> model) {
super(model);
}
@Override public void updateUI() {
setSelectionForeground(null); // Nimbus
setSelectionBackground(null); // Nimbus
setCellRenderer(null);
setTransferHandler(null);
removeMouseListener(rbl);
removeMouseMotionListener(rbl);
super.updateUI();
rubberBandColor = makeRubberBandColor(getSelectionBackground());
setLayoutOrientation(HORIZONTAL_WRAP);
setVisibleRowCount(0);
setFixedCellWidth(62);
setFixedCellHeight(62);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
setCellRenderer(new ListItemListCellRenderer<>());
rbl = new RubberBandingListener();
addMouseMotionListener(rbl);
addMouseListener(rbl);
// putClientProperty("List.isFileList", Boolean.TRUE);
getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
setTransferHandler(new ListItemTransferHandler());
setDropMode(DropMode.INSERT);
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (getDragEnabled()) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
g2.setPaint(getSelectionBackground());
g2.draw(rubberBand);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .1f));
g2.setPaint(rubberBandColor);
g2.fill(rubberBand);
g2.dispose();
}
private static Color makeRubberBandColor(Color c) {
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int max = Math.max(Math.max(r, g), b);
if (max == r) {
max <<= 8;
} else if (max == g) {
max <<= 4;
}
return new Color(max);
}
protected Path2D getRubberBand() {
return rubberBand;
}
private final class RubberBandingListener extends MouseInputAdapter {
private final Point srcPoint = new Point();
@Override public void mouseDragged(MouseEvent e) {
JList<?> l = (JList<?>) e.getComponent();
if (l.getDragEnabled()) {
return;
}
Point dstPoint = e.getPoint();
Path2D rb = getRubberBand();
rb.reset();
rb.moveTo(srcPoint.x, srcPoint.y);
rb.lineTo(dstPoint.x, srcPoint.y);
rb.lineTo(dstPoint.x, dstPoint.y);
rb.lineTo(srcPoint.x, dstPoint.y);
rb.closePath();
// JDK 1.7.0: l.setSelectedIndices(getIntersectsIcons(l, rubberBand));
int[] indices = IntStream.range(0, l.getModel().getSize())
.filter(i -> rb.intersects(l.getCellBounds(i, i))).toArray();
l.setSelectedIndices(indices);
l.repaint();
}
@Override public void mouseReleased(MouseEvent e) {
JList<?> l = (JList<?>) e.getComponent();
l.setFocusable(true);
// if (Objects.isNull(srcPoint) || !getDragEnabled()) {
// Component glassPane = l.getRootPane().getGlassPane();
// glassPane.setVisible(false);
// }
getRubberBand().reset();
l.setDragEnabled(l.getSelectedIndices().length > 0);
l.repaint();
}
@Override public void mousePressed(MouseEvent e) {
JList<?> l = (JList<?>) e.getComponent();
int index = l.locationToIndex(e.getPoint());
if (l.getCellBounds(index, index).contains(e.getPoint())) {
l.setFocusable(true);
if (l.getDragEnabled()) {
return;
}
// System.out.println("ccc:" + startSelectedIndex);
l.setSelectedIndex(index);
} else {
l.clearSelection();
l.getSelectionModel().setAnchorSelectionIndex(-1);
l.getSelectionModel().setLeadSelectionIndex(-1);
l.setFocusable(false);
l.setDragEnabled(false);
}
srcPoint.setLocation(e.getPoint());
l.repaint();
}
// // JDK 1.7.0
// private static int[] getIntersectsIcons(JList<?> l, Shape rect) {
// ListModel model = l.getModel();
// List<Integer> ll = new ArrayList<>(model.getSize());
// for (int i = 0; i < model.getSize(); i++) {
// if (rect.intersects(l.getCellBounds(i, i))) {
// ll.add(i);
// }
// }
// // JDK 1.8.0: return ll.stream().mapToInt(Integer::intValue).toArray();
// int[] il = new int[ll.size()];
// for (int i = 0; i < ll.size(); i++) {
// il[i] = ll.get(i);
// }
// return il;
// }
}
}
class SelectedImageFilter extends RGBImageFilter {
// public SelectedImageFilter() {
// canFilterIndexColorModel = false;
// }
@Override public int filterRGB(int x, int y, int argb) {
// Color color = new Color(argb, true);
// float[] array = new float[4];
// color.getComponents(array);
// return new Color(array[0], array[1], array[2] * .5f, array[3]).getRGB();
return (argb & 0xFF_FF_FF_00) | ((argb & 0xFF) >> 1);
}
}
// class DotBorder extends EmptyBorder {
// protected DotBorder(Insets borderInsets) {
// super(borderInsets);
// }
//
// protected DotBorder(int top, int left, int bottom, int right) {
// super(top, left, bottom, right);
// }
//
// @Override public boolean isBorderOpaque() {
// return true;
// }
//
// @Override public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
// Graphics2D g2 = (Graphics2D) g.create();
// g2.translate(x, y);
// g2.setPaint(new Color(~SystemColor.activeCaption.getRGB()));
// // new Color(200, 150, 150));
// // g2.setStroke(dashed);
// // g2.drawRect(0, 0, w - 1, h - 1);
// BasicGraphicsUtils.drawDashedRect(g2, 0, 0, w, h);
// g2.dispose();
// }
// }
class ListItemListCellRenderer<E extends ListItem> implements ListCellRenderer<E> {
private final JPanel renderer = new JPanel(new BorderLayout());
private final JLabel icon = new JLabel((Icon) null, SwingConstants.CENTER);
private final JLabel label = new JLabel("", SwingConstants.CENTER);
// private final Border dotBorder = new DotBorder(2, 2, 2, 2);
// private final Border empBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2);
private final Border focusBorder = UIManager.getBorder("List.focusCellHighlightBorder");
private final Border noFocusBorder; // = UIManager.getBorder("List.noFocusBorder");
protected ListItemListCellRenderer() {
Border b = UIManager.getBorder("List.noFocusBorder");
if (Objects.isNull(b)) { // Nimbus???
Insets i = focusBorder.getBorderInsets(label);
b = BorderFactory.createEmptyBorder(i.top, i.left, i.bottom, i.right);
}
noFocusBorder = b;
icon.setOpaque(false);
label.setForeground(renderer.getForeground());
label.setBackground(renderer.getBackground());
label.setBorder(noFocusBorder);
renderer.setOpaque(false);
renderer.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
renderer.add(icon);
renderer.add(label, BorderLayout.SOUTH);
}
@Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
label.setText(value.getTitle());
label.setBorder(cellHasFocus ? focusBorder : noFocusBorder);
if (isSelected) {
icon.setIcon(value.getSelectedIcon());
label.setForeground(list.getSelectionForeground());
label.setBackground(list.getSelectionBackground());
label.setOpaque(true);
} else {
icon.setIcon(value.getIcon());
label.setForeground(list.getForeground());
label.setBackground(list.getBackground());
label.setOpaque(false);
}
return renderer;
}
}
class ListItem implements Serializable {
private static final long serialVersionUID = 1L;
private final ImageIcon icon;
private final ImageIcon selectedIcon;
private final String title;
protected ListItem(String title, String path) {
this.title = title;
Image image = makeImage(path);
this.icon = new ImageIcon(image);
ImageProducer ip = new FilteredImageSource(image.getSource(), new SelectedImageFilter());
this.selectedIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(ip));
}
public String getTitle() {
return title;
}
public ImageIcon getIcon() {
return icon;
}
public ImageIcon getSelectedIcon() {
return selectedIcon;
}
public static Image makeImage(String path) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return Optional.ofNullable(cl.getResource(path)).map(url -> {
try (InputStream s = url.openStream()) {
return ImageIO.read(s);
} catch (IOException ex) {
return makeMissingImage();
}
}).orElseGet(ListItem::makeMissingImage);
}
private static Image makeMissingImage() {
Icon missingIcon = UIManager.getIcon("OptionPane.errorIcon");
int iw = missingIcon.getIconWidth();
int ih = missingIcon.getIconHeight();
BufferedImage bi = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
missingIcon.paintIcon(null, g2, (32 - iw) / 2, (32 - ih) / 2);
g2.dispose();
return bi;
}
}
// Demo - BasicDnD (The Java™ Tutorials > ... > Drag and Drop and Data Transfer)
// https://docs.oracle.com/javase/tutorial/uiswing/dnd/basicdemo.html
class ListItemTransferHandler extends TransferHandler {
protected static final DataFlavor FLAVOR = new DataFlavor(List.class, "List of items");
private final List<Integer> indices = new ArrayList<>();
private int addIndex = -1; // Location where items were added
private int addCount; // Number of items added.
// protected ListItemTransferHandler() {
// super();
// localObjectFlavor = new ActivationDataFlavor(
// Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
// // localObjectFlavor = new DataFlavor(Object[].class, "Array of items");
// }
@Override protected Transferable createTransferable(JComponent c) {
JList<?> source = (JList<?>) c;
c.getRootPane().getGlassPane().setVisible(true);
for (int i : source.getSelectedIndices()) {
indices.add(i);
}
// Object[] transferredObjects = source.getSelectedValuesList().toArray(new Object[0]);
// return new DataHandler(transferredObjects, FLAVOR.getMimeType());
return new Transferable() {
@Override public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {FLAVOR};
}
@Override public boolean isDataFlavorSupported(DataFlavor flavor) {
return Objects.equals(FLAVOR, flavor);
}
@Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return source.getSelectedValuesList();
} else {
throw new UnsupportedFlavorException(flavor);
}
}
};
}
@Override public boolean canImport(TransferSupport info) {
return info.isDrop() && info.isDataFlavorSupported(FLAVOR);
}
@Override public int getSourceActions(JComponent c) {
// System.out.println("getSourceActions");
c.getRootPane().getGlassPane().setCursor(DragSource.DefaultMoveDrop);
// glassPane.setVisible(true);
return MOVE; // TransferHandler.COPY_OR_MOVE;
}
@Override public boolean importData(TransferSupport info) {
Component c = info.getComponent();
DropLocation dl = info.getDropLocation();
Transferable t = info.getTransferable();
return c instanceof JList
&& dl instanceof JList.DropLocation
&& addSelection((JList<?>) c, (JList.DropLocation) dl, t);
}
@SuppressWarnings("unchecked")
private boolean addSelection(JList<?> target, JList.DropLocation dl, Transferable t) {
DefaultListModel<Object> model = (DefaultListModel<Object>) target.getModel();
int max = model.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);
index = index >= 0 && index < max ? index : max;
addIndex = index;
List<?> values = getTransferData(t);
for (Object o : values) {
int i = index++;
model.add(i, o);
target.addSelectionInterval(i, i);
}
addCount = values.size();
return !values.isEmpty();
}
private static List<?> getTransferData(Transferable transferable) {
List<?> values;
try {
values = (List<?>) transferable.getTransferData(FLAVOR);
} catch (UnsupportedFlavorException | IOException ex) {
values = Collections.emptyList();
}
return values;
}
@Override protected void exportDone(JComponent c, Transferable data, int action) {
// System.out.println("exportDone");
Component glassPane = c.getRootPane().getGlassPane();
// glassPane.setCursor(Cursor.getDefaultCursor());
glassPane.setVisible(false);
cleanup(c, action == MOVE);
}
private void cleanup(JComponent c, boolean remove) {
if (remove && !indices.isEmpty()) {
// If we are moving items around in the same list, we
// need to adjust the indices accordingly, since those
// after the insertion point have moved.
if (addCount > 0) {
for (int i = 0; i < indices.size(); i++) {
if (indices.get(i) >= addIndex) {
indices.set(i, indices.get(i) + addCount);
}
}
}
JList<?> src = (JList<?>) c;
DefaultListModel<?> model = (DefaultListModel<?>) src.getModel();
for (int i = indices.size() - 1; i >= 0; i--) {
model.remove(indices.get(i));
}
}
indices.clear();
addCount = 0;
addIndex = -1;
}
}