-
Notifications
You must be signed in to change notification settings - Fork 156
/
MainPanel.java
715 lines (645 loc) · 24.9 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// -*- 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.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.TooManyListenersException;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
public final class MainPanel extends JPanel {
private final DnDTabbedPane tabbedPane = new DnDTabbedPane();
private MainPanel() {
super(new BorderLayout());
DnDTabbedPane sub = new DnDTabbedPane();
sub.addTab("Title aa", new JLabel("aaa"));
sub.addTab("Title bb", new JScrollPane(new JTree()));
sub.addTab("Title cc", new JScrollPane(new JTextArea("JTextArea cc")));
tabbedPane.addTab("JTree 00", new JScrollPane(new JTree()));
tabbedPane.addTab("JLabel 01", new JLabel("Test"));
tabbedPane.addTab("JTable 02", new JScrollPane(new JTable(10, 3)));
tabbedPane.addTab("JTextArea 03", new JScrollPane(new JTextArea("JTextArea 03")));
tabbedPane.addTab("JLabel 04", new JLabel("<html>11111111<br>13412341234123446745"));
tabbedPane.addTab("null 05", null);
tabbedPane.addTab("JTabbedPane 06", sub);
tabbedPane.addTab("Title 000000000000000007", new JScrollPane(new JTree()));
// ButtonTabComponent
IntStream.range(0, tabbedPane.getTabCount()).forEach(this::setTabComponent);
tabbedPane.setName("JTabbedPane#main");
sub.setName("JTabbedPane#sub1");
TabTransferHandler handler = new TabTransferHandler();
LayerUI<DnDTabbedPane> layerUI = new DropLocationLayerUI();
DropTargetListener listener = new TabDropTargetAdapter();
Stream.of(tabbedPane, sub).forEach(tabs -> {
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabs.setTransferHandler(handler);
try {
tabs.getDropTarget().addDropTargetListener(listener);
} catch (TooManyListenersException ex) {
UIManager.getLookAndFeel().provideErrorFeedback(tabs);
}
});
add(new JLayer<>(tabbedPane, layerUI));
setPreferredSize(new Dimension(320, 240));
}
private void setTabComponent(int i) {
tabbedPane.setTabComponentAt(i, new ButtonTabComponent(tabbedPane));
tabbedPane.setToolTipTextAt(i, "tooltip: " + i);
}
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.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class DnDTabbedPane extends JTabbedPane {
private static final int SCROLL_SZ = 20; // Test
private static final int BUTTON_SZ = 30; // XXX 30 is magic number of scroll button size
private static final Rectangle RECT_BACKWARD = new Rectangle();
private static final Rectangle RECT_FORWARD = new Rectangle();
protected int dragTabIndex = -1;
private transient DnDTabbedPane.DropLocation dropLocation;
private transient Handler handler;
protected final Point pointOnScreen = new Point(-1, -1);
public static final class DropLocation extends TransferHandler.DropLocation {
private final int index;
private DropLocation(Point p, int index) {
super(p);
this.index = index;
}
public int getIndex() {
return index;
}
}
private void clickArrowButton(String actionKey) {
JButton forwardButton = null;
JButton backwardButton = null;
for (Component c : getComponents()) {
if (c instanceof JButton) {
if (Objects.isNull(forwardButton)) {
forwardButton = (JButton) c;
} else if (Objects.isNull(backwardButton)) {
backwardButton = (JButton) c;
}
}
}
JButton button = "scrollTabsForwardAction".equals(actionKey)
? forwardButton
: backwardButton;
Optional.ofNullable(button).filter(JButton::isEnabled).ifPresent(JButton::doClick);
}
public void autoScrollTest(Point pt) {
Rectangle r = getTabAreaBounds();
// int tabPlacement = getTabPlacement();
// if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int arrowBoxSize = SCROLL_SZ + BUTTON_SZ;
if (isTopBottomTabPlacement(getTabPlacement())) {
RECT_BACKWARD.setBounds(r.x, r.y, SCROLL_SZ, r.height);
RECT_FORWARD.setBounds(r.x + r.width - arrowBoxSize, r.y, arrowBoxSize, r.height);
} else { // if (tabPlacement == LEFT || tabPlacement == RIGHT) {
RECT_BACKWARD.setBounds(r.x, r.y, r.width, SCROLL_SZ);
RECT_FORWARD.setBounds(r.x, r.y + r.height - arrowBoxSize, r.width, arrowBoxSize);
}
if (RECT_BACKWARD.contains(pt)) {
clickArrowButton("scrollTabsBackwardAction");
} else if (RECT_FORWARD.contains(pt)) {
clickArrowButton("scrollTabsForwardAction");
}
}
@Override public void updateUI() {
removeMouseListener(handler);
removeMouseMotionListener(handler);
removePropertyChangeListener(handler);
super.updateUI();
handler = new Handler();
addMouseListener(handler);
addMouseMotionListener(handler);
addPropertyChangeListener(handler);
}
// @Override TransferHandler.DropLocation dropLocationForPoint(Point p) {
public DnDTabbedPane.DropLocation tabDropLocationForPoint(Point p) {
// assert dropMode == DropMode.INSERT : "Unexpected drop mode";
for (int i = 0; i < getTabCount(); i++) {
if (getBoundsAt(i).contains(p)) {
return new DnDTabbedPane.DropLocation(p, i);
}
}
if (getTabAreaBounds().contains(p)) {
return new DnDTabbedPane.DropLocation(p, getTabCount());
}
return new DnDTabbedPane.DropLocation(p, -1);
}
public final DnDTabbedPane.DropLocation getDropLocation() {
return dropLocation;
}
// public Object updateTabDropLocation(DropLocation location, Object state, boolean forDrop) {
public void updateTabDropLocation(DnDTabbedPane.DropLocation location, boolean forDrop) {
DnDTabbedPane.DropLocation old = dropLocation;
if (Objects.isNull(location) || !forDrop) {
dropLocation = new DnDTabbedPane.DropLocation(new Point(), -1);
} else {
dropLocation = location;
}
firePropertyChange("dropLocation", old, dropLocation);
// return state;
}
public void exportTab(int dragIndex, JTabbedPane target, int targetIndex) {
// System.out.println("exportTab");
final Component cmp = getComponentAt(dragIndex);
final String title = getTitleAt(dragIndex);
final Icon icon = getIconAt(dragIndex);
final String toolTipText = getToolTipTextAt(dragIndex);
final boolean isEnabled = isEnabledAt(dragIndex);
Component tab = getTabComponentAt(dragIndex);
if (tab instanceof ButtonTabComponent) {
tab = new ButtonTabComponent(target);
}
remove(dragIndex);
target.insertTab(title, icon, cmp, toolTipText, targetIndex);
target.setEnabledAt(targetIndex, isEnabled);
target.setTabComponentAt(targetIndex, tab);
target.setSelectedIndex(targetIndex);
Optional.ofNullable(SwingUtilities.getWindowAncestor(target))
.ifPresent(Window::toFront);
target.requestFocusInWindow();
target.setSelectedIndex(targetIndex);
pointOnScreen.setLocation(-1, -1);
}
public void convertTab(int prev, int next) {
// System.out.println("convertTab");
// if (next < 0 || prev == next) {
// return;
// }
final Component cmp = getComponentAt(prev);
final Component tab = getTabComponentAt(prev);
final String title = getTitleAt(prev);
final Icon icon = getIconAt(prev);
final String tip = getToolTipTextAt(prev);
final boolean isEnabled = isEnabledAt(prev);
int tgtIndex = prev > next ? next : next - 1;
remove(prev);
insertTab(title, icon, cmp, tip, tgtIndex);
setEnabledAt(tgtIndex, isEnabled);
// When you drag and drop a disabled tab, it finishes enabled and selected.
// pointed out by dlorde
if (isEnabled) {
setSelectedIndex(tgtIndex);
}
// I have a component in all tabs (JLabel with an X to close the tab)
// and when I move a tab the component disappear.
// pointed out by Daniel Dario Morales Salas
setTabComponentAt(tgtIndex, tab);
pointOnScreen.setLocation(-1, -1);
}
public Rectangle getTabAreaBounds() {
Rectangle tabbedRect = getBounds();
int xx = tabbedRect.x;
int yy = tabbedRect.y;
Rectangle compRect = Optional.ofNullable(getSelectedComponent())
.map(Component::getBounds)
.orElseGet(Rectangle::new);
int tabPlacement = getTabPlacement();
if (isTopBottomTabPlacement(tabPlacement)) {
tabbedRect.height -= compRect.height;
if (tabPlacement == BOTTOM) {
tabbedRect.y += compRect.y + compRect.height;
}
} else {
tabbedRect.width -= compRect.width;
if (tabPlacement == RIGHT) {
tabbedRect.x += compRect.x + compRect.width;
}
}
tabbedRect.translate(-xx, -yy);
// tabbedRect.grow(2, 2);
return tabbedRect;
}
public static boolean isTopBottomTabPlacement(int tabPlacement) {
return tabPlacement == TOP || tabPlacement == BOTTOM;
}
private final class Handler extends MouseAdapter implements PropertyChangeListener {
private Point startPt;
private final int dragThreshold = DragSource.getDragThreshold();
// Toolkit tk = Toolkit.getDefaultToolkit();
// Integer dragThreshold = (Integer) tk.getDesktopProperty("DnD.gestureMotionThreshold");
// PropertyChangeListener
@Override public void propertyChange(PropertyChangeEvent e) {
if (Objects.equals("dropLocation", e.getPropertyName())) {
repaint();
}
}
// MouseListener
@Override public void mousePressed(MouseEvent e) {
DnDTabbedPane src = (DnDTabbedPane) e.getComponent();
// boolean isOnlyOneTab = src.getTabCount() <= 1;
// if (isOnlyOneTab) {
// startPt = null;
// return;
// }
Point tabPt = e.getPoint(); // e.getDragOrigin();
int idx = src.indexAtLocation(tabPt.x, tabPt.y);
// disabled tab, null component problem.
// pointed out by daryl. NullPointerException: i.e. addTab("Tab", null)
boolean flag = idx < 0 || !src.isEnabledAt(idx) || Objects.isNull(src.getComponentAt(idx));
startPt = flag ? null : tabPt;
}
@Override public void mouseDragged(MouseEvent e) {
Point tabPt = e.getPoint(); // e.getDragOrigin();
if (Objects.nonNull(startPt) && startPt.distance(tabPt) > dragThreshold) {
DnDTabbedPane src = (DnDTabbedPane) e.getComponent();
TransferHandler th = src.getTransferHandler();
// When a tab runs rotation occurs, a tab that is not the target is dragged.
// pointed out by Arjen
int idx = src.indexAtLocation(tabPt.x, tabPt.y);
int selIdx = src.getSelectedIndex();
boolean isRotateTabRuns = !(src.getUI() instanceof MetalTabbedPaneUI)
&& src.getTabLayoutPolicy() == WRAP_TAB_LAYOUT && idx != selIdx;
dragTabIndex = isRotateTabRuns ? selIdx : idx;
th.exportAsDrag(src, e, TransferHandler.MOVE);
startPt = null;
}
}
}
}
class TabDropTargetAdapter extends DropTargetAdapter {
private void clearDropLocationPaint(Component c) {
if (c instanceof DnDTabbedPane) {
DnDTabbedPane t = (DnDTabbedPane) c;
t.updateTabDropLocation(null, false);
t.setCursor(Cursor.getDefaultCursor());
}
}
@Override public void drop(DropTargetDropEvent e) {
Component c = e.getDropTargetContext().getComponent();
// System.out.println("DropTargetListener#drop: " + c.getName());
clearDropLocationPaint(c);
}
@Override public void dragExit(DropTargetEvent e) {
Component c = e.getDropTargetContext().getComponent();
// System.out.println("DropTargetListener#dragExit: " + c.getName());
clearDropLocationPaint(c);
}
// @Override public void dragEnter(DropTargetDragEvent e) {
// Component c = e.getDropTargetContext().getComponent();
// System.out.println("DropTargetListener#dragEnter: " + c.getName());
// }
// @Override public void dragOver(DropTargetDragEvent e) {
// // System.out.println("dragOver");
// }
// @Override public void dropActionChanged(DropTargetDragEvent e) {
// System.out.println("dropActionChanged");
// }
}
class DnDTabData {
public final DnDTabbedPane tabbedPane;
protected DnDTabData(DnDTabbedPane tabbedPane) {
this.tabbedPane = tabbedPane;
}
}
class TabTransferHandler extends TransferHandler {
protected final DataFlavor localObjectFlavor = new DataFlavor(DnDTabData.class, "DnDTabData");
protected DnDTabbedPane source;
protected final JLabel label = new JLabel() {
// Free the pixel: GHOST drag and drop, over multiple windows
// https://free-the-pixel.blogspot.com/2010/04/ghost-drag-and-drop-over-multiple.html
@Override public boolean contains(int x, int y) {
return false;
}
};
protected JWindow dialog;
protected TabTransferHandler() {
super();
// System.out.println("TabTransferHandler");
DragSource.getDefaultDragSource().addDragSourceMotionListener(e -> {
Point pt = e.getLocation();
pt.translate(5, 5); // offset
if (dialog != null) {
dialog.setLocation(pt);
}
source.pointOnScreen.setLocation(pt);
});
}
@Override protected Transferable createTransferable(JComponent c) {
// System.out.println("createTransferable");
if (c instanceof DnDTabbedPane) {
source = (DnDTabbedPane) c;
}
// return new DataHandler(c, localObjectFlavor.getMimeType());
return new Transferable() {
@Override public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {
localObjectFlavor,
DataFlavor.javaFileListFlavor
};
}
@Override public boolean isDataFlavorSupported(DataFlavor flavor) {
return Arrays.asList(getTransferDataFlavors()).contains(flavor);
}
@Override public Object getTransferData(DataFlavor flavor) {
DataFlavor[] flavors = getTransferDataFlavors();
return flavor.equals(flavors[0])
? new DnDTabData(source)
: Collections.<File>emptyList();
}
};
}
@Override public boolean canImport(TransferSupport support) {
// System.out.println("canImport");
if (!support.isDrop() || !support.isDataFlavorSupported(localObjectFlavor)) {
// boolean b = support.isDataFlavorSupported(localObjectFlavor);
// System.out.println("canImport:" + support.isDrop() + " " + b);
return false;
}
support.setDropAction(MOVE);
TransferHandler.DropLocation tdl = support.getDropLocation();
Point pt = tdl.getDropPoint();
DnDTabbedPane target = (DnDTabbedPane) support.getComponent();
target.autoScrollTest(pt);
DnDTabbedPane.DropLocation dl = target.tabDropLocationForPoint(pt);
int idx = dl.getIndex();
boolean canDrop;
boolean inArea = target.getTabAreaBounds().contains(pt) && idx >= 0;
if (target.equals(source)) {
// System.out.println("target == source");
canDrop = inArea && idx != target.dragTabIndex && idx != target.dragTabIndex + 1;
} else {
// System.out.format("tgt!=src%n tgt: %s%n src: %s", target.getName(), source.getName());
canDrop = Optional.ofNullable(source)
.map(c -> !c.isAncestorOf(target))
.orElse(false) && inArea;
}
// [JDK-6700748]
// Cursor flickering during D&D when using CellRendererPane with validation - Java Bug System
// https://bugs.openjdk.org/browse/JDK-6700748
target.setCursor(canDrop ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
support.setShowDropLocation(canDrop);
// dl.canDrop = canDrop;
target.updateTabDropLocation(dl, canDrop);
return canDrop;
}
private BufferedImage makeDragTabImage(DnDTabbedPane tabs) {
Rectangle rect = tabs.getBoundsAt(tabs.dragTabIndex);
int w = tabs.getWidth();
int h = tabs.getHeight();
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.createGraphics();
tabs.paint(g);
g.dispose();
if (rect.x < 0) {
rect.translate(-rect.x, 0);
}
if (rect.y < 0) {
rect.translate(0, -rect.y);
}
if (rect.x + rect.width > img.getWidth()) {
rect.width = img.getWidth() - rect.x;
}
if (rect.y + rect.height > img.getHeight()) {
rect.height = img.getHeight() - rect.y;
}
return img.getSubimage(rect.x, rect.y, rect.width, rect.height);
}
@Override public int getSourceActions(JComponent c) {
// System.out.println("getSourceActions");
if (c instanceof DnDTabbedPane) {
DnDTabbedPane src = (DnDTabbedPane) c;
if (src.dragTabIndex < 0) {
return NONE;
}
label.setIcon(new ImageIcon(makeDragTabImage(src)));
dialog = new JWindow();
dialog.setOpacity(.5f);
dialog.add(label);
dialog.pack();
dialog.setVisible(true);
return MOVE;
}
return NONE;
}
@Override public boolean importData(TransferSupport support) {
// System.out.println("importData");
DnDTabbedPane target = (DnDTabbedPane) support.getComponent();
DnDTabbedPane.DropLocation dl = target.getDropLocation();
try {
DnDTabData data = (DnDTabData) support.getTransferable().getTransferData(localObjectFlavor);
DnDTabbedPane src = data.tabbedPane;
int index = dl.getIndex(); // boolean insert = dl.isInsert();
if (target.equals(src)) {
src.convertTab(src.dragTabIndex, index); // getTargetTabIndex(e.getLocation()));
} else {
src.exportTab(src.dragTabIndex, target, index);
}
return true;
} catch (UnsupportedFlavorException | IOException ex) {
return false;
}
}
@Override protected void exportDone(JComponent c, Transferable data, int action) {
// System.out.println("exportDone");
DnDTabbedPane src = (DnDTabbedPane) c;
if (src.pointOnScreen.x > 0) {
createNewFrame(src);
}
if (src.getTabCount() == 0) {
Optional.ofNullable(SwingUtilities.getWindowAncestor(src)).ifPresent(Window::dispose);
}
src.updateTabDropLocation(null, false);
src.repaint();
dialog.dispose();
}
private static void createNewFrame(DnDTabbedPane src) {
int index = src.dragTabIndex;
final Component cmp = src.getComponentAt(index);
// final Component tab = src.getTabComponentAt(index);
final String title = src.getTitleAt(index);
final Icon icon = src.getIconAt(index);
final String tip = src.getToolTipTextAt(index);
src.remove(index);
DnDTabbedPane tabs = new DnDTabbedPane();
tabs.setTransferHandler(src.getTransferHandler());
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabs.addTab(title, icon, cmp, tip);
// tabs.setTabComponentAt(0, tab);
tabs.setTabComponentAt(0, new ButtonTabComponent(tabs));
DropTargetListener listener = new TabDropTargetAdapter();
try {
tabs.getDropTarget().addDropTargetListener(listener);
} catch (TooManyListenersException ex) {
ex.printStackTrace();
UIManager.getLookAndFeel().provideErrorFeedback(tabs);
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JLayer<>(tabs, new DropLocationLayerUI()));
frame.setSize(320, 240);
frame.setLocation(src.pointOnScreen);
frame.setVisible(true);
EventQueue.invokeLater(frame::toFront);
}
}
class DropLocationLayerUI extends LayerUI<DnDTabbedPane> {
private static final int LINE_SZ = 3;
private static final Rectangle LINE_RECT = new Rectangle();
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
JLayer<?> layer = (JLayer<?>) c;
DnDTabbedPane tabbedPane = (DnDTabbedPane) layer.getView();
Optional.ofNullable(tabbedPane.getDropLocation())
.filter(loc -> loc.getIndex() >= 0)
.ifPresent(loc -> {
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
g2.setPaint(Color.RED);
initLineRect(tabbedPane, loc);
g2.fill(LINE_RECT);
g2.dispose();
});
}
}
private static void initLineRect(JTabbedPane tabbedPane, DnDTabbedPane.DropLocation loc) {
int index = loc.getIndex();
int a = Math.min(index, 1); // index == 0 ? 0 : 1;
Rectangle r = tabbedPane.getBoundsAt(a * (index - 1));
if (DnDTabbedPane.isTopBottomTabPlacement(tabbedPane.getTabPlacement())) {
LINE_RECT.setBounds(r.x - LINE_SZ / 2 + r.width * a, r.y, LINE_SZ, r.height);
} else {
LINE_RECT.setBounds(r.x, r.y - LINE_SZ / 2 + r.height * a, r.width, LINE_SZ);
}
}
}
// How to Use Tabbed Panes (The Java™ Tutorials > ... > Using Swing Components)
// https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
class ButtonTabComponent extends JPanel {
private final JTabbedPane tabbedPane;
protected ButtonTabComponent(JTabbedPane tabbedPane) {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
this.tabbedPane = Objects.requireNonNull(tabbedPane, "TabbedPane cannot be null");
JLabel label = new JLabel() {
@Override public String getText() {
String txt = null;
int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
txt = tabbedPane.getTitleAt(i);
}
return txt;
}
@Override public Icon getIcon() {
Icon icn = null;
int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
icn = tabbedPane.getIconAt(i);
}
return icn;
}
};
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
JButton button = new TabButton();
TabButtonHandler handler = new TabButtonHandler();
button.addActionListener(handler);
button.addMouseListener(handler);
add(label);
add(button);
}
@Override public final Component add(Component comp) {
return super.add(comp);
}
@Override public void updateUI() {
super.updateUI();
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
}
private final class TabButtonHandler extends MouseAdapter implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
int i = tabbedPane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
tabbedPane.remove(i);
}
}
@Override public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
}
}
@Override public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
}
}
final class TabButton extends JButton {
private static final int SIZE = 17;
private static final int DELTA = 6;
@Override public void updateUI() {
// we don't want to update UI for this button
// super.updateUI();
setUI(new BasicButtonUI());
setToolTipText("close this tab");
setContentAreaFilled(false);
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
setRolloverEnabled(true);
}
@Override public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(new BasicStroke(2));
g2.setPaint(Color.BLACK);
if (getModel().isRollover()) {
g2.setPaint(Color.ORANGE);
}
if (getModel().isPressed()) {
g2.setPaint(Color.BLUE);
}
g2.drawLine(DELTA, DELTA, getWidth() - DELTA - 1, getHeight() - DELTA - 1);
g2.drawLine(getWidth() - DELTA - 1, DELTA, DELTA, getHeight() - DELTA - 1);
g2.dispose();
}
}