思路如下:
建立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;
}
}