动态添加JCheckBoxes

时间:2013-09-19 08:52:14

标签: java swing jcheckbox

有没有办法在Java中动态添加JCheckBox类型的项目,就像JComboBox我们使用addItem方法一样?

2 个答案:

答案 0 :(得分:1)

如果您想将多个项目添加到另一个组件,这样的事情可能会有效:

List<Component>  myList = new Arraylist<Component>() //List for storage
Item myItem = new Item(); //New component
myList.add(myItem);  //Store all the components to add in the list

for(int i = 0; i < myList.size; i++){
myjCheckBox.add(myList[i]); //Add all items from list to jCheckBox
}

以上示例使用jCheckBox中继承的this方法,并且应该能够提供您需要的内容

希望它有所帮助!

答案 1 :(得分:1)

JCheckList

请注意,您可能会使用渲染组件的实际复选框,但这会缩短几行。

import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;

class JCheckList {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout());

                JLabel l = new JLabel("Ctrl/shift click to select multiple");
                gui.add(l, BorderLayout.PAGE_START);

                JList<String> list = new JList<String>(
                        ImageIO.getReaderFileSuffixes());
                list.setCellRenderer(new CheckListCellRenderer());
                gui.add(list, BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

class CheckListCellRenderer extends DefaultListCellRenderer {

    String checked = new String(Character.toChars(9745));
    String unchecked = new String(Character.toChars(9746));

    @Override
    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(
                list,value,index,isSelected,cellHasFocus);
        if (c instanceof JLabel) {
            JLabel l = (JLabel)c;
            String s = (isSelected ? checked : unchecked) + (String)value;
            l.setText(s);
        }

        return c;
    }
}
相关问题