Java Swing - 如何在另一个面板上显示一个面板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/852631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:11:22  来源:igfitidea点击:

Java Swing - how to show a panel on top of another panel?

javaswingdialogjpanelz-index

提问by Pool

I wish to have an internal (non window) dialog to ask for member input. I would like the dialog to be placed centrally on an existing JPanel.

我希望有一个内部(非窗口)对话框来要求成员输入。我希望将对话框集中放置在现有的 JPanel 上。

I have looked at layeredpanesand these seem unusable due to only having a single layout manager (or no layout manager) across all the panes. I guess I could try to override JLayeredPane and provide a custom layout but this seems extreme.

我查看了layeredpanes,由于所有窗格中只有一个布局管理器(或没有布局管理器),这些似乎无法使用。我想我可以尝试覆盖 JLayeredPane 并提供自定义布局,但这似乎很极端。

Glass panesdon't seem to be appropriate either.

玻璃板似乎也不合适。

How can this be done? Is there no usable concept of z-indexes in Swing?

如何才能做到这一点?Swing 中没有可用的 z-index 概念吗?

EDIT

编辑

The reason Layered Panes weren't appropriate was due to the lack of a layout manager per layer. The panel is resizeable, Panel A should stay at 100% of area and Panel B should stay centralized.

分层窗格不合适的原因是每层缺少布局管理器。面板可调整大小,面板 A 应保持在 100% 的区域,面板 B 应保持居中。

采纳答案by willcodejavaforfood

I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.

我认为 LayeredPane 是您最好的选择。您需要第三个面板来包含 A 和 B。第三个面板将是 layeredPane,然后面板 A 和 B 仍然可以有一个不错的 LayoutManagers。您所要做的就是将 B 置于 A 的中心,并且 Swing 小道中有很多关于如何做到这一点的示例。没有 LayoutManager 的定位教程

public class Main {
    private JFrame frame = new JFrame();
    private JLayeredPane lpane = new JLayeredPane();
    private JPanel panelBlue = new JPanel();
    private JPanel panelGreen = new JPanel();
    public Main()
    {
        frame.setPreferredSize(new Dimension(600, 400));
        frame.setLayout(new BorderLayout());
        frame.add(lpane, BorderLayout.CENTER);
        lpane.setBounds(0, 0, 600, 400);
        panelBlue.setBackground(Color.BLUE);
        panelBlue.setBounds(0, 0, 600, 400);
        panelBlue.setOpaque(true);
        panelGreen.setBackground(Color.GREEN);
        panelGreen.setBounds(200, 100, 100, 100);
        panelGreen.setOpaque(true);
        lpane.add(panelBlue, new Integer(0), 0);
        lpane.add(panelGreen, new Integer(1), 0);
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }

}

You use setBounds to position the panels inside the layered pane and also to set their sizes.

您可以使用 setBounds 将面板放置在分层窗格内并设置它们的大小。

Edit to reflect changes to original postYou will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.

编辑以反映对原始帖子的更改您将需要添加组件侦听器,以检测父容器何时调整大小,然后动态更改面板 A 和 B 的边界。

回答by AlbertoPL

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

在现有 JPanel 上使用 1 x 1 GridLayout,然后将您的面板添加到该 JPanel。1 x 1 的 GridLayout 的唯一问题是您将无法在 JPanel 上放置其他项目。在这种情况下,您必须找出合适的布局。您使用的每个面板都可以使用自己的布局,这样就不会有问题。

Am I understanding this question correctly?

我是否正确理解了这个问题?

回答by Yishai

JOptionPane.showInternalInputDialog probably does what you want. If not, it would be helpful to understand what it is missing.

JOptionPane.showInternalInputDialog 可能会做你想要的。如果没有,了解它缺少什么会很​​有帮助。

回答by mavroprovato

You can add an undecorated JDialog like this:

您可以像这样添加一个未修饰的 JDialog:

import java.awt.event.*;

import javax.swing.*;

public class TestSwing {
  public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame("Parent");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setVisible(true);

    final JDialog dialog = new JDialog(frame, "Child", true);    
    dialog.setSize(300, 200);
    dialog.setLocationRelativeTo(frame);
    JButton button = new JButton("Button");
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        dialog.dispose();
      }
    });
    dialog.add(button);
    dialog.setUndecorated(true);
    dialog.setVisible(true);
  }
}

回答by CarlG

I just thought that I'd add that there isa notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]

我只是想,我想补充一点,还有就是Z顺序的一个Swing概念,参见[java.awt.Component中#setComponentZOrder] [1]

which affects the positions of a component in its parents component array, which determines the painting order.

这会影响组件在其父组件数组中的位置,从而确定绘制顺序。

Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabledto return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)

请注意,您应该覆盖javax.swing.JComponent#isOptimizedDrawingEnabled以在父容器中返回 false 以使重叠的组件正确重绘,否则它们的重绘会相互破坏。(除非 isOptimizedDrawingEnabled 返回 false,否则 JComponents 假定没有重叠的子项)

[1]: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#setComponentZOrder(java.awt.Component, int)

[1]:http: //java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#setComponentZOrder(java.awt.Component, int)

回答by AgataB

There's another layout manager that may be of interest here: Overlay LayoutHere's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.

这里还有另一个可能感兴趣的布局管理器:Overlay Layout这是一个简单的教程:OverlayLayout:用于对位于彼此之上的组件进行布局管理。Overlay Layout 允许您将面板放置在彼此的顶部,并在每个面板内设置一个布局。您还可以分别设置每个面板的大小和位置。

(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)

(我在几年前回答这个问题的原因是因为我偶然发现了同样的问题,而且我在 StackOverflow 上看到很少提到 Overlay Layout,虽然它似乎有很好的文档记录。希望这可以帮助某人其他一直在寻找它的人。)