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();
}
}