3

Hi I am a bit new to Java and also to programming and in order to get beter at both the language and programming I decided to build a Monopoly Game.

I should also mention that this is my first project ever as a programmer so my way of doing things may be very well the worst way.

I am using the Swing library and each Rectangle is drawn using graphics

I am building the layout using rectangles and I was wondering if there is a way to add diferent Images to each rectangle?

Thank you

COD3BOY
  • 11,964
  • 1
  • 38
  • 56
Nistor Alexandru
  • 5,309
  • 9
  • 46
  • 71
  • 1
    Are you using Swing components? More information is required to answer this question appropriately. – mre Jan 06 '12 at 14:10
  • Please post (the important part of) your code. – Ishtar Jan 06 '12 at 14:10
  • @user985482: you should edit your question to give a bit more info. Are you using Swing and a layout manager to somehow tile your rectangles? It certainly *could* be done that way but for board games it's much more typical to build yourself one big image and process the elements/sprites/whatever inside that big image yourself (in your case each individual 'rectangle'). – TacticalCoder Jan 06 '12 at 14:12
  • 1
    Yes I am using swing Components – Nistor Alexandru Jan 06 '12 at 14:13

3 Answers3

2

It seems that you are trying to layout the board using Swing. If so, you can simply set the image icon of a JLabel.

JLabel label = new JLabel(new ImageIcon( image ));

However, personally I would design the Monopoly board as a JPanel and write custom paint methods for it. In that case, you could proceed by simply using the drawImage() method of the Graphics class.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
2

What you might need to do is to create each rectangle as a JPanel. You can then use the GridLayout to create your grid and then set the background of the JPanel as shown here.

You can also put a JLabel in each JPanel and use the setIcon() method as shown here.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
2

Create your panel with suitable layout, for ease I'd suggest you to use JPanels with borders rather than drawing rectangles.and follow these,

 image = ImageIO.read(new File(path));
  JLabel picLabel = new JLabel(new ImageIcon(image));

Yayy! Now your image is a swing component ! add it to a frame or panel or anything like you usually do! Probably need a repainting too , like

  jpanel.add(picLabel);
  jpanel.repaint(); 

Do this for as many pics you want :) happy coding...cheers :)

COD3BOY
  • 11,964
  • 1
  • 38
  • 56