组件可以动态添加到GroupLayout中的组吗? [英] Can Components be added to groups in GroupLayout dynamically?

查看:136
本文介绍了组件可以动态添加到GroupLayout中的组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用setHorizontalGroup()setVerticalGroup()之后,可以在不重置布局的情况下将Component动态添加到GroupLayout中的组中吗?我正在为一个项目的GUI工作,该项目将帮助学生找到最好的方法来汇总每周的课程表.这涉及针对未知数量的班级输入关于上课时间等的信息.当然,我不能只为用户添加任意​​数量的表格以放入信息并说没有人可以考虑的数量超过这一类的数量",因此用户需要能够在其上添加新的表格.他们自己的.我可以创建表单,但是我找不到在不调用setHorizontalGroup(...)setVerticalGroup(...)的情况下将它们成功添加到窗口中的GroupLayout的任何方法,而这些setHorizontalGroup(...)setVerticalGroup(...)覆盖了以前的Group而不是添加给他们. 这是我当前拥有的代码的相关部分(为便于阅读):

Can Components be added to groups in GroupLayout dynamically, after setHorizontalGroup() andsetVerticalGroup() have been called, without resetting the layout? I'm working on the GUI to a project that will help students find the best way to put together their weekly class schedules. This involves inputting information regarding class times, etc., for an unknown number of classes. Of course, I can't just add an arbitrarily large number of forms for the user to put information into and say "no one could be considering more than this number of classes", so the user needs to be able to add new forms on their own. I can create the forms, but I can't find any way to successfully add them to the GroupLayout in the window without re-calling setHorizontalGroup(...) or setVerticalGroup(...), which write over the previous Groups rather than add to them. This is the relevant portion of the code I currently have (commented for legibility):

 private static void createAndShowGUI() {
    //Create window and assign an empty GroupLayout to it
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    GroupLayout layout = new GroupLayout(frame.getContentPane());
    frame.getContentPane().setLayout(layout);

    /*WeekPanel extends JPanel, and is the "form" the user enters data into. 
    In essence, it's a JPanel with a series of JTextFields.*/
    WeekPanel panel1 = new WeekPanel();
    WeekPanel panel2 = new WeekPanel();

    //The layout code below places two WeekPanels in the window, one on top of the other
    layout.setHorizontalGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup()
                    .addComponent(panel1)
                    .addComponent(panel2)));
    layout.setVerticalGroup(layout.createSequentialGroup()
            .addComponent(panel1)
            .addComponent(panel2));

    /*I would like to add a component to the layout here as proof of concept.*/
    frame.pack();
    frame.setVisible(true);
}

我已经尝试在frame.pack()之前调用frame.add([some component]),但是它没有任何明显的区别.我看过GroupLayout的官方文档,就此而言,我看不到任何方法来访问或更改GroupLayout中的水平/垂直Group甚至是引用这些Group的字段. 我完全不知道该怎么办.我想尽可能避免学习新的Layout类型,但是我开始担心自己将不得不(或者更糟糕的是,我试图做的事情是不可能开始的)与).

I've tried calling frame.add([some component]) just before frame.pack(), but it never makes any visible difference. I've looked at the official documentation for GroupLayout, and I see no way of accessing or altering the horizontal/vertical Groups in GroupLayout, or even a field referring to those Groups, for that matter. I'm at a complete loss as to what to do here. I want to avoid learning a new type of Layout if at all possible, but I'm starting to fear that I'm going to have to (or, even worse, that what I'm trying to do is impossible to begin with).

推荐答案

此处所示,您可以使用此方法:

As shown here, you can use this approach:

  1. 首先,创建所需的ParallelGroupSequentialGroup.
  2. 稍后,添加代表新行的所需组和组件.
  1. First, create the required ParallelGroup and SequentialGroup.
  2. Later, add the desired groups and components representing a new row.

在下面的示例中,add()将新的标签和文本字段附加到布局.建议在此处AdjustmentListener滚动到最后添加的行.

In the example below, add() appends a new label and text field to the layout. An AdjustmentListener, suggested here, scrolls to the last added row.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentEvent;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/**
 * @see https://stackoverflow.com/a/41926375/230513
 * @see https://stackoverflow.com/a/14858272/230513
 * @see https://stackoverflow.com/a/8504753/230513
 * @see https://stackoverflow.com/a/14011536/230513
 */
public class DynamicGroupLayout {

    private static final int NUM = 6;
    private GroupLayout layout;
    private GroupLayout.ParallelGroup parallel;
    private GroupLayout.SequentialGroup sequential;
    private int i;

    private JPanel create() {
        JPanel panel = new JPanel();
        layout = new GroupLayout(panel);
        panel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        parallel = layout.createParallelGroup();
        layout.setHorizontalGroup(layout.createSequentialGroup().addGroup(parallel));
        sequential = layout.createSequentialGroup();
        layout.setVerticalGroup(sequential);
        for (int i = 0; i < NUM; i++) {
            add();
        }
        return panel;
    }

    private void add() {
        JLabel label = new JLabel(String.valueOf(i + 1), JLabel.RIGHT);
        JTextField field = new JTextField(String.valueOf("String " + (i + 1)));
        label.setLabelFor(field);
        parallel.addGroup(layout.createSequentialGroup().
            addComponent(label).addComponent(field));
        sequential.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).
            addComponent(label).addComponent(field));
        i++;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("DynamicGroupLayout");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                final DynamicGroupLayout dgl = new DynamicGroupLayout();
                final JPanel panel = dgl.create();
                JScrollPane jsp = new JScrollPane(panel) {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(320, 240);
                    }
                };
                jsp.getVerticalScrollBar().addAdjustmentListener((AdjustmentEvent e) -> {
                    e.getAdjustable().setValue(e.getAdjustable().getMaximum());
                });
                f.add(jsp);
                JPanel controls = new JPanel();
                controls.add(new JButton(new AbstractAction("Add") {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dgl.add();
                        panel.validate();
                    }
                }));
                f.add(controls, BorderLayout.SOUTH);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}

这篇关于组件可以动态添加到GroupLayout中的组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆