Example usage for javax.swing JTable getColumnModel

List of usage examples for javax.swing JTable getColumnModel

Introduction

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

Prototype

public TableColumnModel getColumnModel() 

Source Link

Document

Returns the TableColumnModel that contains all column information of this table.

Usage

From source file:TableDemoApplet.java

private static void createGUI(Container contentPane) {
    Object[][] rowData = new String[][] { { "98-43", "AraAra! SL" }, { "81-31", "Aragones Transports SA" },
            { "12-72", "Rocca SL" }, { "99-10", "Rodriguez e Hijos SA" }, { "00-65", "Rimbau Motors SL" } };
    JTable table = new JTable(rowData, new String[] { "Part No", "Provider" });

    JComboBox companyComboBox = new JComboBox(new Object[] { "AraAra! SL", "Aragones Transports SA", "Rocca SL",
            "Rodriguez e Hijos SA", "Rimbau Motors SL" });
    companyComboBox.setEditable(true);// w w  w.  jav a2  s .com
    new S15WorkingBackspace(companyComboBox);

    // setup the ComboBoxCellEditor, DefaultCellEditor won't work!
    table.getColumnModel().getColumn(1).setCellEditor(new ComboBoxCellEditor(companyComboBox));

    table.setPreferredScrollableViewportSize(new Dimension(400, 100));
    JScrollPane scrollPane = new JScrollPane(table);

    contentPane.setLayout(new java.awt.FlowLayout());
    contentPane.add(scrollPane);
    contentPane.add(new JTextField("HALLO!"));
}

From source file:net.sf.webphotos.util.Util.java

/**
 * PackColumn sets the preferred width of the visible column specified by
 * vColIndex. The column will be just wide enough to show the column head
 * and the widest cell in the column. margin pixels are added to the left
 * and right (resulting in an additional width of 2*margin pixels).
 *
 * @param table The table you want to resize a column.
 * @param vColIndex The column number./*www. j a va2  s  . c  o m*/
 * @param margin Extra spaces for each side of column.
 */
public static void packColumn(JTable table, int vColIndex, int margin) {
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width;

    // Get width of column header
    javax.swing.table.TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }
    java.awt.Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false,
            0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r = 0; r < table.getRowCount(); r++) {
        renderer = table.getCellRenderer(r, vColIndex);
        comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r,
                vColIndex);
        width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2 * margin;

    // Set the width
    col.setPreferredWidth(width);
}

From source file:net.sf.webphotos.util.Util.java

/**
 * Ajusta a largura das colunas do modelo.
 *
 * @param tabela Tabela que deseja ajustar as colunas.
 * @param parametros Tamanhos das colunas separadas por vrgula.
 *//*w  w  w  . j a  v  a 2 s .  c  o  m*/
public static void ajustaLargura(JTable tabela, String parametros) {
    int temR = -1;
    TableColumnModel modeloColunas = tabela.getColumnModel();
    if (parametros == null) {
        return;
    }
    if (parametros.length() > 0) {
        StringTokenizer tok = new StringTokenizer(parametros, ",");
        int ct = 0;
        String l;
        while (tok.hasMoreTokens()) {
            l = tok.nextToken();
            try {
                modeloColunas.getColumn(ct).setPreferredWidth(Integer.parseInt(l));
            } catch (NumberFormatException nE) {
                switch (l) {
                case "*":
                    log.info("Packing column " + ct);
                    packColumn(tabela, ct, 1);
                    break;
                case "R":
                    temR = ct;
                    break;
                }
            } catch (Exception e) {
            }
            ct++;
        }

        if (temR > 0) {
            modeloColunas.getColumn(temR).setPreferredWidth(modeloColunas.getColumn(temR).getPreferredWidth()
                    + tabela.getWidth() - modeloColunas.getTotalColumnWidth());
            log.debug("Tamanho da tabela: " + (modeloColunas.getColumn(temR).getPreferredWidth()
                    + tabela.getWidth() - modeloColunas.getTotalColumnWidth()));
        }

        //Testes
        log.debug("Tamanho Total: " + modeloColunas.getTotalColumnWidth());
        log.debug("Tamanho da tabela: " + tabela.getWidth());
    }
}

From source file:com.sshtools.common.ui.PreferencesStore.java

/**
 *
 *
 * @param table/*from   www  .j a  va 2  s  .c o m*/
 * @param pref
 */
public static void saveTableMetrics(JTable table, String pref) {
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        int w = table.getColumnModel().getColumn(i).getWidth();
        put(pref + ".column." + i + ".width", String.valueOf(w));
        put(pref + ".column." + i + ".position", String.valueOf(table.convertColumnIndexToModel(i)));
    }
}

From source file:OAT.ui.util.UiUtil.java

public static void setupColumns(JTable table) {
    for (int i = 0; i < table.getColumnCount(); i++) {
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        TableColumn column = table.getColumnModel().getColumn(i);
        Class columnClass = table.getColumnClass(i);
        String columnName = table.getColumnName(i);
        renderer.setToolTipText(columnName);

        if (columnClass.getSuperclass().equals(Number.class)) {
            renderer.setHorizontalAlignment(DefaultTableCellRenderer.RIGHT);
        }/* w  w  w.j  a v a  2s.  c om*/

        if (table.isEnabled()) {
            if (columnName.equals("Currency")) {
                //addComboCell(column, Product.CURRENCIES);
            } else if (columnName.equals("Holidays")) {
                //column.setCellEditor(new FileChooserCellEditor());
            }
        }

        column.setCellRenderer(renderer);
    }
}

From source file:Main.java

/**
 *  Calculates the optimal width for the header of the given table. The
 *  calculation is based on the preferred width of the header renderer.
 *
 *  @param table    the table to calculate the column width
 *  @param col      the column to calculate the widths
 *  @return         the width, -1 if error
 *//* w  ww  . j a v  a  2 s  . c  o m*/
public static int calcHeaderWidth(JTable table, int col) {
    if (table == null)
        return -1;

    if (col < 0 || col > table.getColumnCount()) {
        System.out.println("invalid col " + col);
        return -1;
    }

    JTableHeader header = table.getTableHeader();
    TableCellRenderer defaultHeaderRenderer = null;
    if (header != null)
        defaultHeaderRenderer = header.getDefaultRenderer();
    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();
    TableColumn column = columns.getColumn(col);
    int width = -1;
    TableCellRenderer h = column.getHeaderRenderer();
    if (h == null)
        h = defaultHeaderRenderer;
    if (h != null) {
        // Not explicitly impossible
        Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, col);
        width = c.getPreferredSize().width + 5;
    }

    return width;
}

From source file:com.stam.batchmove.BatchMoveUtils.java

public static void showFilesFrame(Object[][] data, String[] columnNames, final JFrame callerFrame) {
    final FilesFrame filesFrame = new FilesFrame();

    DefaultTableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override/*from   w  w  w. j  a va  2 s. c o m*/
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 0;
        }
    };
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(JLabel.CENTER);
    final JTable table = new JTable(model);
    for (int i = 1; i < table.getColumnCount(); i++) {
        table.setDefaultRenderer(table.getColumnClass(i), renderer);
    }
    //            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setRowHeight(30);
    table.getTableHeader().setFont(new Font("Serif", Font.BOLD, 14));
    table.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    table.setRowSelectionAllowed(false);
    table.getColumnModel().getColumn(0).setMaxWidth(35);
    table.getColumnModel().getColumn(1).setPreferredWidth(350);
    table.getColumnModel().getColumn(2).setPreferredWidth(90);
    table.getColumnModel().getColumn(2).setMaxWidth(140);
    table.getColumnModel().getColumn(3).setMaxWidth(90);

    JPanel tblPanel = new JPanel();
    JPanel btnPanel = new JPanel();

    tblPanel.setLayout(new BorderLayout());
    if (table.getRowCount() > 15) {
        JScrollPane scrollPane = new JScrollPane(table);
        tblPanel.add(scrollPane, BorderLayout.CENTER);
    } else {
        tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tblPanel.add(table, BorderLayout.CENTER);
    }

    btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    filesFrame.setMinimumSize(new Dimension(800, 600));
    filesFrame.setLayout(new BorderLayout());
    filesFrame.add(tblPanel, BorderLayout.NORTH);
    filesFrame.add(btnPanel, BorderLayout.SOUTH);

    final JLabel resultsLabel = new JLabel();

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filesFrame.setVisible(false);
            callerFrame.setVisible(true);
        }
    });

    JButton moveBtn = new JButton("Copy");
    moveBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setDialogTitle("Choose target directory");
            int selVal = fileChooser.showOpenDialog(null);
            if (selVal == JFileChooser.APPROVE_OPTION) {
                File selection = fileChooser.getSelectedFile();
                String targetPath = selection.getAbsolutePath();

                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                int nRow = dtm.getRowCount();
                int copied = 0;
                for (int i = 0; i < nRow; i++) {
                    Boolean selected = (Boolean) dtm.getValueAt(i, 0);
                    String filePath = dtm.getValueAt(i, 1).toString();

                    if (selected) {
                        try {
                            FileUtils.copyFileToDirectory(new File(filePath), new File(targetPath));
                            dtm.setValueAt("Copied", i, 3);
                            copied++;
                        } catch (Exception ex) {
                            Logger.getLogger(SelectionFrame.class.getName()).log(Level.SEVERE, null, ex);
                            dtm.setValueAt("Failed", i, 3);
                        }
                    }
                }
                resultsLabel.setText(copied + " files copied. Finished!");
            }
        }
    });
    btnPanel.add(cancelBtn);
    btnPanel.add(moveBtn);
    btnPanel.add(resultsLabel);

    filesFrame.revalidate();
    filesFrame.setVisible(true);

    callerFrame.setVisible(false);
}

From source file:com.sshtools.common.ui.PreferencesStore.java

/**
 *
 *
 * @param table//from w  w w .j  a va 2  s .  c o  m
 * @param pref
 * @param defaultWidths
 *
 * @throws IllegalArgumentException
 */
public static void restoreTableMetrics(JTable table, String pref, int[] defaultWidths) {
    //  Check the table columns may be resized correctly
    if (table.getAutoResizeMode() != JTable.AUTO_RESIZE_OFF) {
        throw new IllegalArgumentException("Table AutoResizeMode must be JTable.AUTO_RESIZE_OFF");
    }

    //  Restore the table column widths and positions
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        try {
            table.moveColumn(table.convertColumnIndexToView(getInt(pref + ".column." + i + ".position", i)), i);
            table.getColumnModel().getColumn(i)
                    .setPreferredWidth(getInt(pref + ".column." + i + ".width",
                            (defaultWidths == null) ? table.getColumnModel().getColumn(i).getPreferredWidth()
                                    : defaultWidths[i]));
        } catch (NumberFormatException nfe) {
        }
    }
}

From source file:Main.java

public static void SetJTableAlignment(javax.swing.JTable jTable, ComponentOrientation componentOrientation) {
    Font tahoma = new Font("Tahoma", Font.PLAIN, 11);
    int labelAlighnment = JLabel.RIGHT;
    int headerAlighnment = JLabel.RIGHT;
    if (componentOrientation == ComponentOrientation.LEFT_TO_RIGHT) {
        labelAlighnment = JLabel.LEFT;
        headerAlighnment = JLabel.LEFT;
    }/*from   w  w  w.  j a v a  2s .c o  m*/

    DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
    defaultTableCellRenderer.setHorizontalAlignment(labelAlighnment);
    // defaultTableCellRenderer.setFont(tahoma);

    for (int columnIndex = 0; columnIndex < jTable.getColumnCount(); columnIndex++) {
        if (jTable.getModel().getColumnClass(columnIndex).equals(Boolean.class)) {
            jTable.getColumnModel().getColumn(columnIndex).setWidth(60);
            jTable.getColumnModel().getColumn(columnIndex).setMaxWidth(90);
            jTable.getColumnModel().getColumn(columnIndex).setMinWidth(10);
            jTable.getColumnModel().getColumn(columnIndex).setPreferredWidth(60);
            continue;
        }
        if (jTable.getModel().getColumnClass(columnIndex).equals(ImageIcon.class)) {
            continue;
        }
        jTable.getColumnModel().getColumn(columnIndex).setCellRenderer(defaultTableCellRenderer);

    }
    DefaultTableCellRenderer renderer;
    renderer = (DefaultTableCellRenderer) jTable.getTableHeader().getDefaultRenderer();
    renderer.setHorizontalAlignment(headerAlighnment);

    jTable.getTableHeader().setDefaultRenderer(renderer);

}

From source file:edu.ku.brc.stats.StatGroupTable.java

/**
 * Calculates and sets the each column to it preferred size
 * @param table the table to fix ups/*from   www  .j av a 2s .  co m*/
 */
public static void calcColumnWidths(JTable table) {
    JTableHeader header = table.getTableHeader();

    TableCellRenderer defaultHeaderRenderer = null;

    if (header != null) {
        defaultHeaderRenderer = header.getDefaultRenderer();
    }

    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();

    int margin = columns.getColumnMargin(); // only JDK1.3

    int rowCount = data.getRowCount();

    int totalWidth = 0;

    for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
        TableColumn column = columns.getColumn(i);

        int columnIndex = column.getModelIndex();

        int width = -1;

        TableCellRenderer h = column.getHeaderRenderer();

        if (h == null)
            h = defaultHeaderRenderer;

        if (h != null) // Not explicitly impossible
        {
            Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, i);

            width = c.getPreferredSize().width;
        }

        for (int row = rowCount - 1; row >= 0; --row) {
            TableCellRenderer r = table.getCellRenderer(row, i);

            Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                    false, row, i);

            width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer
        }

        if (width >= 0) {
            column.setPreferredWidth(width + margin); // <1.3: without margin
        }

        totalWidth += column.getPreferredWidth();
    }

    // If you like; This does not make sense for two many columns!
    Dimension size = table.getPreferredScrollableViewportSize();
    //if (totalWidth > size.width)
    {
        size.height = Math.min(size.height, table.getRowHeight() * visibleRows);
        size.width = totalWidth;
        table.setPreferredScrollableViewportSize(size);
    }

}