/
MainPanel.java
231 lines (214 loc) · 8.58 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
// -*- 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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
TableRowTransferHandler handler = new TableRowTransferHandler();
JPanel p = new JPanel(new GridLayout(2, 1));
p.setBorder(BorderFactory.createTitledBorder("Drag & Drop JTable"));
p.add(new JScrollPane(makeDragAndDropTable(handler)));
p.add(new JScrollPane(makeDragAndDropTable(handler)));
add(p);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(320, 240));
}
private static JTable makeDragAndDropTable(TableRowTransferHandler handler) {
String[] columnNames = {"String", "Integer", "Boolean"};
Object[][] data = {
{"AAA", 12, true}, {"aaa", 1, false},
{"BBB", 13, true}, {"bbb", 2, false},
{"CCC", 15, true}, {"ccc", 3, false},
{"DDD", 17, true}, {"ddd", 4, false},
{"EEE", 18, true}, {"eee", 5, false},
{"FFF", 19, true}, {"fff", 6, false},
{"GGG", 92, true}, {"ggg", 0, false}
};
JTable table = new JTable(new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
// ArrayIndexOutOfBoundsException: 0 >= 0
// [JDK-6967479] JTable sorter fires even if the model is empty - Java Bug System
// https://bugs.openjdk.org/browse/JDK-6967479
// return getValueAt(0, column).getClass();
switch (column) {
case 0: return String.class;
case 1: return Number.class;
case 2: return Boolean.class;
default: return super.getColumnClass(column);
}
}
});
table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setTransferHandler(handler);
table.setDropMode(DropMode.INSERT_ROWS);
table.setDragEnabled(true);
table.setFillsViewportHeight(true);
// table.setAutoCreateRowSorter(true); // XXX
// // Disable JTable rows Cut, Copy, Paste
// ActionMap am = table.getActionMap();
// Action empty = new AbstractAction() {
// @Override public void actionPerformed(ActionEvent e) {
// /* do nothing */
// }
// };
// am.put(TransferHandler.getCutAction().getValue(Action.NAME), empty);
// am.put(TransferHandler.getCopyAction().getValue(Action.NAME), empty);
// am.put(TransferHandler.getPasteAction().getValue(Action.NAME), empty);
return table;
}
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);
}
}
// Demo - BasicDnD (The Java™ Tutorials > ... > Drag and Drop and Data Transfer)
// https://docs.oracle.com/javase/tutorial/uiswing/dnd/basicdemo.html
// Demo - DropDemo (The Java™ Tutorials > ... > Drag and Drop and Data Transfer)
// https://docs.oracle.com/javase/tutorial/uiswing/dnd/dropmodedemo.html
// @see https://docs.oracle.com/javase/tutorial/uiswing/examples/dnd/DropDemoProject/src/dnd/ListTransferHandler.java
class TableRowTransferHandler extends TransferHandler {
protected static final DataFlavor FLAVOR = new DataFlavor(List.class, "List of items");
// private int[] indices;
private final List<Integer> indices = new ArrayList<>();
private int addIndex = -1; // Location where items were added
private int addCount; // Number of items added.
private Component source;
// protected TableRowTransferHandler() {
// super();
// localObjectFlavor = new ActivationDataFlavor(
// Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
// }
@Override protected Transferable createTransferable(JComponent c) {
c.getRootPane().getGlassPane().setVisible(true);
source = c;
JTable table = (JTable) c;
DefaultTableModel model = (DefaultTableModel) table.getModel();
// List<Object> list = new ArrayList<>();
// indices = table.getSelectedRows();
// for (int i : indices) {
// list.add(model.getDataVector().get(i));
// }
// Object[] transferredRows = list.toArray();
// indices = table.getSelectedRows();
for (int i : table.getSelectedRows()) {
indices.add(i);
}
@SuppressWarnings("JdkObsolete")
List<?> transferredRows = indices.stream()
.map(model.getDataVector()::get)
.collect(Collectors.toList());
// return new DataHandler(transferredRows, 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 transferredRows;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
};
}
@Override public boolean canImport(TransferHandler.TransferSupport info) {
boolean canDrop = info.isDrop() && info.isDataFlavorSupported(FLAVOR);
// XXX bug? The cursor flickering problem with JTableHeader:
// info.getComponent().setCursor(
// canDrop ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
Component glassPane = ((JComponent) info.getComponent()).getRootPane().getGlassPane();
glassPane.setCursor(canDrop ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
return canDrop;
}
@Override public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
@Override public boolean importData(TransferHandler.TransferSupport info) {
JTable target = (JTable) info.getComponent();
DefaultTableModel model = (DefaultTableModel) target.getModel();
int max = model.getRowCount();
int index;
if (info.isDrop()) {
index = ((JTable.DropLocation) info.getDropLocation()).getRow();
} else { // dl.isInsert()) {
index = target.getSelectedRow();
}
// 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;
// target.setCursor(Cursor.getDefaultCursor());
try {
List<?> values = (List<?>) info.getTransferable().getTransferData(FLAVOR);
Object[] type = new Object[0];
for (Object o : values) {
int row = index++;
// model.insertRow(row, (Vector<?>) o);
model.insertRow(row, ((List<?>) o).toArray(type));
target.getSelectionModel().addSelectionInterval(row, row);
}
target.requestFocusInWindow();
if (Objects.equals(source, target) && info.isDrop()) {
addCount = values.size();
}
return true;
} catch (UnsupportedFlavorException | IOException ex) {
return false;
}
}
@Override protected void exportDone(JComponent c, Transferable data, int action) {
cleanup(c, action == MOVE);
}
private void cleanup(JComponent c, boolean remove) {
c.getRootPane().getGlassPane().setVisible(false);
// c.setCursor(Cursor.getDefaultCursor());
if (remove && !indices.isEmpty()) {
DefaultTableModel model = (DefaultTableModel) ((JTable) c).getModel();
if (addCount > 0) {
for (int i = 0; i < indices.size(); i++) {
if (indices.get(i) >= addIndex) {
// indices[i] += addCount;
indices.set(i, indices.get(i) + addCount);
}
}
}
for (int i = indices.size() - 1; i >= 0; i--) {
model.removeRow(indices.get(i));
}
}
indices.clear();
addCount = 0;
addIndex = -1;
}
}