图形没有在JLayeredPane中显示(java swing)

时间:2011-10-29 12:13:20

标签: java swing graphics jlayeredpane

我正在尝试根据用户输入逐步构建图像。我正在尝试做的是创建一堆图形并将它们添加为图层但是我遇到了一些问题,因为它们不会显示出来。这是我正在使用的代码:

public class ClassA 
{
    protected final static int dimesionsY = 1000;
    private static int dimesionsX;
    private static JFrame window;
    private static JLayeredPane layeredPane;

    public void init()
    {
        window = new JFrame("Foo");
        dimesionsX = // some user input
        window.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
        window.setLayout(new BorderLayout());

            layeredPane = new JLayeredPane();
        layeredPane.setBounds(0, 0, dimesionsX, dimesionsY);
        window.add(layeredPane, BorderLayout.CENTER);

            ClassB myGraphic = new ClassB();    
        myGraphic.drawGraphic();

        layeredPane.add(myGrpahic, new Integer(0), 0);

        window.pack();
        window.setVisible(true);
    }
}



public class ClassB extends JPanel
{
    public void drawGraphic()
    {
        repaint();
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.setColor(Color.BLACK);
        g.fillRect(10, 10, 100, 100);
    }
}

然而,我的图形似乎没有出现,我不明白为什么。我还尝试首先将其添加到JPanel,然后将JPanel添加到JLayeredPane,但这也不起作用。

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:13)

如果将组件添加到JLayeredPane,就像使用容器将其添加到空布局一样:您必须完全指定组件的大小和位置。

如,

import java.awt.*;

import javax.swing.*;

public class ClassA {
   protected final static int dimesionsY = 800;
   protected final static int dimesionsX = 1000; //!!
   private static JFrame window;
   private static JLayeredPane layeredPane;

   public void init() {
      window = new JFrame("Foo");
      // !! dimesionsX = // some user input

      //!! window.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
      window.setLayout(new BorderLayout());

      layeredPane = new JLayeredPane();
      //!! layeredPane.setBounds(0, 0, dimesionsX, dimesionsY);
      layeredPane.setPreferredSize(new Dimension(dimesionsX, dimesionsY));
      window.add(layeredPane, BorderLayout.CENTER);

      ClassB myGraphic = new ClassB();
      myGraphic.drawGraphic();

      myGraphic.setSize(layeredPane.getPreferredSize());
      myGraphic.setLocation(0, 0);
      //!! layeredPane.add(myGraphic, new Integer(0), 0);
      layeredPane.add(myGraphic, JLayeredPane.DEFAULT_LAYER);

      window.pack();
      window.setVisible(true);
   }

   public static void main(String[] args) {
      new ClassA().init();
   }
}

class ClassB extends JPanel {
   public void drawGraphic() {
      repaint();
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);

      g.setColor(Color.BLACK);
      g.fillRect(10, 10, 100, 100);
   }
}

答案 1 :(得分:1)

请参阅 The Java Tutorials 中的Laying Out Components in a Layered Pane

此外,有时您需要设置首选尺寸:

layeredPane.setPreferredSize(new Dimension(width, height));