使用JList实现左右数据移动Dual JList with buttons in between

http://www.java2s.com/Code/Java/Swing-JFC/DualJListwithbuttonsinbetween.htm



import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
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;

public class DualListBox extends JPanel {

  private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0);

  private static final String ADD_BUTTON_LABEL = "Add >>";

  private static final String REMOVE_BUTTON_LABEL = "<< Remove";

  private static final String DEFAULT_SOURCE_CHOICE_LABEL = "Available Choices";

  private static final String DEFAULT_DEST_CHOICE_LABEL = "Your Choices";

  private JLabel sourceLabel;

  private JList sourceList;

  private SortedListModel sourceListModel;

  private JList destList;

  private SortedListModel destListModel;

  private JLabel destLabel;

  private JButton addButton;

  private JButton removeButton;

  public DualListBox() {
    initScreen();
  }

  public String getSourceChoicesTitle() {
    return sourceLabel.getText();
  }

  public void setSourceChoicesTitle(String newValue) {
    sourceLabel.setText(newValue);
  }

  public String getDestinationChoicesTitle() {
    return destLabel.getText();
  }

  public void setDestinationChoicesTitle(String newValue) {
    destLabel.setText(newValue);
  }

  public void clearSourceListModel() {
    sourceListModel.clear();
  }

  public void clearDestinationListModel() {
    destListModel.clear();
  }

  public void addSourceElements(ListModel newValue) {
    fillListModel(sourceListModel, newValue);
  }

  public void setSourceElements(ListModel newValue) {
    clearSourceListModel();
    addSourceElements(newValue);
  }

  public void addDestinationElements(ListModel newValue) {
    fillListModel(destListModel, newValue);
  }

  private void fillListModel(SortedListModel model, ListModel newValues) {
    int size = newValues.getSize();
    for (int i = 0; i < size; i++) {
      model.add(newValues.getElementAt(i));
    }
  }

  public void addSourceElements(Object newValue[]) {
    fillListModel(sourceListModel, newValue);
  }

  public void setSourceElements(Object newValue[]) {
    clearSourceListModel();
    addSourceElements(newValue);
  }

  public void addDestinationElements(Object newValue[]) {
    fillListModel(destListModel, newValue);
  }

  private void fillListModel(SortedListModel model, Object newValues[]) {
    model.addAll(newValues);
  }

  public Iterator sourceIterator() {
    return sourceListModel.iterator();
  }

  public Iterator destinationIterator() {
    return destListModel.iterator();
  }

  public void setSourceCellRenderer(ListCellRenderer newValue) {
    sourceList.setCellRenderer(newValue);
  }

  public ListCellRenderer getSourceCellRenderer() {
    return sourceList.getCellRenderer();
  }

  public void setDestinationCellRenderer(ListCellRenderer newValue) {
    destList.setCellRenderer(newValue);
  }

  public ListCellRenderer getDestinationCellRenderer() {
    return destList.getCellRenderer();
  }

  public void setVisibleRowCount(int newValue) {
    sourceList.setVisibleRowCount(newValue);
    destList.setVisibleRowCount(newValue);
  }

  public int getVisibleRowCount() {
    return sourceList.getVisibleRowCount();
  }

  public void setSelectionBackground(Color newValue) {
    sourceList.setSelectionBackground(newValue);
    destList.setSelectionBackground(newValue);
  }

  public Color getSelectionBackground() {
    return sourceList.getSelectionBackground();
  }

  public void setSelectionForeground(Color newValue) {
    sourceList.setSelectionForeground(newValue);
    destList.setSelectionForeground(newValue);
  }

  public Color getSelectionForeground() {
    return sourceList.getSelectionForeground();
  }

  private void clearSourceSelected() {
    Object selected[] = sourceList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
      sourceListModel.removeElement(selected[i]);
    }
    sourceList.getSelectionModel().clearSelection();
  }

  private void clearDestinationSelected() {
    Object selected[] = destList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
      destListModel.removeElement(selected[i]);
    }
    destList.getSelectionModel().clearSelection();
  }

  private void initScreen() {
    setBorder(BorderFactory.createEtchedBorder());
    setLayout(new GridBagLayout());
    sourceLabel = new JLabel(DEFAULT_SOURCE_CHOICE_LABEL);
    sourceListModel = new SortedListModel();
    sourceList = new JList(sourceListModel);
    add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5,
        1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
        EMPTY_INSETS, 0, 0));

    addButton = new JButton(ADD_BUTTON_LABEL);
    add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    addButton.addActionListener(new AddListener());
    removeButton = new JButton(REMOVE_BUTTON_LABEL);
    add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25,
        GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
            0, 5, 0, 5), 0, 0));
    removeButton.addActionListener(new RemoveListener());

    destLabel = new JLabel(DEFAULT_DEST_CHOICE_LABEL);
    destListModel = new SortedListModel();
    destList = new JList(destListModel);
    add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0,
        GridBagConstraints.CENTER, GridBagConstraints.NONE,
        EMPTY_INSETS, 0, 0));
    add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5,
        1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
        EMPTY_INSETS, 0, 0));
  }

  public static void main(String args[]) {
    JFrame f = new JFrame("Dual List Box Tester");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DualListBox dual = new DualListBox();
    dual.addSourceElements(new String[] { "One", "Two", "Three" });
    dual.addSourceElements(new String[] { "Four", "Five", "Six" });
    dual.addSourceElements(new String[] { "Seven", "Eight", "Nine" });
    dual.addSourceElements(new String[] { "Ten", "Eleven", "Twelve" });
    dual
        .addSourceElements(new String[] { "Thirteen", "Fourteen",
            "Fifteen" });
    dual.addSourceElements(new String[] { "Sixteen", "Seventeen",
        "Eighteen" });
    dual.addSourceElements(new String[] { "Nineteen", "Twenty", "Thirty" });
    f.getContentPane().add(dual, BorderLayout.CENTER);
    f.setSize(400, 300);
    f.setVisible(true);
  }

  private class AddListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Object selected[] = sourceList.getSelectedValues();
      addDestinationElements(selected);
      clearSourceSelected();
    }
  }

  private class RemoveListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Object selected[] = destList.getSelectedValues();
      addSourceElements(selected);
      clearDestinationSelected();
    }
  }
}

class SortedListModel extends AbstractListModel {

  SortedSet model;

  public SortedListModel() {
    model = new TreeSet();
  }

  public int getSize() {
    return model.size();
  }

  public Object getElementAt(int index) {
    return model.toArray()[index];
  }

  public void add(Object element) {
    if (model.add(element)) {
      fireContentsChanged(this, 0, getSize());
    }
  }

  public void addAll(Object elements[]) {
    Collection c = Arrays.asList(elements);
    model.addAll(c);
    fireContentsChanged(this, 0, getSize());
  }

  public void clear() {
    model.clear();
    fireContentsChanged(this, 0, getSize());
  }

  public boolean contains(Object element) {
    return model.contains(element);
  }

  public Object firstElement() {
    return model.first();
  }

  public Iterator iterator() {
    return model.iterator();
  }

  public Object lastElement() {
    return model.last();
  }

  public boolean removeElement(Object element) {
    boolean removed = model.remove(element);
    if (removed) {
      fireContentsChanged(this, 0, getSize());
    }
    return removed;
  }
}

 

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class DualTableFrame extends JFrame {

    private JTable leftTable;
    private JTable rightTable;
    private JButton addButton;
    private JButton removeButton;

    public DualTableFrame() {
 
        this.setSize(666, 668);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        setTitle("Dual wielding tables");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLayout(new GridBagLayout());

        leftTable = new JTable(new SimpleColorTableModel());
        rightTable = new JTable(new SimpleColorTableModel());

        setupTable(leftTable);
        setupTable(rightTable);

        populate((SimpleColorTableModel) leftTable.getModel());

        addButton = new JButton("Add >>");
        removeButton = new JButton("<< Remove");

        JPanel pnlActions = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        pnlActions.add(addButton, gbc);

        gbc.gridy++;
        pnlActions.add(removeButton, gbc);

        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.33;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        add(new JLabel("Available Choices"), gbc);
        gbc.gridx++;
        add(new JPanel(), gbc);
        gbc.gridx++;
        add(new JLabel("Your Choices"), gbc);

        gbc.gridy++;
        gbc.gridx = 0;
        gbc.weighty++;
        gbc.fill = GridBagConstraints.BOTH;

        add(new JScrollPane(leftTable), gbc);
        gbc.gridx++;
        add(pnlActions, gbc);
        gbc.gridx++;
        add(new JScrollPane(rightTable), gbc);

        setSize(400, 600);

        addButton.setEnabled(false);
        removeButton.setEnabled(false);

        leftTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {

                int count = leftTable.getSelectedRowCount();
                addButton.setEnabled(count > 0);

            }
        });
        rightTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {

                int count = leftTable.getSelectedRowCount();
                removeButton.setEnabled(count > 0);

            }
        });

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                moveSelectedRow(leftTable, rightTable);

            }
        });

        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                moveSelectedRow(rightTable, leftTable);

            }
        });

    }

    protected void moveSelectedRow(JTable from, JTable to) {

        SimpleColorTableModel fromModel = (SimpleColorTableModel) from.getModel();
        SimpleColorTableModel toModel = (SimpleColorTableModel) to.getModel();

        for (int index : from.getSelectedRows()) {

            Vector rowValue = (Vector) fromModel.getDataVector().get(index);

            toModel.addRow(rowValue);

        }

        int selectedRow = -1;
        while ((selectedRow = from.getSelectedRow()) != -1) {

            fromModel.removeRow(selectedRow);

        }

        from.clearSelection();

    }

    protected void populate(SimpleColorTableModel model) {

        model.addRow(new Object[]{"Black", Color.BLACK});
        model.addRow(new Object[]{"Blue", Color.BLUE});
        model.addRow(new Object[]{"Cyan", Color.CYAN});
        model.addRow(new Object[]{"Dark Gray", Color.DARK_GRAY});
        model.addRow(new Object[]{"Gray", Color.GRAY});
        model.addRow(new Object[]{"Green", Color.GREEN});
        model.addRow(new Object[]{"Light Gary", Color.LIGHT_GRAY});
        model.addRow(new Object[]{"Mangenta", Color.MAGENTA});
        model.addRow(new Object[]{"Orange", Color.ORANGE});
        model.addRow(new Object[]{"Pink", Color.PINK});
        model.addRow(new Object[]{"Red", Color.RED});
        model.addRow(new Object[]{"White", Color.WHITE});
        model.addRow(new Object[]{"Yellow", Color.YELLOW});

    }

    protected void setupTable(JTable table) {

        table.setFillsViewportHeight(true);

        table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());

    }
    
    private class ColorTableCellRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            setText(null);
            if (value instanceof Color) {

                setOpaque(true);
                setBackground((Color)value);

            }

            return this;

        }

    }
    private class SimpleColorTableModel extends DefaultTableModel {

        public SimpleColorTableModel() {

            addColumn("Name");
            addColumn("Color");

        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {

            Class clazz = String.class;

            switch (columnIndex) {

                case 1:
                    clazz = Color.class;
                    break;

            }

            return clazz;

        }

    }
    
    public static void main(String[] args) { 
    	String array = "abcdefghadefbWwsWFtfF";
    	//listAll(array);
    	//testSwitch();
    	new DualTableFrame();
    }
}



 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值