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

时间:2014-04-28 17:13:07

标签: java swing jlist jcheckbox

我是摇摆新手,尝试删除java swings中单击删除按钮时选中的复选框,我尝试使用

  

" DefaultListModel" ,在这里我可以删除普通数据,而不是复选框,我的代码:

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);
            }
        });
    }
}

感谢任何帮助。

已编辑:适用于良好的用户界面设计

1 个答案:

答案 0 :(得分:2)

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

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

    < / LI>

    类似的东西:

    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);
      }
    });