gpt4 book ai didi

java - 迭代地添加带有 gridbaglayout 的组件?

转载 作者:行者123 更新时间:2023-11-29 05:56:55 25 4
gpt4 key购买 nike

我想在 for 循环中使用 gridbaglayout 来布置固定大小的静态不可编辑网格。但是,当我这样做时,我什么也得不到。这是我作为 SSCEE 的第一次尝试:

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class ViewManager extends JFrame{

private static final long serialVersionUID = 1L;
private NewCharacterVitalsPane myNewCharacterVitalsPane = null;

public ViewManager(){
super("Tony Larp DB Manager");
this.setVisible(true);
this.setDefaultCloseOperation(3);
myNewCharacterVitalsPane = new NewCharacterVitalsPane();
this.getContentPane().add(myNewCharacterVitalsPane);
this.pack();
}
static class Util {
static private ViewManager viewManager = null;
static public synchronized ViewManager getInstance() {
if (viewManager == null) {
viewManager = new ViewManager();
}
return viewManager;
}
}
}

public class Launcher {

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
ViewManager.Util.getInstance();
}
});
}
}

class NewCharacterVitalsPane extends JPanel{

private static final long serialVersionUID = 1962802485168533544L;
String locations[] = {"H","Ch","Ra","La","Rl","Ll"};
int armour[] = {0,0,0,0,10,0};
int life = 30;

/*subPanes*/
JPanel battleBoardPane = new JPanel();


public NewCharacterVitalsPane (){
addSubPanes();
drawBattleBoard();
}
private void addSubPanes() {
this.setLayout(new GridBagLayout());
GridBagConstraints SPgbc = new GridBagConstraints();
SPgbc.fill = GridBagConstraints.BOTH;

SPgbc.gridx = 0;
SPgbc.gridy = 1;
SPgbc.gridheight = 2;
SPgbc.ipadx = 100;
SPgbc.ipady = 180;
battleBoardPane.setBorder(BorderFactory.createLineBorder(Color.black));
add(battleBoardPane,SPgbc);
}

private void drawBattleBoard(){
this.setLayout(new GridBagLayout());
GridBagConstraints BBgbc = new GridBagConstraints();
BBgbc.gridx=0;BBgbc.gridy=0;
for (String location:locations){
JLabel locLabel = new JLabel(location+": ");
BBgbc.gridy++; battleBoardPane.add(locLabel,BBgbc);
}
}
}

目前它只是将所有标签显示在一行中,而不是一个接一个地显示。这是为什么,我怎样才能得到我想要的行为?

最佳答案

battleBoardPane的Layoutmanager设置为GridbagLayout
(默认为 FlowLayout 据我所知,它不会从包含 Pane “继承”它。)

关于java - 迭代地添加带有 gridbaglayout 的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11738912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com