Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

java - How to iteratively add Components to a Swing GroupLayout ParallelGroup?

Is there a way to iterate over a List of Components and add them to a ParallelGroup in Swing GroupLayout?

It seems difficult because there is no method to get hold of the ParallelGroup.

Here is the code generating a List of Components (in this case, JCheckBoxes).

List<JCheckBox> listCustomiseJCB = new ArrayList<>();
    for (int w = 0; w < initialCMTableColumns.size(); w++) {
        String heading = (String)initialCMTableColumns.get(w).getHeaderValue();
        listCustomiseJCB.add(new JCheckBox(heading));
    }

The List is working, but how can I iterate over the List to insert each JCheckbox into a GroupLayout's ParallelGroup? For example, the below code won't compile.

    GroupLayout gl = new GroupLayout(jpnlCustomise);
    jpnlCustomise.setLayout(gl);
    gl.setAutoCreateContainerGaps(true);
    gl.setAutoCreateGaps(true);

    GroupLayout.SequentialGroup hGroup = gl.createSequentialGroup();

    hGroup
            .addComponent(jbtnApply);
    hGroup.addGroup(gl.createParallelGroup(GroupLayout.Alignment.CENTER)
            // ERRORS BEGIN HERE
            { for (JCheckBox c: listCustomiseJCB) {
            .addComponent(c);
            }});
            // ERRORS END HERE
    hGroup
            .addComponent(jbtnCancel);

    gl.setHorizontalGroup(hGroup);

Alternatively, does anyone know of a way to get hold of a ParallelGroup so that I could iteratively add Components to that group in a standalone for loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I can see what you're trying to do and your confusion. You can only use anonymous class syntax with the new operator. i.e

new LinkedList<String>() {
  {
     add("bar");
  }
};

However ParallelGroup instances can only be created with the factory method createParallelGroup(...).

You'll have to use a temporary reference to the parallel group:

ParallelGroup pGroup = gl
        .createParallelGroup(GroupLayout.Alignment.CENTER);
hGroup.addGroup(pGroup);
for (JCheckBox c : listCustomiseJCB) {
    pGroup.addComponent(c);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...