2

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

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

Any Help is appreciated.

EDITED: For Good UI Design

Rajesh Hatwar
  • 1,843
  • 6
  • 39
  • 58
  • Are you trying to delete the items that are selected via a JList selection, or the items that are checked? Note that these are not the same. – splungebob Apr 28 '14 at 19:04
  • @splungebob I am new to Jlist, I want like if you add some elements to the arraylist through remove method i can remove the element and that element not present in the list, so if i remove element from Jlist it has to remove from list and it has to reflect to the GUI application – Rajesh Hatwar Apr 29 '14 at 04:22
  • after clicking on delete button i want to delete checked checkbox(s) – Rajesh Hatwar Apr 29 '14 at 12:35

1 Answers1

2
  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.

  2. 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.

Something like:

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);
  }
});
splungebob
  • 5,357
  • 2
  • 22
  • 45
  • @RajeshHatwar The Oracle tutorials have good explanations on how to use each component: http://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html – splungebob Apr 29 '14 at 17:06
  • Thanks for your efforts you are like a swing genius!!. I want to ask a question, according to you which book or tutorial is helpful to learn swings. If swing is outdated which UI is currently using for corejava and tell me any online tutorial or book. – Rajesh Hatwar Apr 29 '14 at 17:11
  • @splungebob :according to your code every time you are creating new defaultlist model it will effect on performance suppose if some 500 checkbox is present right. – Raki Apr 30 '14 at 06:02
  • @Raki It's only creating a new model once, when the user clicks Delete, at the end of the loop (not in the loop). I don't imagine a performance issue even if there were 5000 items. One could always start off with a `DefaultListModel`, thus needing only one. But then, the deletes *would* be in a loop, I suppose. (I don't have an IDE at the moment to check the API). – splungebob Apr 30 '14 at 13:14
  • @splungebob: your explanation is well, i was talking about, if it is 500 check boxes are there and if i delete checkboxes one by one at this time possibility of using delete button more compare to single delete of whole checkboxes at a time so, DefaultListModel will be create every time whenever i use the delete button here is my concern every time new DefaultListModel will create this leads to some performance issue right (it requires more memory in heap then more and more memory will leads to the program to terminate). – Raki May 01 '14 at 18:24