Creating component dynamically

0

I made a method whose goal is to add a quantity of checkBoxes according to the value of a variable that I'm going to receive. I wanted it to stay inside a scrollPane so it would not take up more space than I set.

What I could not do was make the components all in the same JScrollPane . I wanted to make them side by side with a maximum of 4 checks on each line, so I set it after a small size for JScrollPane , but it creates a JScrollPane for each check.

Here is an example below:

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class TesteAdd extends JFrame {

    JScrollPane jsp = new JScrollPane();

    public TesteAdd() {
        add(addComp());
        setSize(500, 500);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JComponent addComp() {
        JPanel painel = new JPanel();
        painel.setLayout(new FlowLayout());
        painel.setBorder(BorderFactory.createTitledBorder("Borda"));

        int controle = 7;

        for (int i = 0; i < controle; i++) {
            String nome = "Check " + Integer.toString(i);
            JCheckBox box = new JCheckBox(nome);

            painel.add(jsp = new JScrollPane(box));
        }
        jsp.setPreferredSize(new Dimension(150, 150));
        painel.setPreferredSize(new Dimension(300, 300));
        return painel;
    }

    public static void main(String[] args) {
        TesteAdd a = new TesteAdd();
    }
}
    
asked by anonymous 08.07.2017 / 03:17

1 answer

4

When you want to add common components such as buttons and checkboxes to a scrollable panel, you must first add those components to a common panel and add this panel as ViewPort of the scrollable panel. Your code does not work because you try to add it directly to the scrollable pane.

Another problem is that, due to the default layout of the JPanels, even doing the explained way, horizontal scrolling will be generated, as FlowLayout organizes each component side by side, horizontally. Since we can not limit the size of this panel where we'll add the checkboxes (see the reason in this answer ), we'll have to use it another layout that allows us to organize items into groups of 4 on each line, GridLayout allows this mode of organization.

You will need to create another JPanel in your addComp method, and set GridLayout to its layout:

JPanel p = new JPanel();
p.setLayout(new GridLayout(0, 4));

The parameters of GridLayout are, respectively, the number of rows and number of columns. Since we do not have the definition of total rows, we pass 0, which informs the layout that it is an undefined number yet, and columns have passed 4 since you want to arrange rows with this amount.

Modify your loop so that the checkboxes are added in this new panel:

for (int i = 0; i < controle; i++) {
    String nome = "Check " + Integer.toString(i);
    JCheckBox box = new JCheckBox(nome);
    p.add(box);
}

Define a size for your ScrollPane (since it is based on this size that it will be based on to generate the scrollbars) and set the new front panel to ViewPort of that scrollPane:

jsp.setPreferredSize(new Dimension(150, 150));
jsp.setViewportView(p);

Now just add the scrollpane to the panel you will return in the method for JFrame.

The final code is:

private JComponent addComp() {
    JPanel painel = new JPanel();
    painel.setBorder(BorderFactory.createTitledBorder("Borda"));

    //neste painel é que adicionaremos os chekboxes
    JPanel p = new JPanel();
    p.setLayout(new GridLayout(0, 4));

    int controle = 30;

    for (int i = 0; i < controle; i++) {
        String nome = "Check " + i;
        JCheckBox box = new JCheckBox(nome);
        p.add(box);
    }
    //defini um tamanho preferido pro scrollpane
    jsp.setPreferredSize(new Dimension(350, 150));
    //defini o painel de checkboxes como viewport do scrollpane
    jsp.setViewportView(p);
    painel.add(jsp);
    return painel;
}

And the result:

AsmalldetailinyourcodeistouseInteger.toStringtoconvertanintegertoString,anditisunnecessarythere,becausewhenyouconcatenateaprimitivetypetoastring,itisautomaticallyconvertedtostring.SoImodifieditdirectlyinyourmethod.

Ifyouwanttolearnmoreaboutthislayout,followthelinkintheofficialdocumentation,withasmalltutorial:

How to Use GridLayout

    
08.07.2017 / 03:23