The idea is as follows:
Create JPanel panel object;
Use the setLayout(0,4) method of the JPanel class to set the grid layout manager, that is, the number of columns is 4, and the number of rows is automatically adjusted;
Create a string-type one-dimensional array as a control text array;
Create a JCheckBox-type one-dimensional array as a control array;
Use the for loop to loop through the control array, initialize the checkbox component in the array, and add the array elements (i.e. each checkbox) to the panel using the add() method of the JPanel class.
The code is as follows:
The code copy is as follows:
package cn.edu.xidian.crytoll;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.UIManager;
public class CheckBoxArray extends JFrame {
/**
*
*/
private static final long serialVersionUID = -5338362310060106193L;
private JPanel contentPane;
private JPanel panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CheckBoxArray frame = new CheckBoxArray();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CheckBoxArray() {
setTitle("Add multiple checkbox controls through checkbox control array");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 409, 331);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel label = new JLabel(
"What are your hobbies:");
contentPane.add(label, BorderLayout.NORTH);
contentPane.add(getPanel(), BorderLayout.CENTER);
}
private JPanel getPanel() {
if (panel == null) {
panel = new JPanel();// Create panel object
panel.setLayout(new GridLayout(0, 4));// Set the grid layout manager
// Create control text array
String[] labels = { "football", "basketball", "magic", "table tennis", "movie", "world of warcraft", "CS team",
"Badminton", "Swimming", "Traveling", "Climbing", "Singing", "Blogging", "Animal World", "Photographing", "Playing Guitar",
"Reading newspapers", "Racing", "Shopping", "Shopping in malls", "Mahjong", "Reading books", "Looking online information", "News", "Military",
"Gagram", "Health Preservation", "Drinking Tea" };
JCheckBox[] boxes = new JCheckBox[labels.length];// Create an array of controls
for (int i = 0; i < boxes.length; i++) {// traverse the control array
boxes[i] = new JCheckBox(labels[i]);// Initialize the checkbox component in the array
panel.add(boxs[i]);// Add array elements (i.e. each check box) to the panel
}
}
return panel;
}
}