JPopupMenuにマウスドラッグで位置変更を可能にするヘッダを追加する
Total: 1332, Today: 1, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JPopupMenuにJLabelで作成したヘッダを追加し、MouseListenerを追加してドラッグで位置変更を可能にします。
Screenshot

Advertisement
Source Code Examples
class PopupHeaderMouseListener extends MouseAdapter {
private final Point startPt = new Point();
@Override public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
Component c = e.getComponent();
Container popup = SwingUtilities.getAncestorOfClass(
JPopupMenu.class, c);
SwingUtilities.convertMouseEvent(c, e, popup);
startPt.setLocation(e.getPoint());
}
}
@Override public void mouseDragged(MouseEvent e) {
Component c = e.getComponent();
if (SwingUtilities.isLeftMouseButton(e)) {
Window w = SwingUtilities.getWindowAncestor(c);
if (w != null && w.getType() == Window.Type.POPUP) {
// Popup$HeavyWeightWindow
Point pt = e.getLocationOnScreen();
w.setLocation(pt.x - startPt.x, pt.y - startPt.y);
} else {
// Popup$LightWeightWindow
Container popup = SwingUtilities.getAncestorOfClass(
JPopupMenu.class, c);
Point pt = popup.getLocationOnScreen();
popup.setLocation(
pt.x - startPt.x + e.getX(), pt.y - startPt.y + e.getY());
}
}
}
}
View in GitHub: Java, KotlinDescription
JPopupMenuのデフォルトレイアウトは垂直BoxLayoutなので、ドラッグ可能なヘッダとして使用するJLabelはgetMaximumSize()をオーバーライドして最大幅をJPopupMenuの推奨幅以上に設定しておくJPopupMenuの幅スペースを残さないようヘッダの幅が水平方向に引き伸ばすために必要な設定- JComboBoxのドロップダウンリストにヘッダ・フッタを追加する
GTKLookAndFeelではheader.setAlignmentX(Component.CENTER_ALIGNMENT)を設定しないとヘッダ左側に余白が生成される場合がある?
JPopupMenuが親JFrame外に表示されてPopup$HeavyWeightWindowになる場合:MouseEvent#getLocationOnScreen()で取得したデスクトップ領域の絶対位置にSwingUtilities.getWindowAncestor(header)で取得したJPopupMenuの親Windowを移動- JWindowをマウスで移動
JPopupMenuが親JFrame内に表示されてPopup$LightWeightWindowになる場合:SwingUtilities.getAncestorOfClass(JPopupMenu.class, header)で取得したJPopupMenuの位置を変更- JComboBoxのドロップダウンリストの高さをマウスドラッグで変更する
Reference
- JComboBoxのドロップダウンリストにヘッダ・フッタを追加する
- JToggleButtonからポップアップメニューを開く
- JComboBoxのドロップダウンリストの高さをマウスドラッグで変更する
- JWindowをマウスで移動