我正在使用Swing編寫GUI。我使用GridBagLayout
在網格中顯示多個JLabels
(基本上像棋盤)。只要我使用JLabel
而不是JLabel
派生的自制標籤類,GridBagLayout
將堆疊JPanel
左上角的每個標籤。GridBagLayout在使用Jlabel的自定義子類時堆疊標籤
我的子類TileLabel
不正確,或者我沒有正確使用佈局和約束。我想最後一個,因爲我看不出在這樣一個最小的子類中會有什麼問題。
這是它的外觀採用JLabel
(L代表一個標籤):
(MenuBar)
L L L L L L L L L
L L L L L L L L L
L L L L L L L L L
這是它的外觀採用TileLabel
(S代表堆疊的所有標籤):
(MenuBar)
S
這是我的簡單子類JLabel:
import javax.swing.JLabel;
public class TileLabel extends JLabel {
private static final long serialVersionUID = 6718776819945522562L;
private int x;
private int y;
public TileLabel(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
而這是GUI分類秒。我標出了我使用自定義標籤導致佈局問題的三條線。
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainGUI extends JPanel {
private static final long serialVersionUID = -8750891542665009043L;
private JFrame frame;
private MainMenuBar menuBar;
private TileLabel[][] labelGrid; // <-- LINE 1
private GridBagConstraints constraints;
private int gridWidth;
private int gridHeight;
// Basic constructor.
public MainGUI(int frameWidth, int frameHeight) {
super(new GridBagLayout());
constraints = new GridBagConstraints();
buildFrame(frameWidth, frameHeight);
buildLabelGrid(frameWidth, frameHeight);
}
// Builds the frame.
private void buildFrame(int frameWidth, int frameHeight) {
menuBar = new MainMenuBar();
frame = new JFrame("Carcasonne");
frame.getContentPane().add(this);
frame.setJMenuBar(menuBar);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(frameWidth, frameHeight);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(new Color(165, 200, 245));
}
// Creates the grid of labels.
private void buildLabelGrid(int frameWidth, int frameHeight) {
gridWidth = frameWidth/100;
gridHeight = frameHeight/100;
labelGrid = new TileLabel[gridWidth][gridHeight]; // <-- LINE 2
for (int x = 0; x < gridWidth; x++) {
for (int y = 0; y < gridHeight; y++) {
labelGrid[x][y] = new TileLabel(x, y); // <-- LINE 3
constraints.gridx = x;
constraints.gridy = y;
add(labelGrid[x][y], constraints); // add label with constraints
}
}
}
// sets the icon of a specific label
public void paint(Tile tile, int x, int y) {
if (x >= 0 && x < gridWidth && y >= 0 && y < gridHeight) {
labelGrid[x][y].setIcon(tile.getImage());
} else {
throw new IllegalArgumentException("Invalid label grid position (" + x + ", " + y + ")");
}
}
// Just to test this GUI:
public static void main(String[] args) {
MainGUI gui = new MainGUI(1280, 768);
Tile tile = TileFactory.createTile(TileType.Road);
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 7; y++) {
gui.paint(tile, x, x);
}
}
}
}
問題在哪裏?
*「基本上像一個棋盤」 *參見[製作一個健壯的,可調整大小的搖擺象棋GUI(http://stackoverflow.com/q/21142686/418556),用於對佈局的提示和用組分(例如每個網格廣場使用'JButton'而不是'JLabel')。 –