【问题标题】:Layering JPanels with the bottom layer a background image将 JPanel 分层,底层为背景图像
【发布时间】:2012-10-25 18:51:56
【问题描述】:

我正在尝试编写棋盘游戏。我想加载游戏板的图像,然后在其上加载透明网格。我编写了一个自定义面板来绘制图像并将其作为级别 0 添加到分层面板中。然后我使用 GridLayout 制作了一个 JPanel 并将其添加到级别 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); 

【问题讨论】:

  • 为什么不将board的布局管理器设置为BorderLayout,并在其中添加grid panel呢?

标签: java swing jpanel paintcomponent jlayeredpane


【解决方案1】:
  • 尝试像这样调用super.paintComponent(..)

    @Override
    protected void paintComponent(Graphics g) 
    {
       super.paintComponent(g);
       g.drawImage(image, 0, 0, null);
    }
    
  • 不要调用JFrame#setSize(..) 使用appropriate LayoutManager 并覆盖JPanelgetPrefferedSize(..),这将返回正确的大小,然后在设置可见之前在JFrame 实例上调用pack()

以下是您的 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);
     }

}

【讨论】:

  • 感谢您对设置首选尺寸的提醒。但是它仍然只是绘制一个白屏而不是图像
  • 我的一个朋友说他已经成功了。我目前无法访问代码。谢谢大家!
猜你喜欢
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多