欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java通过复选框控件数组实现添加多个复选框控件示例分享

程序员文章站 2024-02-21 23:59:28
思路如下: 创建jpanel面板对象;使用jpanel类的setlayout(0,4)方法设置网格布局管理器,即列数为4,行数自动调节;创建一个字符串型一维数组作为控件文...

思路如下:

创建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;
    }
}