当我在Jpanel

时间:2016-05-28 13:21:57

标签: java image swing jpanel

我正在用Java编写简单平台游戏的初始部分。我创建了一个名为entity的类,它扩展了JPanel并成功将其添加到窗口中。

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

/**
 * Created by bw12954 on 27/05/16.
 */
public abstract class Entity extends JPanel {

   private final SpriteSheet sprites;

   private       Point       location;
   private       Dimension   dimensions;

   public Entity(int x, int y, int w, int h, SpriteSheet sprites)
   {
      location     = new Point(x, y);
      dimensions   = new Dimension(w, h);
      this.sprites = sprites;
   }

   public Entity(int x, int y, int w, int h)
   {
      this(x, y, w, h, null);
   }

   @Override
   public Dimension getPreferredSize()
   {
      return dimensions;
   }

   public void setLocation(int x, int y)
   {
      location.setLocation(x, y);
   }

   /* Some code removed here for brevity */

   @Override
   public void paintComponent(Graphics g)
   {
      super.paintComponent(g);
      g.drawImage(sprites.get(),
                  (int)location.getX(),
                  (int)location.getY(),
                  null);
   }

}

如果我将这个直接添加到JFrame中,如下所示,那么图形会显示在窗口上,就像我期望的那样(注意Player是一个非常简单的实体子类)

public class Window {

   private JFrame window;

   public Window()
   {
      SwingUtilities.invokeLater(this::run);
   }

   private void run()
   {
      try {
         window = new JFrame();
         window.setDefaultCloseOperation(window.EXIT_ON_CLOSE);
         window.setLocationByPlatform(true);
         window.setUndecorated(true);
         Player p = new Player(0,0);
         window.add(p);
         window.setExtendedState(JFrame.MAXIMIZED_BOTH);
         window.setVisible(true);
      } catch (IOException e) {
         // TODO handle exception
         e.printStackTrace();
      }
   }
}

然而 - 当我创建一个名为World的类也扩展JPanel时,将那个添加到窗口中,然后在其构造函数中使用add()方法向其中添加一个新的Player ,它没有出现。有趣的是,如果我将setBackground()添加到Player / Entity的构造函数中,我可以看到实体应该是的有色方块。它只是drawImage似乎不起作用。

如果其他人知道这里发生了什么,那将非常感激!

1 个答案:

答案 0 :(得分:1)

  

如果我将它直接添加到JFrame,如下所示,那么图形会显示在窗口上,正如我所希望的那样

框架内容窗格的默认布局管理器是BorderLayout。在没有约束的情况下添加到框架的任何组件都将添加到" CENTER"这意味着组件会自动调整大小以填充整个空间。

  

但是 - 当我创建一个名为World的类,它也扩展了JPanel,而是将其添加到窗口中,然后在其构造函数中使用add()方法向其添加新的Player,它不会出现。

JPanel的默认布局管理器是FlowLayout,它尊重添加到其中的任何组件的首选大小,并将根据布局管理器的规则重置组件的位置。

  

有趣的是,如果我将setBackground()添加到Player / Entity的构造函数中,我可以看到实体应该是的有色方块。它只是drawImage似乎不起作用

可能是因为您的首选尺寸计算不正确且图像被截断。

  location     = new Point(x, y);
  dimensions   = new Dimension(w, h);

上述代码仅在Point为(0,0)时有效。更一般的案例代码应该是:

  location     = new Point(x, y);
  dimensions   = new Dimension(x + w, y + h);

因为您需要考虑实际绘制与组件相关的图像的位置。

因此,当您执行此操作时,您应该看到图像,但是您不会在正确的位置看到图像,因为布局管理器将覆盖该位置。

因此,您希望继续使用这种使用组件的方法来使用空布局,这意味着您将手动需要使用每个组件的setSize(...)和setLocation(...)。在这种情况下,组件的大小将是(w,h),您将使用以下方式绘制图像:

  g.drawImage(sprites.get(), 0, 0, this);

但是请注意,如果使用组件方法,则无需创建自定义组件。您可以将JLabelImageIcon一起使用。您可以在创建标签时指定图标。