Creating component dynamically

Asked

Viewed 742 times

0

I made a method whose goal is to add a number of checkboxes according to the value of a variable that I will receive. I wanted him to stay inside a scrollPane so he wouldn’t take up more space than I set.

What I couldn’t get was to make the components all the same JScrollPane. I wanted to make them stand next to each other, with at most 4 checks on each line, so I set after the is a small size for the JScrollPane, but it creates a Jscrollpane for each check.

Follow 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();
    }
}
  • painel.add(jsp = new JScrollPane(box)); haven’t noticed anything wrong here?

  • @diegofm without being like this, I couldn’t make him "pick it up", he’s adding a jsp to each ne? :(

1 answer

4


When you want to add common components like buttons and checkboxes in a scrollable panel, you need to first add these components in a common panel and add this panel as ViewPort scrollable panel. Your code does not work because you try to add directly to the scrollable panel.

Another problem is that, due to the standard layout of the Jpanels, even doing the way explained, it will be generated horizontal scroll, because the FlowLayout organizes each component next to each other horizontally. As we cannot limit the size of this panel where we will add checkboxes(see reason in this answer), we will have to use in it another layout that allows us to organize items in groups with 4 in each line, the GridLayout allows this mode of organization.

You will need to create one more JPanel in his method addComp, and define the GridLayout as his layout:

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

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

Modify your loop so that 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);
}

Set a size for your Scrollpane (as it is from this size that it will be based to generate the scrollbars) and set the previous new panel as ViewPort of this 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:

inserir a descrição da imagem aqui

A small detail in your code is to use Integer.toString to convert an integer to String, and it is unnecessary there, because when you concatenate a primitive type to a string, it is automatically converted to a string. That’s why I modified your method directly.

If you want to learn more about this layout, follow the official documentation link, with a small usage tutorial:

How to Use Gridlayout

  • I had tried so, but then he added nothing on the screen. for (int i = 0; i < control; i++) { String name = "Check " + Integer.toString(i); Jcheckbox box = new Jcheckbox(name); jsp.add(box); } panel.add(jsp);

  • @Did you make the changes as I explained in the reply? Will you change the line I quoted by jsp.add(box); inside the loop. You will not add the scrollpane to the panel inside the loop.

  • Yes, I did, what I posted there in the top comment was just the change, after the for, I add the jsp. i do > dashboard.add(jsp); more checks are not added.

  • @Java of course adds, tested here and appeared the 7 checks normally.

  • Strange I increased until the size of the panel, but nothing.

  • @Java you use setpreferredsize but without pack it is ignored. It is not that the component is not added, it is that the panel and scroll are started with zero size. Either you use preferredsize throughout the application and pack() for sizes to be respected, or use fixed size at all, which is a bad practice, as you did with jframe. setSize != setPreferredsize, it is good not to mix them, unless you are sure that it is necessary.

  • even making setPreferredSize and using the pack, it still n displays the check.

  • @Java found the error.

  • and what causes ?

  • 1

    @Java has to do with vc add straight to scrollpane. Tomorrow I respond more calmly explaining the problem in case you did not find the solution.

  • I stand by, did not identify the error

  • @Java was without electricity until now, I will answer. I just did not understand why someone gave negative, but ta de boa.

  • 1

    negative in what ?

  • @Java is that the answer was negative by someone, but no matter, I’ve updated the answer explaining the problem and how to solve, take a look there :)

  • Oops! Now that I saw that you want to organize in lines with 4, and not all below each other. The good news is that we just need to change the layout of panel p and everything is resolved :D

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.