Java PaintComponent 的大小和位置在扩展 Jpanel 的抽象类的子类中

发布于 2024-12-14 03:52:09 字数 960 浏览 0 评论 0 原文

我正在构建一个简单的国际象棋游戏,并且一直致力于尝试在面板上绘制图形

我准备好了一个棋盘,棋盘上有面板。这些面板的尺寸为 70x70px,接下来我想做的就是使用整个表面来绘制棋子。

我创建了一个扩展 JPanel 的抽象类 Pieces。

public abstract class Piece extends JPanel

其中一件当然是 Pawn :

public class Pawn extends Piece

在 Pawn 类中我有绘画组件:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    int w = getWidth();
    int h = getHeight();
    g.setColor(Color.GREEN);
    g.fillOval(0, 0, w, h);
    System.out.println("height:"+h+" width:"+w);
}

这似乎不起作用。输出打印高度 = 10px 和宽度 = 10px; ....但应该是70px和70px。我还看到绿色椭圆形画在 10x10 正方形内,该正方形位于我的面板内...

我尝试了 setSize(70,70) ,但它并没有真正起作用... 我也尝试过 SetPreferredSize 但它也没有真正起作用。 我真的很想保留我的抽象类和子类...

@@@ 编辑@@@ 我再次使用了 setPreferredSize,现在我可以在 Jpanel 上实际绘制绿色圆圈了。但仍然存在错误,因为它不是所使用的 Jpanel 的整个表面...顶部仍然有一个间隙,截图:
http://imgur.com/INVj4

I'm building a simple chess game and am stuck on trying to paint drawings on a Panel

I have a board ready and on the board there are panels. those panels are 70x70px and next thing i want to do is use THAT ENTIRE SURFACE to draw chess pieces.

i made an abstract class Pieces that extends JPanel.

public abstract class Piece extends JPanel

One of the pieces is ofcourse, a Pawn :

public class Pawn extends Piece

in the Pawn class I have paint component :

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    int w = getWidth();
    int h = getHeight();
    g.setColor(Color.GREEN);
    g.fillOval(0, 0, w, h);
    System.out.println("height:"+h+" width:"+w);
}

This does not seem to work. the output prints height = 10px and width = 10px; .... but it is suposed to be 70px and 70px. I also see the green oval painted inside a 10x10 square, which is inside my Panel...

I tried a setSize(70,70) which does not realy do the trick...
I also tried SetPreferredSize but well It did not really work out either.
I really want to keep my abstract class and subclasses...

@@@ EDIT @@@
I've used setPreferredSize again and I can now actually draw my green circle on the Jpanel. but an error remains as in it is not the whole surface of the Jpanel Used... there remains a gap at the top , a screenshot:
http://imgur.com/INVj4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独﹏钓一江月 2024-12-21 03:52:09

示例 JComponent 与 setXxxSize

  • if you only to set Background to Color.GREEN then extends JComponent,

  • if you want to add only Image then look for Icon in JLabel, note JLabel is transparent, non-opaque by default,

  • any JComponent can returns setXxxSize,

  • not all LayoutManagers accepted setXxxSize,

example JComponent with setXxxSize

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文