Swing Overlapping components

后端 未结 3 1669
悲&欢浪女
悲&欢浪女 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: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);
    }   
    

提交回复
热议问题