首页 文章

使用Gridbaglayout摆动显示表结构

提问于
浏览
1

目前我想使用带有gridbaglayout的JPanel来显示表结构,但是我在设计时遇到了一些麻烦 .

我的数据存储在节点结构中(从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;
    }
}

1 回答

  • 0

    尝试将 inputPanel 添加到 WEST 位置 .

    contentPanel.add(inputPanel, BorderLayout.WEST);
    

相关问题