1

我正在尝试编写棋盘游戏。我想加载游戏板的图像,然后在其上加载透明网格。我编写了一个自定义面板来绘制图像并将其添加到分层面板中作为级别 0。然后我JPanel使用 aGridLayout并将其添加到级别 1。然后将分层窗格放入滚动窗格中以说明背景图像是有点大。希望在任何给定时间让大部分网格都是透明的,但是如果玩家棋子进入一个正方形,那么我会将那个正方形设置为代表该棋子的颜色。但是,当我将顶部面板设置为透明时(通过调用setOpaque(false)),我只是得到一个白色背景,没有图像存在。为什么是这样?

public class ImagePanel extends JPanel
{
   private Image image;

   public ImagePanel(Image image) 
   {
      this.image = image;
      this.setPreferredSize(new Dimension(936,889));
    }

   protected void paintComponent(Graphics g) 
   {
      g.drawImage(image, 0, 0, null);
   }
}

这是创建面板并嵌套它们的主程序中的代码。背板是外框。稍后它是 setVisible ,所以这不是问题。

BufferedImage boardImage = null;
       try
       {
           boardImage = ImageIO.read(new File("Clue Board.jpg"));
       }
       catch(IOException e)
       {

       }

   ImagePanel background = new ImagePanel(boardImage); //load clue board image

   JPanel gameBoard = new JPanel (new GridLayout(24,24)); //yet to add actual squares
   gameBoard.setSize(936,889);
   gameBoard.setOpaque(false);

   JLayeredPane lPane = new JLayeredPane();
   lPane.setPreferredSize(new Dimension(936,889));
   lPane.add(background, new Integer(0));
   lPane.add(gameBoard, new Integer(1));

   JScrollPane layerScroller = new    JScrollPane(lPane,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
   backBoard.add(layerScroller, BorderLayout.CENTER); 
4

1 回答 1

2
  • 尝试这样调用super.paintComponent(..)

    @Override
    protected void paintComponent(Graphics g) 
    {
       super.paintComponent(g);
       g.drawImage(image, 0, 0, null);
    }
    
  • 不要调用JFrame#setSize(..)使用适当LayoutManager的覆盖getPrefferedSize(..)JPanel它会返回正确的大小,然后在将其设置为可见之前调用pack()实例JFrame

ImagePanel这是您的班级应该如何看待的示例:

public class ImagePanel extends JPanel
{
    private int width,height;
    private Image image;

    public ImagePanel(Image image) 
    {
          this.image = image;

          //so we can set the JPanel preferred size to the image width and height
          ImageIcon ii = new ImageIcon(this.image);
          width = ii.getIconWidth();
          height = ii.getIconHeight();
     }

     //so our panel is the same size as image
     @Override
     public Dimension getPreferredSize() {
          return new Dimension(width, height);
     }

     @Override
     protected void paintComponent(Graphics g) 
     {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
     }

}
于 2012-10-25T18:54:57.207 回答