防止 JPopupMenu 被任务栏覆盖

3
我该如何让我的 JPopupMenu 出现在任务栏上方?换句话说,我该如何强制它遵守屏幕限制,以免被覆盖?以 Android Studio 的弹出菜单为例:

正常位置:

enter image description here

当我将窗口拖到靠近底部任务栏时,弹出菜单会 "适应 " 并出现在其上方:

现在是我的测试案例:

正常位置:

接近任务栏(你可以看到,与 Android Studio 不同,弹出菜单的一部分消失在任务栏下面):

测试案例代码:

Test.java

public class Test extends javax.swing.JFrame {

    public Test() {
        initComponents();
    }

    public void initUI() {

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        btnMenu = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnMenu.setText("Click for Menu");
        btnMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMenuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(291, Short.MAX_VALUE)
                .addComponent(btnMenu)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(266, Short.MAX_VALUE)
                .addComponent(btnMenu)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void btnMenuActionPerformed(java.awt.event.ActionEvent evt) {                                        
        JPopupMenu menu = new JPopupMenu();
        menu.add(new PopBody());
        menu.show(this, btnMenu.getLocation().x - 95, btnMenu.getLocation().y + 60);
    }                                       

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        }
        java.awt.EventQueue.invokeLater(() -> new Test().setVisible(true));
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnMenu;
    // End of variables declaration                   
}

PopBody.java

public class PopBody extends javax.swing.JPanel {

    public PopBody() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        lblBody = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();

        lblBody.setText("Panel body");

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addComponent(lblBody)
                .addContainerGap(92, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnOK)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addComponent(lblBody)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
                .addComponent(btnOK)
                .addContainerGap())
        );
    }// </editor-fold>                        

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {                                      

    }                                     


    // Variables declaration - do not modify                     
    private javax.swing.JButton btnOK;
    private javax.swing.JLabel lblBody;
    // End of variables declaration                   
}

使 JPopupMenu 成为 重型组件 - undefined
@VGR 那会有什么效果呢? - undefined
几乎所有的Swing组件默认都是轻量级的,这意味着它们不是本地屏幕分配;相反,Swing在窗口内部绘制它们。重量级组件使用本地矩形区域,因此可以覆盖其他本地元素。权衡之处在于,重量级组件使用更多的系统资源,尽管这可能比二十年前更少成为一个问题。 - undefined
我刚刚在JPopup上调用了menu.setLightWeightPopupEnabled(false);,它的行为和之前一样。 - undefined
1个回答

2

我自己遇到了这个问题,并想出了这个解决方案。

private void btnMenuActionPerformed(ActionEvent evt) {
    JPopupMenu popup = new JPopupMenu();
    popup.add(new PopBody());
    popup.pack();

    int popUpHeight = popup.getPreferredSize().height;
    //determines the max available size of the screen
    Rectangle windowBounds = GraphicsEnvironment.
        getLocalGraphicsEnvironment().getMaximumWindowBounds();
    Point invokerPosition = ((Component)evt.getSource()).getLocationOnScreen();

    if (invokerPosition.y + popUpHeight > windowBounds.height) {
        //get the negative margin and use it as the y-offset
        popup.show(this, 0, windowBounds.height - (invokerPosition.y + popUpHeight));
    }
    else {
        popup.show(this, 0, 0);
    }
}

我不确定你硬编码的偏移量是否正确。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接