gpt4 book ai didi

java - Swing展示表格结构与Gridbaglayout

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:10 26 4
gpt4 key购买 nike

目前我想使用 JPanel 和 gridbaglayout 显示表格结构,但设计时遇到一些麻烦。

我的数据存储在节点结构中(从 xml 文档解析)。在我的代码中,如果一个节点有一组其他节点,我每次都会创建一个新面板(递归方法 showGroupField)。我还有一个创建 gridbagconstraint 的方法,它为我提供了表结构。问题是,当将新面板添加到主面板时,它会与 gridbaglayout 的第一列保持一致,而不是使用主面板的整个宽度。有谁知道如何解决这个问题?非常感谢!

这就是我现在拥有的:

What I have now

这就是我想要的:

What I want

代码:

package view;

import domain.NodeInfo;

public class InputScreen {

...

public InputScreen(Node parentNode){
this.parentNode = parentNode;
nodeInfo = new NodeInfo();
}

public void initiateInputScreen() {
mainFrame = new JFrame("Front-End Generator");
mainFrame.setSize(1000,1000);

contentPanel = new JPanel();
inputPanel = new JPanel();

makeContentPanel();

mainFrame.setContentPane(contentPanel);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
}

private void makeContentPanel() {
contentPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPanel.setLayout(new BorderLayout(5,5));

makeInputPanel();

contentPanel.add(inputPanel, BorderLayout.CENTER);
}

private void makeInputPanel() {
inputPanel.setBorder(BorderFactory.createTitledBorder("Inputs"));
inputPanel.setLayout(new GridBagLayout());

inputPanel.add(new JLabel(nodeInfo.getNodeInformation(parentNode)), createGbc(0, 0));

inputPanel.add(showGroupField(parentNode.getFirstChild()), createGbc(0,1));
}

private JPanel showGroupField(Node node) {
int count = 0;
JPanel tmpPanel = new JPanel(new GridBagLayout());
tmpPanel.setBorder(BorderFactory.createTitledBorder("Test"));

NodeList listNode = node.getChildNodes();
for(int i=0; i<listNode.getLength(); i++){
if(nodeInfo.isGroupField(listNode.item(i))){
tmpPanel.add(showGroupField(listNode.item(i)), createGbc(0, count));
count++;
}else{
tmpPanel.add(new JLabel("Test"), createGbc(0, count));
tmpPanel.add(new JTextField(20), createGbc(1, count));
count++;
}
}
return tmpPanel;
}

private GridBagConstraints createGbc(int x, int y){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;

gbc.anchor = (x==0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x==0) ? GridBagConstraints.BOTH : GridBagConstraints.HORIZONTAL;

gbc.insets = (x==0) ? new Insets(5,0,5,5) : new Insets(5,5,5,0);
gbc.weightx = (x==0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
}

最佳答案

尝试将inputPanel添加到WEST位置。

contentPanel.add(inputPanel, BorderLayout.WEST);

关于java - Swing展示表格结构与Gridbaglayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200575/

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