我正在构建一个简单的国际象棋游戏,并且一直致力于尝试在面板上绘制图形
我准备好了一个棋盘,棋盘上有面板。这些面板的尺寸为 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 的整个表面...顶部仍然有一个间隙,截图:
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:
发布评论
评论(1)
如果您仅将
Background
设置为Color.GREEN
,则扩展JComponent
,如果您只想添加图像,然后在 JLabel 是透明的,默认情况下
非不透明
,任何JComponent 可以返回
setXxxSize
,不是所有 LayoutManagers 接受
setXxxSize
,示例 JComponent 与 setXxxSize
if you only to set
Background
toColor.GREEN
then extendsJComponent
,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