使用Java Swing删除选定的复选框而不使用Jtable/Database [英] Deleting Selected Checkbox using java swings without using Jtable/Database

查看:68
本文介绍了使用Java Swing删除选定的复选框而不使用Jtable/Database的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swing的新手,尝试通过单击Java Swing中的删除按钮来删除选定的复选框,我尝试使用

I am new to swings, trying to delete selected checkbox on click of delete button in java swings, i tried by using

"DefaultListModel",在这里我可以删除普通数据,而无需在此处输入我的代码的复选框:

"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设计

EDITED: For Good UI Design

推荐答案

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

  1. You need to add an ActionListener to your Delete button. You have one but it's commented out. In this listener, you need to determine which items to keep/discard. In your attempt, you iterate over the JList's selection model. Instead, you need to iterate over it's data model.

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

When you add items to a JList via its constructor that takes an array as a parameter, you get a bare-bones ListModel implemented for you. Unfortunately, the API for ListModel is very limiting. There's no remove(...) method. One way around this limitation is to iterate over the ListModel, and add the ones that aren't selected to a new model, which we can then set onto the JList when we're done evaluating.

类似的东西:

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 Swing删除选定的复选框而不使用Jtable/Database的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆