java gridlayout.add_JPanel GridLayout(部分由循环填充)将新值添加到结尾,而不管它们的添加顺序如何...

所以我正在玩Swing和GUI,设计一个程序,其中我有一个包含10x10自定义JButton网格的JPanel . 我有1-10的数字水平索引,以及A-J(两个JLabels)的字母垂直索引 .

我使用带有WEST的垂直索引的BorderLayout,以及嵌套在CENTER中的11x10 GridLayout(为什么?因为这是我能想到的最简单的方法来完善水平索引号在其相应按钮列上方的位置) .

我有110个空间网格的前10个空格,用数字来索引列 - 这很好用 .

然后我使用一个11x1网格将垂直索引上的字母平均分配给WEST,以考虑网格顶部水平索引的额外插槽(见下图) .

我的问题是:每当我去填充垂直网格顶部的空白区域时,它会将新的JLabel放在底部,无论它是放在填充循环之前还是之后 .

结果如下:

fcd6aeab-2c0d-4c7c-84cf-663aaee509a6.png

这里是我用来填充循环的代码,在填充循环之前和之后添加了一个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时会发生什么 .

任何输入将非常感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值