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