思路如下:
創建JPanel面板對象;
使用JPanel類的setLayout(0,4)方法設置網格布局管理器,即列數為4,行數自動調節;
創建一個字符串型一維數組作為控件文本數組;
創建一個JCheckBox型一維數組作為控件數組;
使用for循環遍歷控件數組,初始化數組中的復選框組件,使用JPanel類的add()方法把數組元素(即每個復選框)添加到面板中。
代碼如下:
代碼如下:
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("通過復選框控件數組實現添加多個復選框控件");
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(
"你的愛好有哪些:");
contentPane.add(label, BorderLayout.NORTH);
contentPane.add(getPanel(), BorderLayout.CENTER);
}
private JPanel getPanel() {
if (panel == null) {
panel = new JPanel();// 創建面板對象
panel.setLayout(new GridLayout(0, 4));// 設置網格布局管理器
// 創建控件文本數組
String[] labels = { "足球", "籃球", "魔術", "乒乓球", "看電影", "魔獸世界", "CS戰隊",
"羽毛球", "游泳", "旅游", "爬山", "唱歌", "寫博客", "動物世界", "拍照", "彈吉他",
"讀報紙", "飙車", "逛街", "逛商場", "麻將", "看書", "上網看資料", "新聞", "軍事",
"八卦", "養生", "飲茶" };
JCheckBox[] boxs = new JCheckBox[labels.length];// 創建控件數組
for (int i = 0; i < boxs.length; i++) {// 遍歷控件數組
boxs[i] = new JCheckBox(labels[i]);// 初始化數組中的復選框組件
panel.add(boxs[i]);// 把數組元素(即每個復選框)添加到面板中
}
}
return panel;
}
}