Tiled images in a swing

I have a task to prepare two windows with a swing. One contains a grid of squares with random numbers in them. Secondly, I need to load fragments of the tiled image, and then show them in the correct order, forming a tiled image.

Windows should look like this:

alt text http://img535.imageshack.us/img535/3129/lab8a.jpg

Ok, how to bite it? I used the swing only a few times to draw a few polylines, so in principle, I just theoretically now what to do.

So window number 1: I start by creating a Jframe for the window. Then I do for the loop and in it create 16 JLabels with random numbers in them? How to set margins between each tile and the whole window?

Window number 2: So, I start the same, but instead of loading numbers, I add images? Now, how to download an image from a file and then set it as a background?

+4
source share
1 answer

The following code describes JLabels using a GridLayout . The arguments for GridLayout are the following: rows, columns, horizontal clearance, vertical gap. In the example below, I have a width of 3 pixels between the labels both vertically and horizontally.

To use images instead of numbers, you can pass ImageIcon to the ImageIcon constructor instead of text.

However, it looks like you are making a game where the user should be able to click on tiles. This suggests that you might need to use buttons instead of shortcuts, but that is up to you :-)

 import java.awt.GridLayout; import javax.swing.*; import javax.swing.border.BevelBorder; public class FrameTest { public static void main(String[] args) { final JFrame f = new JFrame("Frame Test"); JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3)); for (int i = 0; i < 16; i++) { JLabel l = new JLabel("" + i, JLabel.CENTER); //JLabel l = new JLabel(new ImageIcon("image_file.png"), JLabel.CENTER); l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); l.setFont(l.getFont().deriveFont(20f)); panel.add(l); } f.setContentPane(panel); f.setSize(200, 200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } } 

enter image description here

+12
source

Source: https://habr.com/ru/post/1309146/


All Articles