Swing Overlapping components

后端 未结 3 1631
悲&欢浪女
悲&欢浪女 2021-01-06 14:06

I have two AWT components in a Frame, Panel A and Panel B. I would like panel A to be sized to the height width of the frame (and maintain that size on frame resize), but I

相关标签:
3条回答
  • 2021-01-06 15:04

    Maybe I'm missing something. If B is fixed size and is at (0,0) and A runs the full width what's the use of having B overlap A? You will never see anything that is placed under B.

    I can't think of any of the default layout managers, but Orielly has this one you can use: relative layout manager (see source code link) with documentation. I haven't used it in a long while, but it should beat managing the layout yourself.

    0 讨论(0)
  • 2021-01-06 15:09

    Take a look at JLayeredPanes. Here is a tutorial.

    edit:

    If panelA is an AWT component, you will be hard pressed to get panelB to overlap. From Sun's article entitled Mixing Heavy and Light Components:

    Do not mix lightweight (Swing) and heavyweight (AWT) components within a container where the lightweight component is expected to overlap the heavyweight one.

    However, if you are looking to have panelA fill the Frame completely, why not add panelB as a component of panelA?

    Edit2:

    If you can make panelB a heavyweight component, then you can use the JLayeredPane.

    Here is a quick mockup that shows how:

    public static void main(String[] args){
        new GUITest();
    }
    
    public GUITest() {
        frame = new JFrame("test");
        frame.setSize(300,300);
        addStuffToFrame();
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                frame.setVisible(true);
            }
        });
    
    }       
    
    private void addStuffToFrame() {    
        Panel awtPanel = new Panel();
        awtPanel.setBackground(Color.blue);
        //here you can fool around with the pane:
        //first, you can see how the layered pane works by switching the 
        //DEFUALT_LAYER and PALLETTE_LAYER back and forth between the two panels
        //and re-compiling to see the results
        awtPanel.setSize(200,300);
        frame.getLayeredPane().add(awtPanel, JLayeredPane.DEFAULT_LAYER);
        //next you comment out the above two lines and 
        //uncomment the following line. this will give you the desired effect of
        //awtPanel filling in the entire frame, even on a resize. 
        //frame.add(awtPanel);
    
        Panel awtPanel2 = new Panel();
        awtPanel2.setBackground(Color.red);
        awtPanel2.setSize(300,200);
        frame.getLayeredPane().add(awtPanel2,JLayeredPane.PALETTE_LAYER);
    }   
    
    0 讨论(0)
  • 2021-01-06 15:12

    Your best bet is to have your own LayoutManager. The easiest way is probably to extend or proxy BorderLayout, and have a specific case to layout panel B.

    0 讨论(0)
提交回复
热议问题