【问题标题】:JPanel ontop of other JPanelsJPanel 在其他 JPanel 之上
【发布时间】:2018-08-25 02:58:20
【问题描述】:

我想让一个 JPanel 在 java 中弹出另一个 JPanel。但是我在互联网上找不到任何有用的东西。我尝试使用绝对定位,但底层的按钮之类的东西通过顶层显示。 我上传了一张我想做的非常丑陋的图画。 有没有简单的方法可以做到这一点?

编辑: 我试着按照“Ulkra”的建议去做。这是代码和屏幕截图:

public class Main {

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(new Dimension(400, 400));

    JPanel panel = new JPanel();

    JPanel foregroundPanel = new JPanel();      
    foregroundPanel.setVisible(false);
    foregroundPanel.setBackground(Color.BLUE);
    foregroundPanel.setLayout(new BoxLayout(foregroundPanel, BoxLayout.Y_AXIS));

    JPanel backgroungPanel = new JPanel();      
    backgroungPanel.setBackground(Color.RED);
    backgroungPanel.setLayout(new BoxLayout(backgroungPanel, BoxLayout.Y_AXIS));

    for (int i = 0; i < 10; i++) {
        backgroungPanel.add(new JButton("BackgroundBtn " + i));
    }       
    foregroundPanel.add(new JButton("ForegroundBtn 1"));

    JButton makeVisibleBtn = new JButton("+");
    makeVisibleBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            foregroundPanel.setVisible(true);
        }
    });     
    backgroungPanel.add(makeVisibleBtn);        

    JButton makeInvisibleBtn = new JButton("-");
    makeInvisibleBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            foregroundPanel.setVisible(false);
        }
    });     
    foregroundPanel.add(makeInvisibleBtn);      

    panel.add(backgroungPanel);
    panel.add(foregroundPanel);

    frame.add(panel);
}

}

【问题讨论】:

  • 你尝试过的代码在哪里?
  • 请出示您的代码并给我们一个确切的问题来帮助您。
  • 使用未修饰的 JDialog 作为弹出窗口。
  • 未修饰的 JDialog 正是我所需要的。谢谢
  • 我发现该解决方案存在问题。 JDialog 不与主 JFrame 一起移动。它可以以某种方式固定到 JFrame 的位置吗?

标签: java swing layout jpanel overlap


【解决方案1】:

为此,您必须使用面板(如果您使用的是 NetBeans,则可以在 Swing Containers 中找到它)并且在 Frame 的构造函数中,您必须将其设置为不可见,因此您需要按钮才能看到它:(在本例中,我将面板称为“jPanel1”,并在其中放置了一个按钮)

public Main() {
    initComponents();
    jPanel1.setVisible(false);//<-- This!
    this.setLocationRelativeTo(null);
}

然后,您创建按钮以“激活它”,但此代码位于:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jPanel1.setVisible(true);
}  

(当然,如果您想将其设置为不可见,您只需执行与构造函数中相同的操作即可)。

我对其进行了测试,它可以工作:(Imgur 不工作,所以请原谅我必须使用 postimg.org) https://postimg.org/gallery/1z6fpajva/

现在您可以放置​​一个边框,以便将您的新面板与其他框架区分开来: https://postimg.org/image/mdpf7hvxx/

【讨论】:

  • 感谢您的快速答复。该解决方案的问题在于,隐形面板必须一直存在,挡住了空间。我希望它高于一切。就像在 Gmail 中一样,当您写一封新邮件时。布局的其余部分有一个弹出窗口,不会干扰它。
猜你喜欢
  • 1970-01-01
  • 2014-05-20
  • 2017-04-18
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多