java - 如何修复 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);
,则菜单显示没有任何问题。
像这样
解决方案
问题是由于根窗格使用错误,必须将组件放在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);
}
推荐阅读
- vba - ContentControl 是否有 OnClick 功能
- jwt - Azure KeyVault - 如何使用节点获取存储在 keyvault 中的私钥?
- javascript - 对象数组的嵌套过滤
- java - Android - 两个 Activity 无法从九个中获得 Bundle Extras
- javascript - d3 树 - 使用 nodeSize 根据树大小自动缩放
- python - 不可散列的类型:将 GPS 数据加载到 pandas 数据帧时的“SimpleTZ”
- excel - Excel 中的 CSV UTF-8 与普通 CSV
- nativescript - (NATIVESCRIPT) 已弃用的 API 使用 - Apple 将停止接受使用 UIWebView API 的应用提交
- excel - 数据透视表类的 AddField 方法在宏上失败
- html - CSS 在图像旁边放置文本并使其具有移动响应性