java經由過程復選框控件數組完成添加多個復選框控件示例分享。本站提示廣大學習愛好者:(java經由過程復選框控件數組完成添加多個復選框控件示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是java經由過程復選框控件數組完成添加多個復選框控件示例分享正文
思緒以下:
創立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;
}
}