java java中的动态复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5756038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:36:44  来源:igfitidea点击:

Dynamic check boxes in java

javaswing

提问by Fatema Mohsen

I want to create check boxes dynamically in java so that whenever a button is pressed a new check box is created and appeared and whenever another button is pressed all the checked boxes are removed. Can anyone help about that?

我想在java中动态创建复选框,以便每当按下按钮时都会创建并出现一个新复选框,每当按下另一个按钮时,所有复选框都会被删除。任何人都可以帮忙吗?

Up till now i have only the check boxes created manually

到目前为止,我只有手动创建的复选框

cb1=new JCheckBox("Task 1"); 
cb2=new JCheckBox("Task 2"); 
cb3=new JCheckBox("Task 3"); 
cb4=new JCheckBox("Task 4"); 
cb5=new JCheckBox("Task 5"); 
cb6=new JCheckBox("Task 6"); 

addTask= new JButton("Add Task"); 
removeTask= new JButton("Remove Checked"); 

addTask.addActionListener(this); 
removeTask.addActionListener(this);

回答by MByD

Lets say that instead of cb1, cb2, cb3 etc you create an ArrayListof JCheckBoxes and create a panel only for checkboxs, not for the buttons. Now, every time you press the add buttonyou create another checkbox, and add it to both panel and ArrayList. When you press the remove buttonyou clear the array list and the panel. The following code is only an example snippet, not a full tested code, but it should give you a direction.

假设不是 cb1、cb2、cb3 等,而是创建一个ArrayListof JCheckBoxes 并仅为checkboxs创建面板,而不是为按钮创建面板。现在,每次按下添加按钮时,都会创建另一个复选框,并将其添加到面板和ArrayList. 当您按下删除按钮时,您将清除阵列列表和面板。下面的代码只是一个示例片段,不是完整的测试代码,但它应该给你一个方向。

// Up in your code
List<JCheckBox> cbarr = new ArrayList<JCheckBox>();
// The listener code
public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == addTask) // add checkbox
     {
          JCheckBox cb = new CheckBox("New CheckBox");
          cbarr.add(cb);
          cbpanel.add(cb);
     }
     else // remove checkboxs
     {
          cbarr = new ArrayList<JCheckBox>();
          cbpanel.removeAll()
     }
}

EDIT

编辑

I am sorry, but I missed the part when you said you want to remove only the checked boxes. This can be done easily by changing the code in the else block:

我很抱歉,但是当您说您只想删除选中的框时,我错过了部分。这可以通过更改 else 块中的代码轻松完成:

for (int i = cbarr.size() - 1; i >=0; i--)
{
    JCheckBox cb = cbarr.get(i);
    if (cb.isSelected())
    {
        cbarr.remove(cb);
        cbpanel.remove(cb);
    }
}

回答by Suhail Gupta

//This will surely help you!

//这肯定对你有帮助!

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;

    class tester {
      JButton remove;
      JButton appear;
      JCheckBox cb[]=new JCheckBox[10]; 


       tester() {
          buildGUI();
          hookUpEvents();
       }

       public void buildGUI() {
           JFrame fr=new JFrame();
           JPanel p=new JPanel();
           remove=new JButton("remove");
           appear=new JButton("appear");
             for(int i=0;i<10;i++) {
                cb[i]=new JCheckBox("checkbox:"+i);
                cb[i].setVisible(false);
             }
           fr.add(p);
           p.add(remove);
           p.add(appear);
           for(int i=0;i<10;i++) {
             p.add(cb[i]);
           }
           fr.setVisible(true);
           fr.setSize(400,400);
        }

        public void hookUpEvents() {
           remove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    for(int i=0;i<10;i++) {
                        cb[i].setVisible(false);
                     }
                 }
           });

           appear.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                   for(int i=0;i<10;i++) {
                      cb[i].setVisible(true);
                    }
                }
           });
         }

         public static void main(String args[]) {
             new tester();
         }
        }

回答by camickr

When you dynamically add/remove components for a GUI you need to tell the layout manager that changes have been made. YOu do this with code like:

当您为 GUI 动态添加/删除组件时,您需要告诉布局管理器已进行更改。您可以使用以下代码执行此操作:

panel.add(....);
panel.revalidate();
panel.repaint();

回答by jzd

Instead of creating a new variable for each checkbox. Store references to the checkboxes in a list. When you create new check boxes add them to the list. When you want to remove them all, remove them from the GUI and clear the list.

而不是为每个复选框创建一个新变量。在列表中存储对复选框的引用。创建新复选框时,将它们添加到列表中。如果您想将它们全部删除,请从 GUI 中删除它们并清除列表。

回答by Boro

You should use some Layout Manager, for example GridLayout, for which you can specify, rows or columns to be dynamic by setting them to 0 in the layout constructor.

您应该使用一些布局管理器,例如GridLayout,您可以通过在布局构造函数中将它们设置为 0 来指定动态行或列。

In actionPerformed method you would add to the panel new checkbox using JPanel.add() method, validate it afterwords and you are done.

在 actionPerformed 方法中,您将使用 JPanel.add() 方法将新复选框添加到面板中,验证它之后就完成了。

About removal you can iterate through list of the components of the panel and call JPanel.remove() method, validate the panel afterwards.

关于删除,您可以遍历面板的组件列表并调用 JPanel.remove() 方法,然后验证面板。

Good luck, Boro.

祝你好运,波罗。

回答by Andrew Thompson

This Nested Layout Examplehas a JButtonon the left to Add Another Label. It adds labels in columns of two. The same basic principal could be applied to adding any number of JCheckBox.

这种嵌套布局实例有一个JButton在左边Add Another Label。它在两列中添加标签。相同的基本原理可以应用于添加任意数量的JCheckBox.

To remove them, call Container.removeAll()and call the same methods afterwards to update the GUI.

要删除它们,请Container.removeAll()在之后调用和调用相同的方法来更新 GUI。

回答by Hovercraft Full Of Eels

All the above solutions are excellent. One alternative though is if you have a significant list of check boxes in a column, Consider instead using a JTable that has a column of check boxes and perhaps a column as a "label". The Oracle Swing JTable tutorialwill show you how to do this, but it's simply a matter of extending a DefaultTableModel class and overriding it's getColumnClass method to return Boolean.class for the column with the checkboxes. Then fill the model with Boolean objects. You can then add or remove rows from the model and have the JTable take care of handling the GUI nitty gritty. If you want to try it this way, we can help you with the specifics.

以上所有解决方案都非常出色。一种替代方法是,如果您在一列中有大量复选框,请考虑使用具有一列复选框和一列作为“标签”的 JTable。在甲骨文秋千JTable的教程将告诉你如何做到这一点,但它只是扩展一个DefaultTableModel类并覆盖它的问题是的getColumnClass方法返回Boolean.class与复选框列。然后用布尔对象填充模型。然后,您可以在模型中添加或删除行,并让 JTable 负责处理 GUI 细节。如果您想以这种方式尝试,我们可以帮助您了解具体情况。

edit 1:
For Example:

编辑1:
例如:

edit 2:
add/remove functionality shown

编辑 2:
添加/删除功能显示

edit 3:
Moved the removeChecked and showAll methods into the model class.

编辑 3:
将 removeChecked 和 showAll 方法移动到模型类中。

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class CheckBoxTable extends JPanel {
   public static final String[] COLUMNS = {"Purchased", "Item"};
   public static final String[] INITIAL_ITEMS = {"Milk", "Flour", "Rice", "Cooking Oil", "Vinegar"}; 
   private CheckBoxDefaultTableModel model = new CheckBoxDefaultTableModel(COLUMNS, 0);
   private JTable table = new JTable(model);
   private JTextField itemTextField = new JTextField("item", 10);

   public CheckBoxTable() {
      JButton addItemBtn = new JButton("Add Item");
      addItemBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            addItemActionPerformed();
         }
      });
      JButton removeCheckedItemsBtn = new JButton("Remove Checked Items");
      removeCheckedItemsBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            removeCheckedItemsActionPerformed();
         }
      });
      JButton showAllBtn = new JButton("Show All");
      showAllBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            showAllActionPerformed();
         }
      });
      itemTextField.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            itemTextField.selectAll();
         }
      });
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      btnPanel.add(itemTextField);
      btnPanel.add(addItemBtn);
      btnPanel.add(removeCheckedItemsBtn);
      btnPanel.add(showAllBtn);

      setLayout(new BorderLayout(5, 5));
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);

      for (int i = 0; i < INITIAL_ITEMS.length; i++) {
         Object[] row = {Boolean.FALSE, INITIAL_ITEMS[i]};
         model.addRow(row);
      }
   }

   private void showAllActionPerformed() {
      model.showAll();
   }

   private void removeCheckedItemsActionPerformed() {
      model.removeCheckedItems();
   }

   private void addItemActionPerformed() {
      String item = itemTextField.getText().trim();
      if (!item.isEmpty()) {
         Object[] row = {Boolean.FALSE, item};
         model.addRow(row);
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("CheckBoxTable");
      frame.getContentPane().add(new CheckBoxTable());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

@SuppressWarnings("serial")
class CheckBoxDefaultTableModel extends DefaultTableModel {
   private List<String> removedItemsList = new ArrayList<String>();

   public CheckBoxDefaultTableModel(Object[] columnNames, int rowCount) {
      super(columnNames, rowCount);
   }

   public void showAll() {
      if (removedItemsList.size() > 0) {
         Iterator<String> iterator = removedItemsList.iterator();
         while (iterator.hasNext()) {
            String next = iterator.next();
            Object[] row = {Boolean.TRUE, next};
            addRow(row);
            iterator.remove();
         }
      }
   }

   @Override
   public Class<?> getColumnClass(int columnNumber) {
      if (columnNumber == 0) {
         return Boolean.class;
      }
      return super.getColumnClass(columnNumber);
   }

   public void removeCheckedItems() {
      int rowCount = getRowCount();
      for (int row = rowCount - 1; row >= 0; row--) {
         if ((Boolean) getValueAt(row, 0)) {
            removedItemsList.add(getValueAt(row, 1).toString());
            removeRow(row);
         }
      }

   }
}

回答by Austin

You can use arrays of collections that contain check box types, initialize data collections for check box names, initialize check boxes and collection arrays, and finally loop through collection arrays and perform logic processing based on whether check box objects are selected or not.

您可以使用包含复选框类型的集合数组,为复选框名称初始化数据集合,初始化复选框和集合数组,最后循环遍历集合数组并根据复选框对象是否被选中进行逻辑处理。