1

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

Sam
  • 1,509
  • 3
  • 19
  • 28
  • Don't use setSize(). Override the setPreferredSize() method to reurn the Dimension(70, 70). – camickr Nov 07 '11 at 02:22
  • I did that but an error remains as it seems to have a padding/margin at the top which i cant get removed – Synbitz Prowduczions Nov 07 '11 at 13:40
  • Probably because you are using a FlowLayout which have 5 pixels of horizontal/vertical spacing between components. If you need more help post your SSCCE that demonstrates the problem. – camickr Nov 07 '11 at 15:03
  • I solved this problem by deleting setpreferredsize in all and adding a layout manager inside my Jpanel, which i did not do before... works perfectly now – Synbitz Prowduczions Nov 07 '11 at 19:33
  • Your issue is that you are attempting to output a 70x70px image into a 10x10 canvas, please include more code so that we can see what you are attempting to draw on. – blazingkin Nov 06 '11 at 21:49

1 Answers1

1
  • 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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1 See also this [Q&A](http://stackoverflow.com/questions/8017561/jcomponent-size-issue/8017763#8017763). – trashgod Nov 06 '11 at 23:13