Example usage for javax.swing.table DefaultTableModel addColumn

List of usage examples for javax.swing.table DefaultTableModel addColumn

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableModel addColumn.

Prototype

public void addColumn(Object columnName) 

Source Link

Document

Adds a column to the model.

Usage

From source file: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.  ja  v  a  2 s  . c o  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));
}

From source file:latexstudio.editor.DropboxRevisionsTopComponent.java

public void updateRevisionsList(String path) {
    DbxClient client = DbxUtil.getDbxClient();
    List<DbxEntry.File> entries = null;

    if (path != null) {
        try {//from w  ww .j av a  2s. c  o  m
            entries = client.getRevisions(path);
        } catch (DbxException ex) {
            DbxUtil.showDbxAccessDeniedPrompt();
        }
    }

    dlm.clear();
    DefaultTableModel model = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return column == REVIEW_COLUMN;
        }
    };
    model.addColumn(REVISION_COLUMN_NAME);
    model.addColumn(MODIFIED_COLUMN_NAME);
    model.addColumn(FILE_SIZE_COLUMN_NAME);
    model.addColumn(REVIEW_COLUMN_NAME);

    if (entries != null && entries.size() > 0) {
        for (DbxEntry.File dbxEntry : entries) {
            dlm.addElement(new DbxEntryRevision(dbxEntry));
            model.addRow(new Object[] { dbxEntry.rev, dbxEntry.lastModified, dbxEntry.humanSize,
                    REVIEW_BUTTON_LABEL });
        }
    }

    Action showVersion = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Resolving which row has been double-clicked
            JTable table = (JTable) e.getSource();
            int row = Integer.valueOf(e.getActionCommand());
            // Finding revision using information from the clicked row
            String revisionNumber = table.getValueAt(row, REVISION_COLUMN).toString();
            loadRevision(revisionNumber);
        }
    };

    jTable1.setModel(model);
    ButtonColumn buttonColumn = new ButtonColumn(jTable1, showVersion, REVIEW_COLUMN);
    buttonColumn.setMnemonic(KeyEvent.VK_D);
}

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

/**
 * @return//www  .j  ava 2s.c  o  m
 */
private DefaultTableModel getCleanTableModel() {
    DefaultTableModel model = new DefaultTableModel() {
        public boolean isCellEditable(int row, int column) {
            return (column != 1);
        }
    };
    model.addColumn(FIELD_VALUE_COL);
    model.addColumn(DISPLAY_FORMAT_COL);
    model.addColumn(ELLIPSIS_BUTTON_COL);

    addTableModelListener(model);
    return model;
}

From source file:Import.pnl_import_vcf.java

public void setMapTable(JTable table, DefaultTableModel model, String[] selectedFamilies,
        String[] selectedTableFamilies) {
    model.setRowCount(0);//from   w  w  w . j a va  2 s  .c  o m
    model.addColumn("Import Column");
    model.addColumn("Map to");
    TableColumn sportColumn = table.getColumnModel().getColumn(1);
    JComboBox comboBox = new JComboBox();
    for (String a : selectedFamilies) {
        comboBox.addItem(a);
    }
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    for (String b : selectedTableFamilies) {
        String[] tmp = new String[1];
        tmp[0] = b;
        model.addRow(tmp);
    }
}

From source file:edu.ucla.stat.SOCR.motionchart.MotionMouseListener.java

protected JPanel getSeriesPanel(final JDialog dialog, ChartMouseEvent event) {
    MotionDataSet dataset = (MotionDataSet) event.getChart().getXYPlot().getDataset();
    MotionBubbleRenderer renderer = (MotionBubbleRenderer) event.getChart().getXYPlot().getRenderer();
    MotionTableModel model = dataset.getTableModel();
    DefaultTableModel tModel = new DefaultTableModel();
    ArrayList<Integer> visibleSeries = renderer.getVisibleSeries();
    ArrayList<String> rowIds = new ArrayList<String>();

    int columnCount = model.getColumnCount();
    int r = 0;/*from  www .  j a  v  a  2s  .  c om*/

    for (int c = 0; c < columnCount; c++) {
        tModel.addColumn(model.getColumnName(c));
    }

    Iterator<Integer> itr = visibleSeries.iterator();

    while (itr.hasNext()) {
        ArrayList<Integer> rows = model.getKeyMap().get(dataset.getSeriesKey(itr.next()));

        Iterator<Integer> rItr = rows.iterator();

        while (rItr.hasNext()) {
            int row = rItr.next();

            tModel.addRow(new Object[0]);
            rowIds.add(new String(row + ":"));

            for (int c = 0; c < columnCount; c++) {
                tModel.setValueAt(model.getValueAt(row, c), r, c);
            }

            r++;
        }
    }

    return getPanel(dialog, tModel, rowIds);
}

From source file:view.ResultsPanel.java

public ResultsPanel(final MainControler controler, String[] command, String resultsName) {

    this.resultsName = resultsName;

    this.controler = controler;
    this.command = command;
    modeTable = new JTable(0, 2);

    DefaultTableModel model = new MyTableModel();

    model.addColumn("Stoichiometry");
    model.addColumn("Enzyme name");
    model.addColumn("Equation");
    modeTable.setModel(model);/*from   w  w w .j  a v  a2 s. com*/

    JPanel logPanel = new JPanel(new BorderLayout());
    log = new JTextArea();
    log.setEditable(false);
    log.setBackground(new Color(0, 0, 0));
    log.setForeground(new Color(255, 255, 255));

    logPanel.add(new JLabel("Genereted log", JLabel.CENTER), BorderLayout.PAGE_START);
    logPanel.add(new JScrollPane(log), BorderLayout.CENTER);

    addToProject.setName("add");
    addToProject.setToolTipText("Attach this result to the project");
    removeFromProject.setName("remove");
    removeFromProject.setToolTipText("Remove this result from the project");

    removeFromProject.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            removeFromProject();
            updateToolbar();
        }
    });

    addToProject.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            addToProject();
            updateToolbar();
        }
    });

    if (!resultsName.startsWith("saved/")) {
        isAttached = false;
    } else {
        isAttached = true;
    }

    filterButton.setToolTipText("Filter the results");

    filterButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            FilterFrame ff = new FilterFrame(GeneralFrame.getInstance(controler), allModes, filter, controler);
            if (ff.okPressed()) {

                displayFrame(ff.getNewModes(), ff.getIndices());
            }
        }
    });

    scriptButton.setToolTipText("Download the command as a script");
    scriptButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            String scriptString = makeScript();
            new Download(scriptString, "Download the command as a script", "");

        }
    });

    download = new JButton(new ImageIcon("src/icons/download.png"));
    download.setToolTipText("Download results");

    histoButton.setToolTipText("Statistics");

    searchField.setMaximumSize(new Dimension(20, 30));

    readLog();
    allModes = readResultsFile();

    List<Integer> indices = new ArrayList<Integer>();
    for (int i = 0; i < allModes.size(); i++) {
        indices.add((i + 1));
    }

    displayFrame(allModes, indices);

}

From source file:edu.ucla.stat.SOCR.motionchart.MotionMouseListener.java

protected JPanel getItemPanel(final JDialog dialog, XYItemEntity item, ChartMouseEvent event) {
    MotionDataSet dataset = (MotionDataSet) event.getChart().getXYPlot().getDataset();
    MotionTableModel model = dataset.getTableModel();
    DefaultTableModel tModel = new DefaultTableModel(2, 0);
    ArrayList<String> rowIds = new ArrayList<String>();

    Integer row = model.getKeyMap().get(dataset.getSeriesKey(item.getSeriesIndex())).get(item.getItem());
    rowIds.add(row + ":");

    int columnCount = model.getColumnCount();

    for (int c = 0; c < columnCount; c++) {
        tModel.addColumn(model.getColumnName(c));
        tModel.setValueAt(model.getValueAt(row, c), 0, c);
    }/*ww  w .  jav a 2 s  .co  m*/

    rowIds.add("Mappings:");

    Object category = dataset.getCategory(item.getSeriesIndex(), item.getItem());
    if (category != null) {
        tModel.setValueAt(category, 1, model.getCategoryMapping());
    }

    Object key = dataset.getSeriesKey(item.getSeriesIndex());
    if (key != null) {
        tModel.setValueAt(key, 1, model.getKeyMapping());
    }

    Object x = dataset.getX(item.getSeriesIndex(), item.getItem());
    if (x != null) {
        tModel.setValueAt(x, 1, model.getXAxisMapping());
    }

    Object y = dataset.getY(item.getSeriesIndex(), item.getItem());
    if (y != null) {
        tModel.setValueAt(y, 1, model.getYAxisMapping());
    }

    Object size = dataset.getSize(item.getSeriesIndex(), item.getItem());
    if (size != null) {
        tModel.setValueAt(size, 1, model.getSizeMapping());
    }

    Color color = dataset.getColor(item.getSeriesIndex(), item.getItem());
    if (color != null) {
        //String colorText = "RGB(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ")";
        tModel.setValueAt(color, 1, model.getColorMapping());
    }

    return getPanel(dialog, tModel, rowIds);
}

From source file:view.ResultsPanel.java

public void showHistogram(List<ElementaryMode> modes) {

    //for the JTable
    DefaultTableModel tableModel = new DefaultTableModel();
    JTable tableResult = new JTable();
    tableResult.setModel(tableModel);// ww w .j  av  a 2s.  c o m

    tableModel.addColumn("Reaction");
    tableModel.addColumn("Presence in the modes");

    tableResult.setAutoCreateRowSorter(true);

    Map<Reaction, Double> stats = new HashMap<Reaction, Double>();

    DecimalFormat df = new DecimalFormat("0.00");

    for (ElementaryMode em : modes) {
        for (Reaction r : em.getContent().keySet()) {
            if (em.getContent().containsKey(r)) {
                if (!stats.containsKey(r)) {
                    stats.put(r, 1.0);
                } else {
                    Reaction key = r;
                    Double value = stats.get(r) + 1;
                    stats.remove(key);
                    stats.put(key, value);
                }
            }
        }
    }

    for (Reaction r : stats.keySet()) {
        tableModel
                .addRow(new Object[] { r, String.valueOf(df.format(stats.get(r) * 100 / modes.size())) + "%" });
    }

    JFrame statisticFrame = new JFrame();
    statisticFrame.add(new JScrollPane(tableResult), BorderLayout.CENTER);
    statisticFrame.setVisible(true);
    statisticFrame.setSize(400, 350);
    statisticFrame.setTitle("Representativeness of each reaction");
    statisticFrame.setLocation(500, 600);

    //histogram
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Map<Integer, Integer> data = new TreeMap<Integer, Integer>();
    int maxSize = 0;
    for (ElementaryMode em : modes) {
        int modeLength = em.getContent().size();
        if (modeLength > maxSize) {
            maxSize = modeLength;
        }
        if (data.containsKey(modeLength)) {
            int value = data.get(modeLength) + 1;
            data.put(modeLength, value);
        } else {
            data.put(modeLength, 1);
        }
    }

    for (int i = 1; i < maxSize; i++) {
        if (!data.containsKey(i)) {
            data.put(i, 0);
        }
    }
    for (int key : data.keySet()) {
        dataset.addValue(Integer.valueOf((data.get(key))), "test", Integer.valueOf(key));
    }

    String plotTitle = "Number of reactions per elementary mode";
    String xaxis = "Reaction number";
    String yaxis = "Elementary mode number";
    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;
    JFreeChart chart = ChartFactory.createBarChart3D(plotTitle, xaxis, yaxis, dataset, orientation, show,
            toolTips, urls);

    CategoryPlot plot = chart.getCategoryPlot();
    CategoryAxis axis = plot.getDomainAxis();

    plot.getDomainAxis(0).setLabelFont(plot.getDomainAxis().getLabelFont().deriveFont(new Float(11)));

    ChartFrame frame = new ChartFrame("Elementary modes", chart);
    frame.setVisible(true);
    frame.setSize(400, 350);
    frame.setLocation(500, 100);

}

From source file:Forms.FrmPrincipal.java

private void mostrarPesos(ArrayList<ArrayList<double[]>> w, int[] capas) {
    int max = 0;// w  w  w. java 2  s  .  c o  m
    for (int capa = 0; capa < capas.length; capa++) {
        if (capas[capa] >= max) {
            max = capas[capa];
        }
    }

    DefaultTableModel modelo = new DefaultTableModel();
    tblPesos.setModel(modelo);
    for (int capa = 0; capa < w.size(); capa++) {
        modelo.addColumn("Capa " + (capa + 1));
    }

    Object[] object = new Object[4];
    object[0] = "1";
    object[1] = "2";
    object[2] = "3";
    object[3] = "4";

    modelo.addRow(object);

}

From source file:frames.MainGUI.java

public void LoadRentToJtable(JTable t, File file) {
    try {/*from   w  w  w .  j a v  a2s . co  m*/
        CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        //t.setModel(tm);
        DefaultTableModel model = new DefaultTableModel();
        //model.setRowCount(0);
        for (CSVRecord c : parser) {
            if (c.getRecordNumber() == 1) {
                model.addColumn("??");
                model.addColumn("");
                model.addColumn("?");
                model.addColumn("?");
                model.addColumn("");
                model.addColumn("");
                t.setModel(model);
                model = (DefaultTableModel) t.getModel();
                continue;
            }
            model.addRow(new Object[] { c.get(0), c.get(1), c.get(2), c.get(3), c.get(4), c.get(5) });
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}