Java Swing Components : CheckBox List

  1.  CheckBox List
  2. Check List Example
  3. Check List Example 2
  4. ToolTip List Example
  5. Editable List Example
  6. DND Drag and drop Lis
CheckBox List

import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

public class CheckBoxList extends JList {

  public CheckBoxList() {
    super();

    setModel(new DefaultListModel());
    setCellRenderer(new CheckboxCellRenderer());

    addMouseListener(new MouseAdapter() {
      @Override
      public void mousePressed(MouseEvent e) {
        int index = locationToIndex(e.getPoint());

        if (index != -1) {
          Object obj = getModel().getElementAt(index);
          if (obj instanceof JCheckBox) {
            JCheckBox checkbox = (JCheckBox) obj;

            checkbox.setSelected(!checkbox.isSelected());
            repaint();
          }
        }
      }
    }

    );

    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  }

  @SuppressWarnings("unchecked")
  public int[] getCheckedIdexes() {
    java.util.List list = new java.util.ArrayList();
    DefaultListModel dlm = (DefaultListModel) getModel();
    for (int i = 0; i < dlm.size(); ++i) {
      Object obj = getModel().getElementAt(i);
      if (obj instanceof JCheckBox) {
        JCheckBox checkbox = (JCheckBox) obj;
        if (checkbox.isSelected()) {
          list.add(new Integer(i));
        }
      }
    }

    int[] indexes = new int[list.size()];

    for (int i = 0; i < list.size(); ++i) {
      indexes[i] = ((Integer) list.get(i)).intValue();
    }

    return indexes;
  }

  @SuppressWarnings("unchecked")
  public java.util.List getCheckedItems() {
    java.util.List list = new java.util.ArrayList();
    DefaultListModel dlm = (DefaultListModel) getModel();
    for (int i = 0; i < dlm.size(); ++i) {
      Object obj = getModel().getElementAt(i);
      if (obj instanceof JCheckBox) {
        JCheckBox checkbox = (JCheckBox) obj;
        if (checkbox.isSelected()) {
          list.add(checkbox);
        }
      }
    }
    return list;
  }
}

/*
 * Copyright (C) 2005 - 2007 JasperSoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 * 
 * Unless you have purchased a commercial license agreement from JasperSoft, the
 * following license terms apply:
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2 as published by the
 * Free Software Foundation.
 * 
 * This program is distributed WITHOUT ANY WARRANTY; and without the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses/gpl.txt or write to:
 * 
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA USA
 * 02111-1307
 * 
 * 
 * 
 * 
 * CheckboxCellRenderer.java
 * 
 * Created on October 5, 2006, 10:03 AM
 * 
 */

/**
 * 
 * @author gtoffoli
 */
class CheckboxCellRenderer extends DefaultListCellRenderer {
  protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    if (value instanceof CheckBoxListEntry) {
      CheckBoxListEntry checkbox = (CheckBoxListEntry) value;
      checkbox.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
      if (checkbox.isRed()) {
        checkbox.setForeground(Color.red);
      } else {
        checkbox.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
      }
      checkbox.setEnabled(isEnabled());
      checkbox.setFont(getFont());
      checkbox.setFocusPainted(false);
      checkbox.setBorderPainted(true);
      checkbox.setBorder(isSelected ? UIManager.getBorder("List.focusCellHighlightBorder")
          : noFocusBorder);

      return checkbox;
    } else {
      return super.getListCellRendererComponent(list, value.getClass().getName(), index,
          isSelected, cellHasFocus);
    }
  }
}

/*
 * Copyright (C) 2005 - 2007 JasperSoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 * 
 * Unless you have purchased a commercial license agreement from JasperSoft, the
 * following license terms apply:
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2 as published by the
 * Free Software Foundation.
 * 
 * This program is distributed WITHOUT ANY WARRANTY; and without the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses/gpl.txt or write to:
 * 
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA USA
 * 02111-1307
 * 
 * 
 * 
 * 
 * CheckBoxListEntry.java
 * 
 * Created on October 5, 2006, 10:19 AM
 * 
 */

/**
 * 
 * @author gtoffoli
 */
class CheckBoxListEntry extends JCheckBox {

  private Object value = null;

  private boolean red = false;

  public CheckBoxListEntry(Object itemValue, boolean selected) {
    super(itemValue == null ? "" : "" + itemValue, selected);
    setValue(itemValue);
  }

  public boolean isSelected() {
    return super.isSelected();
  }

  public void setSelected(boolean selected) {
    super.setSelected(selected);
  }

  public Object getValue() {
    return value;
  }

  public void setValue(Object value) {
    this.value = value;
  }

  public boolean isRed() {
    return red;
  }

  public void setRed(boolean red) {
    this.red = red;
  }

}
Check List Example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;

import javax.swing.Icon;
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.JTextArea;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;

/**
 * @version 1.0 04/24/99
 */
public class CheckListExample extends JFrame {

  public CheckListExample() {
    super("CheckList Example");
    String[] strs = { "swing", "home", "basic", "metal", "JList" };

    final JList list = new JList(createData(strs));

    // set "home" icon
    Icon icon = MetalIconFactory.getFileChooserHomeFolderIcon();
    ((CheckableItem) list.getModel().getElementAt(1)).setIcon(icon);

    list.setCellRenderer(new CheckListRenderer());
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(new EmptyBorder(0, 4, 0, 0));
    list.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        int index = list.locationToIndex(e.getPoint());
        CheckableItem item = (CheckableItem) list.getModel()
            .getElementAt(index);
        item.setSelected(!item.isSelected());
        Rectangle rect = list.getCellBounds(index, index);
        list.repaint(rect);
      }
    });
    JScrollPane sp = new JScrollPane(list);

    final JTextArea textArea = new JTextArea(3, 10);
    JScrollPane textPanel = new JScrollPane(textArea);
    JButton printButton = new JButton("print");
    printButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        ListModel model = list.getModel();
        int n = model.getSize();
        for (int i = 0; i < n; i++) {
          CheckableItem item = (CheckableItem) model.getElementAt(i);
          if (item.isSelected()) {
            textArea.append(item.toString());
            textArea.append(System.getProperty("line.separator"));
          }
        }
      }
    });
    JButton clearButton = new JButton("clear");
    clearButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textArea.setText("");
      }
    });
    JPanel panel = new JPanel(new GridLayout(2, 1));
    panel.add(printButton);
    panel.add(clearButton);

    getContentPane().add(sp, BorderLayout.CENTER);
    getContentPane().add(panel, BorderLayout.EAST);
    getContentPane().add(textPanel, BorderLayout.SOUTH);
  }

  private CheckableItem[] createData(String[] strs) {
    int n = strs.length;
    CheckableItem[] items = new CheckableItem[n];
    for (int i = 0; i < n; i++) {
      items[i] = new CheckableItem(strs[i]);
    }
    return items;
  }

  class CheckableItem {
    private String str;

    private boolean isSelected;

    private Icon icon;

    public CheckableItem(String str) {
      this.str = str;
      isSelected = false;
    }

    public void setSelected(boolean b) {
      isSelected = b;
    }

    public boolean isSelected() {
      return isSelected;
    }

    public String toString() {
      return str;
    }

    public void setIcon(Icon icon) {
      this.icon = icon;
    }

    public Icon getIcon() {
      return icon;
    }
  }

  class CheckListRenderer extends CheckRenderer implements ListCellRenderer {
    Icon commonIcon;

    public CheckListRenderer() {
      check.setBackground(UIManager.getColor("List.textBackground"));
      label.setForeground(UIManager.getColor("List.textForeground"));
      commonIcon = UIManager.getIcon("Tree.leafIcon");
    }

    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean hasFocus) {
      setEnabled(list.isEnabled());
      check.setSelected(((CheckableItem) value).isSelected());
      label.setFont(list.getFont());
      label.setText(value.toString());
      label.setSelected(isSelected);
      label.setFocus(hasFocus);
      Icon icon = ((CheckableItem) value).getIcon();
      if (icon == null) {
        icon = commonIcon;
      }
      label.setIcon(icon);
      return this;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    CheckListExample frame = new CheckListExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

class CheckRenderer extends JPanel implements TreeCellRenderer {
  protected JCheckBox check;

  protected TreeLabel label;

  public CheckRenderer() {
    setLayout(null);
    add(check = new JCheckBox());
    add(label = new TreeLabel());
    check.setBackground(UIManager.getColor("Tree.textBackground"));
    label.setForeground(UIManager.getColor("Tree.textForeground"));
  }

  public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean isSelected, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {
    String stringValue = tree.convertValueToText(value, isSelected,
        expanded, leaf, row, hasFocus);
    setEnabled(tree.isEnabled());
    check.setSelected(((CheckNode) value).isSelected());
    label.setFont(tree.getFont());
    label.setText(stringValue);
    label.setSelected(isSelected);
    label.setFocus(hasFocus);
    if (leaf) {
      label.setIcon(UIManager.getIcon("Tree.leafIcon"));
    } else if (expanded) {
      label.setIcon(UIManager.getIcon("Tree.openIcon"));
    } else {
      label.setIcon(UIManager.getIcon("Tree.closedIcon"));
    }
    return this;
  }

  public Dimension getPreferredSize() {
    Dimension d_check = check.getPreferredSize();
    Dimension d_label = label.getPreferredSize();
    return new Dimension(d_check.width + d_label.width,
        (d_check.height < d_label.height ? d_label.height
            : d_check.height));
  }

  public void doLayout() {
    Dimension d_check = check.getPreferredSize();
    Dimension d_label = label.getPreferredSize();
    int y_check = 0;
    int y_label = 0;
    if (d_check.height < d_label.height) {
      y_check = (d_label.height - d_check.height) / 2;
    } else {
      y_label = (d_check.height - d_label.height) / 2;
    }
    check.setLocation(0, y_check);
    check.setBounds(0, y_check, d_check.width, d_check.height);
    label.setLocation(d_check.width, y_label);
    label.setBounds(d_check.width, y_label, d_label.width, d_label.height);
  }

  public void setBackground(Color color) {
    if (color instanceof ColorUIResource)
      color = null;
    super.setBackground(color);
  }

  public class TreeLabel extends JLabel {
    boolean isSelected;

    boolean hasFocus;

    public TreeLabel() {
    }

    public void setBackground(Color color) {
      if (color instanceof ColorUIResource)
        color = null;
      super.setBackground(color);
    }

    public void paint(Graphics g) {
      String str;
      if ((str = getText()) != null) {
        if (0 < str.length()) {
          if (isSelected) {
            g.setColor(UIManager
                .getColor("Tree.selectionBackground"));
          } else {
            g.setColor(UIManager.getColor("Tree.textBackground"));
          }
          Dimension d = getPreferredSize();
          int imageOffset = 0;
          Icon currentI = getIcon();
          if (currentI != null) {
            imageOffset = currentI.getIconWidth()
                + Math.max(0, getIconTextGap() - 1);
          }
          g.fillRect(imageOffset, 0, d.width - 1 - imageOffset,
              d.height);
          if (hasFocus) {
            g.setColor(UIManager
                .getColor("Tree.selectionBorderColor"));
            g.drawRect(imageOffset, 0, d.width - 1 - imageOffset,
                d.height - 1);
          }
        }
      }
      super.paint(g);
    }

    public Dimension getPreferredSize() {
      Dimension retDimension = super.getPreferredSize();
      if (retDimension != null) {
        retDimension = new Dimension(retDimension.width + 3,
            retDimension.height);
      }
      return retDimension;
    }

    public void setSelected(boolean isSelected) {
      this.isSelected = isSelected;
    }

    public void setFocus(boolean hasFocus) {
      this.hasFocus = hasFocus;
    }
  }
}

class CheckNode extends DefaultMutableTreeNode {

  public final static int SINGLE_SELECTION = 0;

  public final static int DIG_IN_SELECTION = 4;

  protected int selectionMode;

  protected boolean isSelected;

  public CheckNode() {
    this(null);
  }

  public CheckNode(Object userObject) {
    this(userObject, true, false);
  }

  public CheckNode(Object userObject, boolean allowsChildren,
      boolean isSelected) {
    super(userObject, allowsChildren);
    this.isSelected = isSelected;
    setSelectionMode(DIG_IN_SELECTION);
  }

  public void setSelectionMode(int mode) {
    selectionMode = mode;
  }

  public int getSelectionMode() {
    return selectionMode;
  }

  public void setSelected(boolean isSelected) {
    this.isSelected = isSelected;

    if ((selectionMode == DIG_IN_SELECTION) && (children != null)) {
      Enumeration e = children.elements();
      while (e.hasMoreElements()) {
        CheckNode node = (CheckNode) e.nextElement();
        node.setSelected(isSelected);
      }
    }
  }

  public boolean isSelected() {
    return isSelected;
  }

  // If you want to change "isSelected" by CellEditor,
  /*
   * public void setUserObject(Object obj) { if (obj instanceof Boolean) {
   * setSelected(((Boolean)obj).booleanValue()); } else {
   * super.setUserObject(obj); } }
   */

}
Check List Example 2
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

/**
 * @version 1.0 04/26/99
 */
public class CheckListExample2 extends JFrame {

  public CheckListExample2() {
    super("CheckList Example");
    String[] strs = { "swing", "home", "basic", "metal", "JList" };

    final JList list = new JList(createData(strs));

    list.setCellRenderer(new CheckListRenderer());
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(new EmptyBorder(0, 4, 0, 0));
    list.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        int index = list.locationToIndex(e.getPoint());
        CheckableItem item = (CheckableItem) list.getModel()
            .getElementAt(index);
        item.setSelected(!item.isSelected());
        Rectangle rect = list.getCellBounds(index, index);
        list.repaint(rect);
      }
    });
    JScrollPane sp = new JScrollPane(list);

    final JTextArea textArea = new JTextArea(3, 10);
    JScrollPane textPanel = new JScrollPane(textArea);
    JButton printButton = new JButton("print");
    printButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        ListModel model = list.getModel();
        int n = model.getSize();
        for (int i = 0; i < n; i++) {
          CheckableItem item = (CheckableItem) model.getElementAt(i);
          if (item.isSelected()) {
            textArea.append(item.toString());
            textArea.append(System.getProperty("line.separator"));
          }
        }
      }
    });
    JButton clearButton = new JButton("clear");
    clearButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textArea.setText("");
      }
    });
    JPanel panel = new JPanel(new GridLayout(2, 1));
    panel.add(printButton);
    panel.add(clearButton);

    getContentPane().add(sp, BorderLayout.CENTER);
    getContentPane().add(panel, BorderLayout.EAST);
    getContentPane().add(textPanel, BorderLayout.SOUTH);
  }

  private CheckableItem[] createData(String[] strs) {
    int n = strs.length;
    CheckableItem[] items = new CheckableItem[n];
    for (int i = 0; i < n; i++) {
      items[i] = new CheckableItem(strs[i]);
    }
    return items;
  }

  class CheckableItem {
    private String str;

    private boolean isSelected;

    public CheckableItem(String str) {
      this.str = str;
      isSelected = false;
    }

    public void setSelected(boolean b) {
      isSelected = b;
    }

    public boolean isSelected() {
      return isSelected;
    }

    public String toString() {
      return str;
    }
  }

  class CheckListRenderer extends JCheckBox implements ListCellRenderer {

    public CheckListRenderer() {
      setBackground(UIManager.getColor("List.textBackground"));
      setForeground(UIManager.getColor("List.textForeground"));
    }

    public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean hasFocus) {
      setEnabled(list.isEnabled());
      setSelected(((CheckableItem) value).isSelected());
      setFont(list.getFont());
      setText(value.toString());
      return this;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    CheckListExample2 frame = new CheckListExample2();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

ToolTip List Example

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

/**
 * @version 1.0 08/26/99
 */
public class ToolTipListExample extends JFrame {

  public ToolTipListExample() {
    super("ToolTip Example");

    String[][] strs = { { "Acinonyx jutatus", "Cheetah" },
        { "Panthera leo", "Lion" }, { "Canis lupus", "Wolf" },
        { "Lycaon pictus", "Llycaon" }, { "Vulpes Vulpes", "Fox" } };

    JList list = new JList(createItems(strs)) {
      public String getToolTipText(MouseEvent e) {
        int index = locationToIndex(e.getPoint());
        if (-1 < index) {
          ToolTipItem item = (ToolTipItem) getModel().getElementAt(
              index);
          return item.getToolTipText();
        } else {
          //return super.getToolTipText();
          return null;
        }
      }
    };
    list.setToolTipText("");

    getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
  }

  Object[] createItems(String[][] strs) {
    ToolTipItem[] items = new ToolTipItem[strs.length];
    for (int i = 0; i < strs.length; i++) {
      items[i] = new ToolTipItem(strs[i][0], strs[i][1]);
    }
    return items;
  }

  class ToolTipItem {
    String obj;

    String toolTipText;

    public ToolTipItem(String obj, String text) {
      this.obj = obj;
      this.toolTipText = text;
    }

    public String getToolTipText() {
      return toolTipText;
    }

    public String toString() {
      return obj;
    }
  }

  public static void main(String args[]) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    ToolTipListExample frame = new ToolTipListExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    frame.setSize(140, 150);
    frame.setVisible(true);
  }
}
Editable List Example
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 * @version 1.0 12/24/98
 */
public class EditableListExample extends JFrame {

  public EditableListExample() {
    super("Editable List Example");

    String[] data = { "a", "b", "c", "d", "e", "f", "g" };

    JList list = new JList(data);
    JScrollPane scrollList = new JScrollPane(list);
    scrollList.setMinimumSize(new Dimension(100, 80));
    Box listBox = new Box(BoxLayout.Y_AXIS);
    listBox.add(scrollList);
    listBox.add(new JLabel("JList"));

    DefaultTableModel dm = new DefaultTableModel();
    Vector dummyHeader = new Vector();
    dummyHeader.addElement("");
    dm.setDataVector(strArray2Vector(data), dummyHeader);
    JTable table = new JTable(dm);
    table.setShowGrid(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollTable = new JScrollPane(table);
    scrollTable.setColumnHeader(null);
    scrollTable.setMinimumSize(new Dimension(100, 80));
    Box tableBox = new Box(BoxLayout.Y_AXIS);
    tableBox.add(scrollTable);
    tableBox.add(new JLabel("JTable"));

    Container c = getContentPane();
    c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
    c.add(listBox);
    c.add(new JSeparator(SwingConstants.VERTICAL));
    //c.add(new JLabel("test"));
    //c.add(new JSeparator(SwingConstants.HORIZONTAL));
    c.add(tableBox);
    setSize(220, 130);
    setVisible(true);
  }

  private Vector strArray2Vector(String[] str) {
    Vector vector = new Vector();
    for (int i = 0; i < str.length; i++) {
      Vector v = new Vector();
      v.addElement(str[i]);
      vector.addElement(v);
    }
    return vector;
  }

  public static void main(String[] args) {
    final EditableListExample frame = new EditableListExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}

DND Drag and drop List

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListModel;


public class DNDList extends JList implements DropTargetListener, DragSourceListener, DragGestureListener
{

  /**
   * enables this component to be a dropTarget
   */

  DropTarget dropTarget = null;

  /**
   * enables this component to be a Drag Source
   */
  DragSource dragSource = null;

  /**
   * constructor - initializes the DropTarget and DragSource.
   */

  public DNDList( ListModel dataModel )
  {
    super( dataModel );
    dropTarget = new DropTarget( this, this );
    dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_MOVE, this );
  }

  /**
   * is invoked when you are dragging over the DropSite
   * 
   */

  public void dragEnter( DropTargetDragEvent event )
  {

    // debug messages for diagnostics
    System.out.println( "dragEnter" );
    event.acceptDrag( DnDConstants.ACTION_MOVE );
  }

  /**
   * is invoked when you are exit the DropSite without dropping
   * 
   */

  public void dragExit( DropTargetEvent event )
  {
    System.out.println( "dragExit" );

  }

  /**
   * is invoked when a drag operation is going on
   * 
   */

  public void dragOver( DropTargetDragEvent event )
  {
    System.out.println( "dragOver" );
  }

  /**
   * a drop has occurred
   * 
   */

  public void drop( DropTargetDropEvent event )
  {

    try
    {
      Transferable transferable = event.getTransferable();

      // we accept only Strings
      if( transferable.isDataFlavorSupported( DataFlavor.stringFlavor ) )
      {

        event.acceptDrop( DnDConstants.ACTION_MOVE );
        String s = ( String )transferable.getTransferData( DataFlavor.stringFlavor );
        addElement( s );
        event.getDropTargetContext().dropComplete( true );
      }
      else
      {
        event.rejectDrop();
      }
    }
    catch( Exception exception )
    {
      System.err.println( "Exception" + exception.getMessage() );
      event.rejectDrop();
    }
  }

  /**
   * is invoked if the use modifies the current drop gesture
   * 
   */

  public void dropActionChanged( DropTargetDragEvent event )
  {
  }

  /**
   * a drag gesture has been initiated
   * 
   */

  public void dragGestureRecognized( DragGestureEvent event )
  {

    Object selected = getSelectedValue();
    if( selected != null )
    {
      StringSelection text = new StringSelection( selected.toString() );

      // as the name suggests, starts the dragging
      dragSource.startDrag( event, DragSource.DefaultMoveDrop, text, this );
    }
    else
    {
      System.out.println( "nothing was selected" );
    }
  }

  /**
   * this message goes to DragSourceListener, informing it that the dragging
   * has ended
   * 
   */

  public void dragDropEnd( DragSourceDropEvent event )
  {
    if( event.getDropSuccess() )
    {
      removeElement();
    }
  }

  /**
   * this message goes to DragSourceListener, informing it that the dragging
   * has entered the DropSite
   * 
   */

  public void dragEnter( DragSourceDragEvent event )
  {
    System.out.println( " dragEnter" );
  }

  /**
   * this message goes to DragSourceListener, informing it that the dragging
   * has exited the DropSite
   * 
   */

  public void dragExit( DragSourceEvent event )
  {
    System.out.println( "dragExit" );

  }

  /**
   * this message goes to DragSourceListener, informing it that the dragging is
   * currently ocurring over the DropSite
   * 
   */

  public void dragOver( DragSourceDragEvent event )
  {
    System.out.println( "dragExit" );

  }

  /**
   * is invoked when the user changes the dropAction
   * 
   */

  public void dropActionChanged( DragSourceDragEvent event )
  {
    System.out.println( "dropActionChanged" );
  }

  /**
   * adds elements to itself
   * 
   */

  public void addElement( Object s )
  {
    ( ( DefaultListModel )getModel() ).addElement( s.toString() );
  }

  /**
   * removes an element from itself
   */

  public void removeElement()
  {
    ( ( DefaultListModel )getModel() ).removeElement( getSelectedValue() );
  }

}