Nistor Alexandru
Nistor Alexandru

Reputation: 5393

Java rectangle images

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

Upvotes: 3

Views: 653

Answers (3)

COD3BOY
COD3BOY

Reputation: 12092

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 :)

Upvotes: 2

npinti
npinti

Reputation: 52185

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.

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36456

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.

Upvotes: 2

Related Questions