开发者

JLabel withing another JLabel

I want to do a very simple thing with java swing and I'm not being able to.

I added a jLabel as it is the only object using java swing that can hold an image (using the icon property)...at least I wasn't able to set an image using other objects.

Now I want to add another jlabel in top of the first one with another image so it can be "clicked" independently from the "background" label. But whenever I try to add it using the graphical editor or by doing jLabel1.add(jLabel2) it doesn't work...it simply sets next to the label1 but not on top of it.

This is in order to do a java application like the Tic Tac Toe game...so I can have the background which are squares (first label) and the others the "X" and "O".

board

开发者_如何学运维

This might be the board and I want to put labels on each square so they can be the pieces.


Well you would probably want to set the label to use a GridLayout. Then you can add other JLabel components to each of the nine cells. When somebody clicks on the label you can then set the Icon to be whatever you want.


You can easily subclass JLabel and override the whole public void paint(Graphics g) with something like:

public void paint(Graphics g)
{
  Graphics2D g2 = (Graphics2D)g;

  // antialiasing, just because it's nicer
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

  g2.drawRect(..); // or instead
  g2.drawImage(..); // if you really want a border as an image

  g2.drawImage(..); // to draw the symbol in the middle


}

Otherwise you can set a border to the JLabel with the BorderFactory (mind about spacings between grid cells) and set just the image in the middle.

To layout elements use a GridLayout, they'll arrange them in a grid, forcing same sizes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜