问题
I have task to prepare two windows with swing. One contains grid of squares, with random numbers in them. In second I need to load pieces of tiled image and then show them in the correct order, forming tiled image.
Windows should look like this :
alt text http://img535.imageshack.us/img535/3129/lab8a.jpg
Okay so how to bite this? I've used swing only few times to draw some 2d polylines, so basically I just theoretically now what to do.
Ok, so window number 1: I start with creating Jframe for the window. Then I do for 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 can I load image from file and then set it as background?
回答1:
The following code lays out the JLabels using the GridLayout
. The arguments to the GridLayout
are the following: rows, cols, horizontal gap, vertical gap. In the example below I have 3 pixels wide gap between labels both vertically and horizontally.
To use images instead of numbers, you could pass an ImageIcon
to the constructor of the JLabel instead of the text.
However, it looks like your doing a game where the user should be able to click on the tiles. This suggests that you perhaps should use buttons instead of labels, but it's 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);
}
}
来源:https://stackoverflow.com/questions/2791402/tiled-images-in-swing