我想在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);
}
}
}
目前它只显示一行中的所有标签,而不是一个接一个地显示。为什么这样,我怎么能得到我想要的行为?
答案 0 :(得分:2)
将布局管理员battleBoardPane
设置为GridbagLayout
(据我所知,默认为FlowLayout
它不会从包含窗格“继承”它。)
答案 1 :(得分:1)
第一个答案是对的,但是您更错了代码。
而不是this.setLayout(new GridBagLayout());
drawBattleBoard()
方法的第一行
你必须写
battleBoardPane.setLayout(new GridBagLayout());