所以我正在玩Swing和GUI,设计一个程序,其中我有一个包含10x10自定义JButton网格的JPanel . 我有1-10的数字水平索引,以及A-J(两个JLabels)的字母垂直索引 .
我使用带有WEST的垂直索引的BorderLayout,以及嵌套在CENTER中的11x10 GridLayout(为什么?因为这是我能想到的最简单的方法来完善水平索引号在其相应按钮列上方的位置) .
我有110个空间网格的前10个空格,用数字来索引列 - 这很好用 .
然后我使用一个11x1网格将垂直索引上的字母平均分配给WEST,以考虑网格顶部水平索引的额外插槽(见下图) .
我的问题是:每当我去填充垂直网格顶部的空白区域时,它会将新的JLabel放在底部,无论它是放在填充循环之前还是之后 .
结果如下:
这里是我用来填充循环的代码,在填充循环之前和之后添加了一个JLabel,以显示它是如何放置在底部的:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test {
private static void createAndDisplayGUI() {
// This panel contains the grid layout for the buttons
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
JPanel gridIndexLeft = new JPanel();
gridIndexLeft.setLayout(new GridLayout(12,1));
gridIndexLeft.add(new JLabel(" " + 0)); // Added a 0 here before fill loop to show where space should be
for (int i=0; i<10; i++) {
gridIndexLeft.add(new JLabel(" " + Character.toString((char)('J' - i))), SwingConstants.CENTER);
}
gridIndexLeft.add(new JLabel(" " + 0)); // And again here with same result
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(11,10));
for (int i=0; i<10; i++) {
buttons.add(new JLabel(" " + (10-i)), SwingConstants.CENTER);
}
for (int i=0; i<100; i++) {
buttons.add(new BattleshipButton());
}
center.add(gridIndexLeft, BorderLayout.WEST, SwingConstants.CENTER);
center.add(buttons, BorderLayout.CENTER, SwingConstants.CENTER);
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(center, BorderLayout.CENTER);
JFrame display = new JFrame();
display.setContentPane(content);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.setBackground(Color.GRAY);
display.setResizable(false);
display.setSize(300,325);
display.setLocation(500,190);
display.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndDisplayGUI();
}
});
}
}
我知道间距应该是11x1才能匹配,但我已经做了12x1以显示在循环之前和之后添加新的JLabel时会发生什么 .
任何输入将非常感谢!