overlapping JPanels in the GUI

回眸只為那壹抹淺笑 提交于 2019-12-11 18:52:21

问题


I am using BorderLayout in my application. I have a main panel to which I add two JPanels at the center. I want one of them to be transparent. My code is :

 mainPanel = new JPanel();
 mainPanel.setLayout(new BorderLayout());
 mainPanel.add(getGraphPaneScrollPane(), BorderLayout.CENTER);
 mainPanel.add(getSituationPanel(), BorderLayout.CENTER);

Code for these two functions is :

public JScrollPane getGraphPaneScrollPane() {
    if (graphPaneScrollPane == null) {
        graphPaneScrollPane = new JScrollPane();
        graphPaneScrollPane.setViewportView(getGraphEditorPane());
    }
    return graphPaneScrollPane;
}
private JScrollPane getSituationPanel(){
    if(situationPanel == null){
        logs.debug("Initializing Situation Panel");

        situationPanel = new JScrollPane();

        situationLabel = new JLabel("");
        situationLabel.setVerticalTextPosition(JLabel.BOTTOM);
        situationLabel.setHorizontalTextPosition(JLabel.CENTER);
        situationLabel.setVerticalAlignment(JLabel.TOP);
        situationLabel.setHorizontalAlignment(JLabel.CENTER);
        situationLabel.setBorder(BorderFactory.createTitledBorder(""));
        situationLabel.setBackground(Color.WHITE);
        situationLabel.setOpaque(true);
        situationLabel.setVerticalAlignment(SwingConstants.TOP);

        situationPanel.setViewportView(situationLabel); 

    } 

    return situationPanel;
}

Now I want situationPanel to be transparent and getGraphPaneScrollPane to be above that in the GUI, because getGraphPaneScrollPane is the canvas, which I use to draw nodes.


回答1:


I want situationPanel to be transparent and getGraphPaneScrollPane to be above that in the GUI,

The panel that is on top is the panel that needs to be transparent. If the panel on top is opaque then you will never see the panel under the top panel.

So making changes to the layout is the last thing I want.

Well that is what you are going to need to do. You can't just add two panels to one panel and expect it to work the way you want it to. Most Swing layout managers are designed to lay out components in two dimensions, not on top of one another.

Your current code is:

mainPanel.setLayout(new BorderLayout());
mainPanel.add(getGraphPaneScrollPane(), BorderLayout.CENTER);
mainPanel.add(getSituationPanel(), BorderLayout.CENTER);

You could try using the OverlayLayout, it is designed to lay out panels on top of on another. The code should be something like:

JPanel overlay = new JPanel();
overlay.setLayout( new OverlayLayout(overlay) );
overlay.add(getSituationPanel(), BorderLayout.CENTER); // add transparent panel first
overlay.add(getGraphPaneScrollPane(), BorderLayout.CENTER);
mainPanel.setLayout(new BorderLayout()); 
mainPanel.add(overlay);


来源:https://stackoverflow.com/questions/16555080/overlapping-jpanels-in-the-gui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!