首页 文章

如何构建一个在java中动态调整大小的布局?

提问于
浏览
2

我需要知道如何构建一个动态调整大小的java布局 . 布局设置有4个面板,从上到下堆叠:

顶部面板是GridLayout(4,2) . 每个rown是标签和文本字段,第二个面板是单个按钮,第三个面板是网格布局(n,2) . 我将在一分钟内到达底部面板也是一个按钮

n是动态变化的数字 . 第三个面板包含一个文本字段,然后是一个右侧有2个按钮的面板 . 我遇到的问题是我需要能够添加和删除这些行并让JFrame像我一样自动调整大小 . 我尝试将Frame设置为GridLayout(4,1),但是当我在actionPerformed()上更改大小时,它会均匀地扩展额外的空间 . 我想只为第三个面板添加空间 .

谢谢

EDIT: ActionPerformed Method

public void actionPerformed(ActionEvent e) {
    Object src = e.getSource();

    if (src == addTarget) {
        targetChoosers.add(new JFileChooser(new File("C:\\")));
        targets.add(new JTextField());
        targetButtons.add(new JButton("Browse..."));
        targetDeleters.add(new JButton("Delete"));

        int numTargets = targets.size();
        targetButtons.get(numTargets - 1).addActionListener(this);
        targetDeleters.get(numTargets - 1).addActionListener(this);

        bottomPanel.setLayout(new GridLayout(numTargets, 2));
        bottomPanel.add(targets.get(numTargets - 1));

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 2));
        panel.add(targetButtons.get(numTargets - 1));
        panel.add(targetDeleters.get(numTargets - 1));

        bottomPanel.add(panel);
    } 

    //...

    else if (targetDeleters.contains(src)) {
        int index = targetDeleters.indexOf(src);

        targets.remove(index);
        targetChoosers.remove(index);
        targetButtons.remove(index);
        targetDeleters.remove(index);

        this.remove(submit);
        this.remove(bottomPanel);

        int numTargets = targets.size();
        bottomPanel = new JPanel(new GridLayout(numTargets, 2));

        for (int i = 0; i < targets.size(); i++) {
            bottomPanel.add(targets.get(i));

            JPanel panel = new JPanel();
            panel.setLayout(new GridLayout(1, 2));
            panel.add(targetButtons.get(i));
            panel.add(targetDeleters.get(i));

            bottomPanel.add(panel);
        }

        this.add(bottomPanel);
        this.add(submit);
    }

    //...   

    pack();

    invalidate();
    validate();
}

2 回答

  • 0

    GridBagLayout可能有助于解决(n,2)问题 .

  • 1

    另一个很棒的LayoutManager是MigLayout .

相关问题