java - 使用java swings删除选定的复选框而不使用Jtable/Database

标签 java swing jlist jcheckbox

我是 Swings 新手,尝试在单击 Java Swings 中的删除按钮时删除选定的复选框,我尝试使用

"DefaultListModel" ,here i able to delete normal data not with check box here my code:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class ListModels extends JFrame {

//  @SuppressWarnings({ "unused", "rawtypes" })
//  //private DefaultListModel model;
//  @SuppressWarnings("rawtypes")
    @SuppressWarnings("rawtypes")
    private JList list;
    private JPanel rightPanel;
    JButton cancel = new JButton("Cancel");
    JButton delbtn = new JButton("Delete");

    // final JCheckBox chkApple = new JCheckBox("Apple");

    public ListModels() {

        createList();
        createButtons();
        initUI();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void createList() {

        /*
         * model = new DefaultListModel(); model.addElement(new CheckListItem[]
         * { new CheckListItem("1")});
         * model.addElement("Aguirre, der Zorn Gottes");
         * model.addElement("Fargo"); model.addElement("Exorcist");
         * model.addElement("Schindler's list");
         */
        // list = new JList(model);

        list = new JList(new CheckListItem[] { new CheckListItem("1"),
                new CheckListItem("2"), new CheckListItem("3"),
                new CheckListItem("4"), new CheckListItem("5") });

        list.setCellRenderer(new CheckListRenderer());
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent event) {
                JList list = (JList) event.getSource();

                // Get index of item clicked
                int index = list.locationToIndex(event.getPoint());
                CheckListItem item = (CheckListItem) list.getModel()
                        .getElementAt(index);

                // Toggle selected state
                item.setSelected(!item.isSelected());

                // Repaint cell
                list.repaint(list.getCellBounds(index, index));
            }
        });

    }

    private void createButtons() {

        rightPanel = new JPanel();

        // JButton cancel = new JButton("Cancel");
        cancel.setMaximumSize(cancel.getMaximumSize());

        // JButton delbtn = new JButton("Delete");
        delbtn.setMaximumSize(cancel.getMaximumSize());

        /*
         * delbtn.addActionListener(new ActionListener() {
         * 
         * @Override public void actionPerformed(ActionEvent event) {
         * ListSelectionModel selmodel = list.getSelectionModel(); int index =
         * selmodel.getMinSelectionIndex(); if (index >= 0) model.remove(index);
         * }
         * 
         * });
         */



        // JPanel buttonPane = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.LINE_AXIS));
        rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 4));
        rightPanel.add(Box.createHorizontalStrut(60));
        rightPanel.add(delbtn);
        rightPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        rightPanel.add(cancel);
    }

    private void initUI() {

        // JScroll Panel
        JScrollPane listScroller = new JScrollPane(list);
        listScroller.setPreferredSize(new Dimension(250, 80));
        listScroller.setAlignmentX(LEFT_ALIGNMENT);

        // Lay out the label and scroll pane from top to bottom.
        JPanel listPane = new JPanel();
        listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
        JLabel labelTest = new JLabel("New Label");

        // Add all to the panel
        listPane.add(labelTest);
        listPane.add(Box.createRigidArea(new Dimension(0, 5)));
        listPane.add(listScroller);
        listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // Lay out the buttons from left to right.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
        buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        buttonPane.add(Box.createHorizontalStrut(60));
        buttonPane.add(delbtn);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(cancel);

        listPane.add(buttonPane);

        // Put everything together, using the content pane's BorderLayout.
        Container contentPane = getContentPane();
        contentPane.add(listPane, BorderLayout.CENTER);
        contentPane.add(buttonPane, BorderLayout.PAGE_END);
        add(listPane);

        add(listPane);

        setTitle("JList models");
        setSize(300, 250);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class CheckListItem {
        private String label;
        private boolean isSelected = false;

        public CheckListItem(String label) {
            this.label = label;
        }

        public boolean isSelected() {
            return isSelected;
        }

        public void setSelected(boolean isSelected) {
            this.isSelected = isSelected;
        }

        public String toString() {
            return label;
        }
    }

    @SuppressWarnings({ "rawtypes", "serial" })
    class CheckListRenderer extends JCheckBox implements ListCellRenderer {
        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean hasFocus) {
            setEnabled(list.isEnabled());
            setSelected(((CheckListItem) value).isSelected());
            setFont(list.getFont());
            setBackground(list.getBackground());
            setForeground(list.getForeground());
            setText(value.toString());
            return this;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ListModels ex = new ListModels();
                ex.setVisible(true);
            }
        });
    }
}

感谢任何帮助。

已编辑:良好的 UI 设计

最佳答案

  1. 您需要向“删除”按钮添加一个 ActionListener。你有一个,但它被注释掉了。在此监听器中,您需要确定要保留/丢弃哪些项目。在您的尝试中,您将迭代 JList 的选择模型。相反,您需要迭代其数据模型。

  2. 当您通过以数组作为参数的构造函数将项目添加到 JList 时,您将获得一个为您实现的简单的 ListModel。不幸的是,ListModel 的 API 非常有限。没有 remove(...) 方法。解决此限制的一种方法是迭代 ListModel,并将未选择的模型添加到新模型中,然后在完成评估后将其设置到 JList 上。

类似于:

delbtn.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent event)
  {
    ListModel currentModel = list.getModel();
    DefaultListModel newModel = new DefaultListModel();

    for (int i = 0; i < currentModel.getSize(); i++)
    {
      CheckListItem item = (CheckListItem) currentModel.getElementAt(i);
      if (! item.isSelected())
      {
        newModel.addElement(item);
      }
    }
    list.setModel(newModel);
  }
});

关于java - 使用java swings删除选定的复选框而不使用Jtable/Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23347169/

相关文章:

java - 获取 Java Swing 组件的内容

java - 增加 JTextArea 上点指示器的大小

java - JComboBox 未填充数据库 JDBC 信息 - Java

java - UI 中的 JList 未反射(reflect)所有对等进程的更改

java - 按住 ALT 键并单击,删除 JList 上选定的元素

java - ActiveJDBC 和带引号的标识符

java - Java方法签名语法

java - Seedstack 中的存储库和查找器有什么区别?

java - 从 jython 调用 java 方法的右重载

java - 单击按钮时的递归搜索文件方法