Question

i am doing one project related to swings in this i am facing one problem like some 5 check boxes are there in this if i delete two non immediate check boxes (or) single check box i am able to delete but if i delete two immediate check boxes i am not able to delete i.e i have check boxes like 1,2,3,4,5 if i delete 1 and 3 , 1 and 4 , or 3 and 5 etc... (or) 1,2,3 etc.. if i delete using this combination i am able to delete but if i delete 1 and 2 or 2 and 3 or 4 and 5 like immediate check boxes i am not able to delete i am new to swings i don't no what's happening wrong and where. when i am searching for the answer i found this link Deleting check boxes

The same program i am using the different approach, Here i am creating my own custom classes here my program:

import java.awt.*;
import java.util.*;

import javax.swing.*;

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

    @SuppressWarnings("rawtypes")
    private JList list;
    private JPanel rightPanel;
    JButton cancel = new JButton("Cancel");
    JButton delbtn = new JButton("Delete");

    public ListModels() {

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

    public ListModels(List<String> values) {
    }

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

        myModel mModel = new myModel(new CheckListItem[] {
                new CheckListItem("78"), new CheckListItem("79"),
                new CheckListItem("80"), new CheckListItem("81"),
                new CheckListItem("82") });
        list = new JList(mModel);

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

                if (item.isSelected) {
                    System.out.println("i am selected ");
                }

                // 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());

        // Cancel button
        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });

        // Cancel
        delbtn.addActionListener(new ActionListener() {
            @SuppressWarnings("rawtypes")
            public void actionPerformed(ActionEvent event) {

                // CheckListItem item = (CheckListItem)
                // list.getModel().getElementAt(index);
            int dialogButton = JOptionPane.YES_NO_OPTION;
            int dialogResult = JOptionPane.showConfirmDialog(null,
                        "Are you sure you want to delete the selected map",
                        "Delete", dialogButton);
                myModel mModel = (myModel) list.getModel();

                ListModel currentModel = list.getModel();
                for (int i = 0; i < mModel.getSize(); i++) {
                CheckListItem item = (CheckListItem) mModel.getElementAt(i);

                    if(!item.isSelected)
                    {
                        System.out.println("i am in not selected item "+item);
                    }

                    else if (item.isSelected()) {

                        System.out.println("i am selected item "+item);

                        if (dialogResult == JOptionPane.YES_OPTION) {
                            // Location loc=(Location) mModel.getElementAt(i);
                            mModel.removeAt(i);
                            mModel.fireIntervalRemoved(this, i,mModel.getSize());
                        }

                    }
                }


            }

        });

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

        // Add all to the panel
        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("Delete Map");
        setSize(300, 250);
        setLocationRelativeTo(null);

    }

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

    class myModel extends AbstractListModel<CheckListItem> {

        private List<CheckListItem> items;

        public myModel(CheckListItem[] items) {
            super();
            this.items = new ArrayList<ListModels.CheckListItem>();
            for (CheckListItem item : items) {
                this.items.add(item);
            }
        }

        /*
         * @Override protected void fireContentsChanged(Object Source, int
         * index0, int index1) { super.fireContentsChanged(Source, index0,
         * index1); }
         */

        @Override
        public CheckListItem getElementAt(int index) {
            return items.get(index);
        }

        @Override
        protected void fireIntervalRemoved(Object Source, int index0, int index1) {
            // TODO Auto-generated method stub
            super.fireIntervalRemoved(Source, index0, index1);
        }

        @Override
        public int getSize() {
            return items.size();
        }

        public void removeAt(int item) {
            items.remove(item);
        }

        public void addAt(int index, CheckListItem item) {
            items.set(index, item);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                List<String> values = new ArrayList<String>();
                values.addAll(newList);
                ListModels ex = new ListModels();
                ex.setVisible(true);
            }
        });
    }
}

Finally in this program i am loading the check boxes through my custom class directly giving numbers ,I want to call this class from my main method and pass the numbers through Array list or array. Any HELP IS WELCOME and THANKS.

Was it helpful?

Solution

for (int i = 0; i < mModel.getSize(); i++)

You need to start at the end of the list and work backwards:

for (int i = mModel.getSize() - 1; i >=0; i--)

because if you start at 0, all the rows will shift down by one when the row is removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top