Ideas are as follows:
Create a JPanel panel object;
The SetLayout (0,4) method of the JPanel class is used to set the grid layout manager, that is, the number of columns is 4 and the number of rows is automatically adjusted;
Creates a string one-dimensional array as an array of control text;
Create a Jcheckbox-type one-dimensional array as an array of controls;
Use a For loop to iterate through the control array, initialize the checkbox component in the array, and use the Add () method of the JPanel class to add the element of the array (that is, each check box) to the panel.
The code is as follows:
Copy Code code 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 check box controls through a check box control array Implementation");
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 Dashboard Object
Panel.setlayout (New GridLayout (0, 4));/Set Grid layout Manager
To create a control text array
string[] Labels = {"Football", "basketball", "Magic", "Table tennis", "Watch Movie", "World of Warcraft", "CS Team",
"Badminton", "swimming", "travel", "climbing", "singing", "blogging", "Animal World", "taking Pictures", "playing the Guitar",
"Read the newspaper", "Drag Racing", "shopping", "Shopping malls", "Mahjong", "reading", "Surfing the Internet", "News", "military",
"Gossip", "Health", "Drink Tea"};
jcheckbox[] Boxs = new jcheckbox[labels.length];//Create control array
for (int i = 0; i < boxs.length; i++) {//Traverse control array
Boxs[i] = new Jcheckbox (labels[i]);//Initialize the checkbox component in the array
Panel.add (Boxs[i])//Add array elements (that is, each check box) to the panel
}
}
return panel;
}
}