将JPanel添加到JLayeredPane会导致绘制和调整大小无效

时间:2011-12-07 13:18:15

标签: java swing jlayeredpane

我正在尝试将一个JPanel(好吧,几个)添加到JLayeredPane。但是,当我这样做时,JPanel的paint组件方法似乎没有任何效果。下面是一个例子:

import javax.swing.*;
import java.awt.*;

public class Example {

    public static void main(String[] args) {

        // This Works as expected
        JFrame usingPanel = new JFrame();
        JPanel p = new JPanel();
        p.add(new BluePanel());
        usingPanel.setContentPane(p);
        usingPanel.pack();
        usingPanel.setVisible(true);

        // This makes the frame but does not paint the BluePanel
        JFrame usingLayer = new JFrame();
        JLayeredPane l = new JLayeredPane();
        l.setPreferredSize(new Dimension(200,200));
        l.add(new BluePanel(), JLayeredPane.DEFAULT_LAYER);
        JPanel p2 = new JPanel();
        p2.add(l);
        usingLayer.setContentPane(p2);
        usingLayer.pack();
        usingLayer.setVisible(true);
    }


   static class BluePanel extends JPanel{

        public BluePanel(){
            setPreferredSize(new Dimension(200,200));
        }

        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, 200, 200);
        }


    }


}

这是为什么?什么是可能的解决方案?

2 个答案:

答案 0 :(得分:8)

JLayeredPane没有LayoutManager,因此您需要自己设置面板的位置和大小。 请参阅tutorial

答案 1 :(得分:1)

  1. 您在屏幕上硬编码了大小,必须从

    更改
    g.fillRect(0, 0, 200, 200);
    

    g.fillRect(0, 0, getWidth(), getHeight());
    
  2. (一个小改动)添加方法

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }
    

    然后删除代码行setPreferredSize(new Dimension(200,200));