Example usage for javax.swing JTable JTable

List of usage examples for javax.swing JTable JTable

Introduction

In this page you can find the example usage for javax.swing JTable JTable.

Prototype

public JTable(TableModel dm) 

Source Link

Document

Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.

Usage

From source file:org.jfree.expdemo.SelectionDemo4.java

/**
 * Creates a new demo.// w w  w.  j  av  a  2  s. c  o m
 * 
 * @param title
 *            the frame title.
 */
public SelectionDemo4(String title) {
    super(title);
    ChartPanel chartPanel = (ChartPanel) createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    this.dataset = (SimpleHistogramDataset) plot.getDataset();
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);

    this.model = new DefaultTableModel(new String[] { "Item:", "Bin Start::", "Bin End:", "Value:" }, 0);
    this.table = new JTable(this.model);
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);
}

From source file:gui.TwopointPWDPanel.java

private JPanel createControls() {
    // Marker model (for ordered list of markers)
    markerModel = new PWDTableModel();

    // Populate the marker table
    markerTable = new JTable(markerModel);
    markerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    markerTable.getColumnModel().getColumn(1).setPreferredWidth(175);
    markerTable.getColumnModel().getColumn(2).setPreferredWidth(60);
    for (CMarker cm : order.getLinkageGroup().getMarkers()) {
        markerModel.addRow(new Object[] { cm.marker.getPrefix(), cm, cm.marker.getRatio() });
    }// ww  w  .  j a  va  2 s . co m
    markerTable.getSelectionModel().addListSelectionListener(this);

    // Phase model (for scores of each ordered marker against the others)
    phaseModel = new PWDTableModel2();
    phaseModel.setColumnIdentifiers(new Object[] { "Graph Code", "Marker Name", "Recom Freq", "LOD Score" });

    phaseTable = new JTable(phaseModel);
    phaseTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    phaseTable.getSelectionModel().addListSelectionListener(this);

    rfqChart = new PWDChartPanel("Recombination Freq");
    lodChart = new PWDChartPanel("LOD Score");

    m1Label = new JLabel("");
    m1Label.setFont(new Font("Monospaced", Font.PLAIN, 11));
    m2Label = new JLabel("");
    m2Label.setFont(new Font("Monospaced", Font.PLAIN, 11));

    JScrollPane mSP = new JScrollPane(markerTable);
    mSP.setPreferredSize(new Dimension(300, 10));

    JPanel p1 = new JPanel(new BorderLayout(5, 0));
    p1.add(new JLabel("Ordered Markers:"), BorderLayout.NORTH);
    p1.add(mSP);

    JPanel p2 = new JPanel(new BorderLayout(5, 0));
    p2.add(new JLabel("Scores:"), BorderLayout.NORTH);
    p2.add(new JScrollPane(phaseTable));

    JPanel p3 = new JPanel(new GridLayout(2, 1, 2, 2));
    p3.setBorder(BorderFactory.createLoweredBevelBorder());
    p3.add(m1Label);
    p3.add(m2Label);

    JPanel p4 = new JPanel(new GridLayout(1, 2, 5, 5));
    p4.add(rfqChart);
    p4.add(lodChart);

    JPanel p5 = new JPanel(new BorderLayout(5, 5));
    p5.add(p3, BorderLayout.NORTH);
    p5.add(p4, BorderLayout.CENTER);

    JSplitPane splits = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splits.setResizeWeight(0.5);
    splits.setLeftComponent(p1);
    splits.setRightComponent(p2);

    JPanel p6 = new JPanel(new BorderLayout(5, 5));
    p6.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    p6.add(splits);
    p6.add(p5, BorderLayout.SOUTH);

    return p6;
}

From source file:gui.TwopointPWDPanelnonsnp.java

private JPanel createControls() {
    // Marker model (for ordered list of markers)
    markerModel = new PWDTableModel();

    // Populate the marker table
    markerTable = new JTable(markerModel);
    markerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    markerTable.getColumnModel().getColumn(0).setPreferredWidth(60);
    markerTable.getColumnModel().getColumn(1).setPreferredWidth(130);
    markerTable.getColumnModel().getColumn(2).setPreferredWidth(50);// ratio
    markerTable.getColumnModel().getColumn(3).setPreferredWidth(70);// geno
    markerTable.getColumnModel().getColumn(4).setPreferredWidth(50);// p1
    markerTable.getColumnModel().getColumn(5).setPreferredWidth(50);// p2
    for (CMarker cm : order.getLinkageGroup().getMarkers()) {
        markerModel.addRow(new Object[] { cm.marker.getPrefix(), cm, cm.marker.getRatio(),
                cm.marker.getRatioGenotypes(), "0000", "0000" });
    }/*from   w ww . j a  va  2s  .  c om*/
    markerTable.getSelectionModel().addListSelectionListener(this);

    if (order.rows != null) {
        int row = 0;
        for (String[] data : order.rows) {
            for (int i = 0; i < 2; i++) {
                markerModel.setValueAt(data[i], row, i + 4);
            }
            row++;
        }
    } else {
        order.rows = getSelection();
    }

    // Phase model (for scores of each ordered marker against the others)
    phaseModel = new PWDTableModel2();
    phaseModel.setColumnIdentifiers(new Object[] { "Graph Code", "Marker Name", "Recom Freq", "LOD Score" });

    phaseTable = new JTable(phaseModel);
    phaseTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    phaseTable.getSelectionModel().addListSelectionListener(this);

    rfqChart = new PWDChartPanel("Recombination Freq");
    lodChart = new PWDChartPanel("LOD Score");

    m1Label = new JLabel("");
    m1Label.setFont(new Font("Monospaced", Font.PLAIN, 11));
    m2Label = new JLabel("");
    m2Label.setFont(new Font("Monospaced", Font.PLAIN, 11));

    JScrollPane mSP = new JScrollPane(markerTable);
    mSP.setPreferredSize(new Dimension(300, 10));

    JPanel p1 = new JPanel(new BorderLayout(5, 0));
    p1.add(new JLabel("Ordered Markers:"), BorderLayout.NORTH);
    p1.add(mSP);

    JPanel p2 = new JPanel(new BorderLayout(5, 0));
    p2.add(new JLabel("Scores:"), BorderLayout.NORTH);
    p2.add(new JScrollPane(phaseTable));

    JPanel p3 = new JPanel(new GridLayout(2, 1, 2, 2));
    p3.setBorder(BorderFactory.createLoweredBevelBorder());
    p3.add(m1Label);
    p3.add(m2Label);

    JPanel p4 = new JPanel(new GridLayout(1, 2, 5, 5));
    p4.add(rfqChart);
    p4.add(lodChart);

    JPanel p5 = new JPanel(new BorderLayout(5, 5));
    p5.add(p3, BorderLayout.NORTH);
    p5.add(p4, BorderLayout.CENTER);

    JSplitPane splits = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splits.setResizeWeight(0.5);
    splits.setLeftComponent(p1);
    splits.setRightComponent(p2);

    JPanel p6 = new JPanel(new BorderLayout(5, 5));
    p6.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    p6.add(splits);
    p6.add(p5, BorderLayout.SOUTH);

    return p6;
}

From source file:dbseer.gui.panel.DBSeerLiveMonitorPanel.java

public DBSeerLiveMonitorPanel() {
    this.setLayout(new MigLayout("fill"));

    numTransactionType = 0;//from   w  w  w . j a va 2s .  co m
    transactionNames = new ArrayList<String>();
    monitorTable = new JTable(new DefaultTableModel(null, new String[] { "Name", "Value" }) {
        @Override
        public boolean isCellEditable(int i, int i1) {
            return false;
        }
    });

    monitorTable.setFillsViewportHeight(true);
    monitorTable.getColumnModel().getColumn(0).setMaxWidth(1200);
    monitorTable.getColumnModel().getColumn(0).setPreferredWidth(1200);
    monitorTable.getColumnModel().getColumn(1).setMaxWidth(200);
    monitorTable.getColumnModel().getColumn(1).setPreferredWidth(200);
    monitorTable.setRowHeight(20);

    for (String header : tableHeaders) {
        DefaultTableModel model = (DefaultTableModel) monitorTable.getModel();
        model.addRow(new Object[] { header, "0.0" });
    }

    transactionLabels = new ArrayList<JLabel>();
    transactionDeleteButtons = new ArrayList<JButton>();
    transactionRenameButtons = new ArrayList<JButton>();
    transactionViewSampleButtons = new ArrayList<JButton>();
    transactionEnableDisableButtons = new ArrayList<JButton>();

    initialize();
}

From source file:TableDialogEditDemo.java

public TableDialogEditDemo() {
    super(new GridLayout(1, 0));

    JTable table = new JTable(new MyTableModel());
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Set up renderer and editor for the Favorite Color column.
    table.setDefaultRenderer(Color.class, new ColorRenderer(true));
    table.setDefaultEditor(Color.class, new ColorEditor());

    //Add the scroll pane to this panel.
    add(scrollPane);/* w  ww .  j  a va  2s. c om*/
}

From source file:view.tabtables.EmulationTablesDrawer.java

protected void tablesInitialize() {
    JScrollPane scroll;//  w w w.  j  av a 2  s . c o m

    logTable = new JTable(new StringTableModel(new Object[0][0], new Object[0]));
    logTable.getTableHeader().setReorderingAllowed(false);
    scroll = new JScrollPane(logTable);
    scroll.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(scroll);

    statisticTable = new JTable(new StringTableModel(new Object[0][0], new Object[0]));
    statisticTable.getTableHeader().setReorderingAllowed(false);
    scroll = new JScrollPane(statisticTable);
    scroll.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(scroll);

    changingMarkStatisticTable = new JTable(new StringTableModel(new Object[0][0], new Object[0]));
    changingMarkStatisticTable.getTableHeader().setReorderingAllowed(false);
    scroll = new JScrollPane(changingMarkStatisticTable);
    scroll.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(scroll);

    changingPMarkStatisticTable = new JTable(new StringTableModel(new Object[0][0], new Object[0]));
    changingPMarkStatisticTable.getTableHeader().setReorderingAllowed(false);
    scroll = new JScrollPane(changingPMarkStatisticTable);
    scroll.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(scroll);

    summaryTable = new JTable(new StringTableModel(new Object[0][0], new Object[0]));
    summaryTable.getTableHeader().setReorderingAllowed(false);
    scroll = new JScrollPane(summaryTable);
    scroll.setAlignmentX(Component.CENTER_ALIGNMENT);
    add(scroll);
}

From source file:edu.ku.brc.af.ui.forms.CarryForwardConfigDlg.java

@Override
public void createUI() {
    super.createUI();

    buildTableModel(mvParent);//w  w  w .j a va  2s  .co  m

    model = new CFTableModel();
    table = new JTable(model) {
        //  Returning the Class of each column will allow different
        //  renderers to be used based on Class
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            if (!c.getBackground().equals(getSelectionBackground())) {
                CFWItem item = items.get(row);
                c.setBackground(item.getColor());
            }
            return c;
        }
    };

    UIHelper.makeTableHeadersCentered(table, false);

    //((DefaultTableCellRenderer)table.getColumnModel().getColumn(1).getCellRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

    JScrollPane sp = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    contentPanel = sp;//new JPanel(new BorderLayout()));
    mainPanel.add(contentPanel, BorderLayout.CENTER);
}

From source file:TableFilterDemo.java

public TableFilterDemo() {
    super();/*www.  j a  v  a  2  s  .  com*/
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // Create a table with a sorter.
    MyTableModel model = new MyTableModel();
    sorter = new TableRowSorter<MyTableModel>(model);
    table = new JTable(model);
    table.setRowSorter(sorter);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);

    // For the purposes of this example, better to have a single
    // selection.
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // When selection changes, provide user with row numbers for
    // both view and model.
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent event) {
            int viewRow = table.getSelectedRow();
            if (viewRow < 0) {
                // Selection got filtered away.
                statusText.setText("");
            } else {
                int modelRow = table.convertRowIndexToModel(viewRow);
                statusText.setText(String.format("Selected Row in view: %d. " + "Selected Row in model: %d.",
                        viewRow, modelRow));
            }
        }
    });

    // Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    // Add the scroll pane to this panel.
    add(scrollPane);

    // Create a separate form for filterText and statusText
    JPanel form = new JPanel(new SpringLayout());
    JLabel l1 = new JLabel("Filter Text:", SwingConstants.TRAILING);
    form.add(l1);
    filterText = new JTextField();
    // Whenever filterText changes, invoke newFilter.
    filterText.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            newFilter();
        }

        public void insertUpdate(DocumentEvent e) {
            newFilter();
        }

        public void removeUpdate(DocumentEvent e) {
            newFilter();
        }
    });
    l1.setLabelFor(filterText);
    form.add(filterText);
    JLabel l2 = new JLabel("Status:", SwingConstants.TRAILING);
    form.add(l2);
    statusText = new JTextField();
    l2.setLabelFor(statusText);
    form.add(statusText);
    SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
    add(form);
}

From source file:net.sf.jabref.importer.ImportCustomizationDialog.java

/**
 *
 * @param frame/*  w w  w  .jav  a  2 s.co  m*/
 */
public ImportCustomizationDialog(final JabRefFrame frame) {
    super(frame, Localization.lang("Manage custom imports"), false);

    ImportTableModel tableModel = new ImportTableModel();
    customImporterTable = new JTable(tableModel);
    TableColumnModel cm = customImporterTable.getColumnModel();
    cm.getColumn(0).setPreferredWidth(COL_0_WIDTH);
    cm.getColumn(1).setPreferredWidth(COL_1_WIDTH);
    cm.getColumn(2).setPreferredWidth(COL_2_WIDTH);
    cm.getColumn(3).setPreferredWidth(COL_3_WIDTH);
    JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    customImporterTable.setPreferredScrollableViewportSize(getSize());
    if (customImporterTable.getRowCount() > 0) {
        customImporterTable.setRowSelectionInterval(0, 0);
    }

    JButton addFromFolderButton = new JButton(Localization.lang("Add from folder"));
    addFromFolderButton.addActionListener(e -> {
        CustomImporter importer = new CustomImporter();
        importer.setBasePath(FileDialogs.getNewDir(frame,
                new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Collections.emptyList(),
                Localization.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false));
        String chosenFileStr = null;
        if (importer.getBasePath() != null) {
            chosenFileStr = FileDialogs.getNewFile(frame, importer.getFileFromBasePath(),
                    Collections.singletonList(".class"), Localization.lang("Select new ImportFormat subclass"),
                    JFileChooser.CUSTOM_DIALOG, false);
        }
        if (chosenFileStr != null) {
            try {
                importer.setClassName(pathToClass(importer.getFileFromBasePath(), new File(chosenFileStr)));
                importer.setName(importer.getInstance().getFormatName());
                importer.setCliId(importer.getInstance().getId());
                addOrReplaceImporter(importer);
                customImporterTable.revalidate();
                customImporterTable.repaint();
            } catch (Exception exc) {
                JOptionPane.showMessageDialog(frame,
                        Localization.lang("Could not instantiate %0", chosenFileStr));
            } catch (NoClassDefFoundError exc) {
                JOptionPane.showMessageDialog(frame, Localization.lang(
                        "Could not instantiate %0. Have you chosen the correct package path?", chosenFileStr));
            }

        }
    });
    addFromFolderButton
            .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a class path.")
                    + "\n" + Localization.lang("The path need not be on the classpath of JabRef."));

    JButton addFromJarButton = new JButton(Localization.lang("Add from jar"));
    addFromJarButton.addActionListener(e -> {
        String basePath = FileDialogs.getNewFile(frame,
                new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Arrays.asList(".zip", ".jar"),
                Localization.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false);

        if (basePath != null) {
            try (ZipFile zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ)) {
                ZipFileChooser zipFileChooser = new ZipFileChooser(this, zipFile);
                zipFileChooser.setVisible(true);
                customImporterTable.revalidate();
                customImporterTable.repaint(10);
            } catch (IOException exc) {
                LOGGER.info("Could not open Zip-archive.", exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not open %0", basePath) + "\n"
                        + Localization.lang("Have you chosen the correct package path?"));
            } catch (NoClassDefFoundError exc) {
                LOGGER.info("Could not instantiate Zip-archive reader.", exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0", basePath)
                        + "\n" + Localization.lang("Have you chosen the correct package path?"));
            }
        }
    });
    addFromJarButton
            .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.")
                    + "\n" + Localization.lang("The Zip-archive need not be on the classpath of JabRef."));

    JButton showDescButton = new JButton(Localization.lang("Show description"));
    showDescButton.addActionListener(e -> {
        int row = customImporterTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
        } else {
            CustomImporter importer = ((ImportTableModel) customImporterTable.getModel()).getImporter(row);
            try {
                ImportFormat importFormat = importer.getInstance();
                JOptionPane.showMessageDialog(frame, importFormat.getDescription());
            } catch (IOException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException exc) {
                LOGGER.warn("Could not instantiate importer " + importer.getName(), exc);
                JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0 %1",
                        importer.getName() + ":\n", exc.getMessage()));
            }
        }
    });

    JButton removeButton = new JButton(Localization.lang("Remove"));
    removeButton.addActionListener(e -> {
        int row = customImporterTable.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
        } else {
            customImporterTable.removeRowSelectionInterval(row, row);
            Globals.prefs.customImports
                    .remove(((ImportTableModel) customImporterTable.getModel()).getImporter(row));
            Globals.IMPORT_FORMAT_READER.resetImportFormats();
            customImporterTable.revalidate();
            customImporterTable.repaint();
        }
    });

    Action closeAction = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    };

    JButton closeButton = new JButton(Localization.lang("Close"));
    closeButton.addActionListener(closeAction);

    JButton helpButton = new HelpAction(HelpFile.CUSTOM_IMPORTS).getHelpButton();

    // Key bindings:
    JPanel mainPanel = new JPanel();
    ActionMap am = mainPanel.getActionMap();
    InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", closeAction);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(sp, BorderLayout.CENTER);
    JPanel buttons = new JPanel();
    ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
    buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    bb.addGlue();
    bb.addButton(addFromFolderButton);
    bb.addButton(addFromJarButton);
    bb.addButton(showDescButton);
    bb.addButton(removeButton);
    bb.addButton(closeButton);
    bb.addUnrelatedGap();
    bb.addButton(helpButton);
    bb.addGlue();

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(buttons, BorderLayout.SOUTH);
    this.setSize(getSize());
    pack();
    this.setLocationRelativeTo(frame);
    new FocusRequester(customImporterTable);
}

From source file:dnd.BasicDnD.java

public BasicDnD() {
    super(new BorderLayout());
    JPanel leftPanel = createVerticalBoxPanel();
    JPanel rightPanel = createVerticalBoxPanel();

    //Create a table model.
    DefaultTableModel tm = new DefaultTableModel();
    tm.addColumn("Column 0");
    tm.addColumn("Column 1");
    tm.addColumn("Column 2");
    tm.addColumn("Column 3");
    tm.addRow(new String[] { "Table 00", "Table 01", "Table 02", "Table 03" });
    tm.addRow(new String[] { "Table 10", "Table 11", "Table 12", "Table 13" });
    tm.addRow(new String[] { "Table 20", "Table 21", "Table 22", "Table 23" });
    tm.addRow(new String[] { "Table 30", "Table 31", "Table 32", "Table 33" });

    //LEFT COLUMN
    //Use the table model to create a table.
    table = new JTable(tm);
    leftPanel.add(createPanelForComponent(table, "JTable"));

    //Create a color chooser.
    colorChooser = new JColorChooser();
    leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser"));

    //RIGHT COLUMN
    //Create a textfield.
    textField = new JTextField(30);
    textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast");
    rightPanel.add(createPanelForComponent(textField, "JTextField"));

    //Create a scrolled text area.
    textArea = new JTextArea(5, 30);
    textArea.setText("Favorite shows:\nBuffy, Alias, Angel");
    JScrollPane scrollPane = new JScrollPane(textArea);
    rightPanel.add(createPanelForComponent(scrollPane, "JTextArea"));

    //Create a list model and a list.
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("Martha Washington");
    listModel.addElement("Abigail Adams");
    listModel.addElement("Martha Randolph");
    listModel.addElement("Dolley Madison");
    listModel.addElement("Elizabeth Monroe");
    listModel.addElement("Louisa Adams");
    listModel.addElement("Emily Donelson");
    list = new JList(listModel);
    list.setVisibleRowCount(-1);//w w  w  .j av  a2  s .  co m
    list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    list.setTransferHandler(new TransferHandler() {

        public boolean canImport(TransferHandler.TransferSupport info) {
            // we only import Strings
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            if (dl.getIndex() == -1) {
                return false;
            }
            return true;
        }

        public boolean importData(TransferHandler.TransferSupport info) {
            if (!info.isDrop()) {
                return false;
            }

            // Check for String flavor
            if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                displayDropLocation("List doesn't accept a drop of this type.");
                return false;
            }

            JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            int index = dl.getIndex();
            boolean insert = dl.isInsert();
            // Get the current string under the drop.
            String value = (String) listModel.getElementAt(index);

            // Get the string that is being dropped.
            Transferable t = info.getTransferable();
            String data;
            try {
                data = (String) t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                return false;
            }

            // Display a dialog with the drop information.
            String dropValue = "\"" + data + "\" dropped ";
            if (dl.isInsert()) {
                if (dl.getIndex() == 0) {
                    displayDropLocation(dropValue + "at beginning of list");
                } else if (dl.getIndex() >= list.getModel().getSize()) {
                    displayDropLocation(dropValue + "at end of list");
                } else {
                    String value1 = (String) list.getModel().getElementAt(dl.getIndex() - 1);
                    String value2 = (String) list.getModel().getElementAt(dl.getIndex());
                    displayDropLocation(dropValue + "between \"" + value1 + "\" and \"" + value2 + "\"");
                }
            } else {
                displayDropLocation(dropValue + "on top of " + "\"" + value + "\"");
            }

            /**  This is commented out for the basicdemo.html tutorial page.
                       **  If you add this code snippet back and delete the
                       **  "return false;" line, the list will accept drops
                       **  of type string.
                      // Perform the actual import.  
                      if (insert) {
            listModel.add(index, data);
                      } else {
            listModel.set(index, data);
                      }
                      return true;
            */
            return false;
        }

        public int getSourceActions(JComponent c) {
            return COPY;
        }

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            Object[] values = list.getSelectedValues();

            StringBuffer buff = new StringBuffer();

            for (int i = 0; i < values.length; i++) {
                Object val = values[i];
                buff.append(val == null ? "" : val.toString());
                if (i != values.length - 1) {
                    buff.append("\n");
                }
            }
            return new StringSelection(buff.toString());
        }
    });
    list.setDropMode(DropMode.ON_OR_INSERT);

    JScrollPane listView = new JScrollPane(list);
    listView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(listView, "JList"));

    //Create a tree.
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Mia Familia");
    DefaultMutableTreeNode sharon = new DefaultMutableTreeNode("Sharon");
    rootNode.add(sharon);
    DefaultMutableTreeNode maya = new DefaultMutableTreeNode("Maya");
    sharon.add(maya);
    DefaultMutableTreeNode anya = new DefaultMutableTreeNode("Anya");
    sharon.add(anya);
    sharon.add(new DefaultMutableTreeNode("Bongo"));
    maya.add(new DefaultMutableTreeNode("Muffin"));
    anya.add(new DefaultMutableTreeNode("Winky"));
    DefaultTreeModel model = new DefaultTreeModel(rootNode);
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setPreferredSize(new Dimension(300, 100));
    rightPanel.add(createPanelForComponent(treeView, "JTree"));

    //Create the toggle button.
    toggleDnD = new JCheckBox("Turn on Drag and Drop");
    toggleDnD.setActionCommand("toggleDnD");
    toggleDnD.addActionListener(this);

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
    splitPane.setOneTouchExpandable(true);

    add(splitPane, BorderLayout.CENTER);
    add(toggleDnD, BorderLayout.PAGE_END);
    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}