首页 > 解决方案 > 如何修复 JPopupMenu 隐藏在边框的插图内?

问题描述

我需要在对话框中显示一个菜单。但是,当 JPopupMenu 隐藏在边框内时,barder 插图很大。

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

public class PopupMenuBorderInsetsBug {
    public static void main(String[] args) {
        JDialog popupDialog = new JDialog();
        popupDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        popupDialog.getRootPane().setBorder(new BorderWithInsets(Color.RED));

        JButton btnShowMenu = new JButton("Show Menu");

        JPopupMenu menu = new JPopupMenu();
        menu.add(new JMenuItem("Menu Item"));

        btnShowMenu.addActionListener(e -> menu.show(btnShowMenu, 0, btnShowMenu.getHeight()));
        popupDialog.add(btnShowMenu);

        popupDialog.pack();
        popupDialog.setVisible(true);
    }

    private static class BorderWithInsets extends LineBorder {
        public BorderWithInsets(Color color) {
            super(color);
        }

        @Override
        public Insets getBorderInsets(Component c) {
            return new Insets(10, 10, 30, 10);
        }
    }
}

上面的代码创建了一个对话框,当单击按钮菜单时应该会出现,但它会隐藏在边框插图内。 像这样

如果边框的插图如此更改return new Insets(10, 10, 10, 10);,则菜单显示没有任何问题。 像这样

标签: javaswing

解决方案


问题是由于根窗格使用错误,必须将组件放在JDialog的contentPane中。

查看中的更改main

public static void main(String[] args) {
    JDialog popupDialog = new JDialog();
    popupDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    //Use a JPanel as container and set insets and content on it
    JPanel content=new JPanel();
    content.setBorder(new BorderWithInsets(Color.RED));

    JButton btnShowMenu = new JButton("Show Menu");

    JPopupMenu menu = new JPopupMenu();
    menu.add(new JMenuItem("Menu Item"));

    btnShowMenu.addActionListener(e -> menu.show(btnShowMenu, 0, btnShowMenu.getHeight()));
    
    content.add(btnShowMenu);

    //Set the panel as contentPane for the dialog
    popupDialog.setContentPane(content);
    popupDialog.pack();
    popupDialog.setVisible(true);
}

推荐阅读