所以我玩弄Swing和GUI,設計一個程序,其中我有一個包含10x10自定義網格的JPanel Jbutton將。我有一個1-10的數字的水平索引,以及來自A-J(都是JLabels)的垂直索引。JPanel GridLayout(部分由循環填充)增加了新的值,無論它們被添加的順序如何
我使用了Vertical垂直索引到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時會發生什麼。
任何輸入將不勝感激!
考慮提供一個[可運行的示例](https://stackoverflow.com/help/mcve),它演示了您的問題。這不是代碼轉儲,而是您正在做的事情的一個例子,它突出了您遇到的問題。這將導致更少的混淆和更好的迴應 – MadProgrammer
好的。我試圖保持簡短,但我認爲在這裏爲Swing示例提供SSCCE更方便。我的錯。 – SmithNineSix
示例代碼可以更輕鬆地將代碼放入上下文中,並查看還有哪些可能導致的問題,並允許我們對其進行修改;) – MadProgrammer