Example usage for javax.swing.table TableColumn getPreferredWidth

List of usage examples for javax.swing.table TableColumn getPreferredWidth

Introduction

In this page you can find the example usage for javax.swing.table TableColumn getPreferredWidth.

Prototype

public int getPreferredWidth() 

Source Link

Document

Returns the preferred width of the TableColumn.

Usage

From source file:Main.java

public static String headerString(TableColumn tc) {
    final StringBuilder result = new StringBuilder();
    result.append(tc.getHeaderValue());/*from  w  w  w.  j  av a 2 s  . co m*/
    result.append('[').append(tc.getPreferredWidth()).append(']');
    return result.toString();
}

From source file:com.github.fritaly.dualcommander.event.ColumnEventHelper.java

@Override
public void mouseReleased(MouseEvent e) {
    if (resizing) {
        if (e.getSource() instanceof JTableHeader) {
            final TableColumn column = ((JTableHeader) e.getSource()).getColumnModel()
                    .getColumn(resizingColumn);

            if (column != null) {
                int newWidth = column.getPreferredWidth();

                if (newWidth != oldWidth) {
                    listener.columnResized(new ColumnEvent(column));
                }//from  w  w  w  . j  ava  2 s .c o  m
            }
        }
    }

    resizing = false;
    resizingColumn = -1;
    oldWidth = -1;
}

From source file:com.github.fritaly.dualcommander.event.ColumnEventHelper.java

@Override
public void mousePressed(MouseEvent e) {
    // capture start of resize
    if (e.getSource() instanceof JTableHeader) {
        final TableColumn column = ((JTableHeader) e.getSource()).getResizingColumn();

        if (column != null) {
            resizing = true;/*  w  ww .  j a  v a 2s .c o m*/
            resizingColumn = column.getModelIndex();
            oldWidth = column.getPreferredWidth();
        } else {
            resizingColumn = -1;
            oldWidth = -1;
        }
    }
}

From source file:FrozenColumnHeader.java

public void addNotify() {
    TableColumn column;
    super.addNotify();
    TableColumnModel mainModel = mainTable.getColumnModel();
    TableColumnModel headerModel = new DefaultTableColumnModel();
    int frozenWidth = 0;
    for (int i = 0; i < columnCount; i++) {
        column = mainModel.getColumn(0);
        mainModel.removeColumn(column);/*from w  w  w.j a  v  a2  s .  co m*/
        headerModel.addColumn(column);
        frozenWidth += column.getPreferredWidth() + headerModel.getColumnMargin();
    }
    headerTable.setColumnModel(headerModel);
    Component columnHeader = getColumnHeader().getView();
    getColumnHeader().setView(null);
    JScrollPane mainScrollPane = (JScrollPane) SwingUtilities.getAncestorOfClass(JScrollPane.class, mainTable);
    mainScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, new JLabel("..."));

    headerTable.setPreferredScrollableViewportSize(new Dimension(frozenWidth, 0));
}

From source file:MainClass.java

public MainClass() {
    super("Row Header Test");
    setSize(300, 200);/*from   ww w.j  a  v a  2  s .  c  om*/
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    TableModel tm = new AbstractTableModel() {
        String data[] = { "", "a", "b", "c", "d", "e" };

        String headers[] = { "Row #", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" };

        public int getColumnCount() {
            return data.length;
        }

        public int getRowCount() {
            return 1000;
        }

        public String getColumnName(int col) {
            return headers[col];
        }

        public Object getValueAt(int row, int col) {
            return data[col] + row;
        }
    };

    TableColumnModel cm = new DefaultTableColumnModel() {
        boolean first = true;

        public void addColumn(TableColumn tc) {
            if (first) {
                first = false;
                return;
            }
            tc.setMinWidth(150);
            super.addColumn(tc);
        }
    };

    TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {
        boolean first = true;

        public void addColumn(TableColumn tc) {
            if (first) {
                tc.setMaxWidth(tc.getPreferredWidth());
                super.addColumn(tc);
                first = false;
            }
        }
    };

    JTable jt = new JTable(tm, cm);
    JTable headerColumn = new JTable(tm, rowHeaderModel);
    jt.createDefaultColumnsFromModel();
    headerColumn.createDefaultColumnsFromModel();

    jt.setSelectionModel(headerColumn.getSelectionModel());

    headerColumn.setBackground(Color.lightGray);
    headerColumn.setColumnSelectionAllowed(false);
    headerColumn.setCellSelectionEnabled(false);

    JViewport jv = new JViewport();
    jv.setView(headerColumn);
    jv.setPreferredSize(headerColumn.getMaximumSize());

    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    JScrollPane jsp = new JScrollPane(jt);
    jsp.setRowHeader(jv);
    jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
    getContentPane().add(jsp, BorderLayout.CENTER);
}

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 w w w . j ava  2  s  .  c om*/
 */
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);
    }

}

From source file:DefaultsDisplay.java

protected JTable createDefaultsTable() {
    JTable table = new JTable(new UIDefaultsTableModel());
    table.setRowHeight(rowHeight);/*from ww  w  .  j  a v a 2  s  .  c om*/
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.setIntercellSpacing(new Dimension(0, 0));
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    initFilters(table);

    DefaultTableColumnModel columnModel = new DefaultTableColumnModel();

    Color rowColors[] = new Color[2];
    rowColors[0] = UIManager.getColor("Table.background");
    rowColors[1] = new Color((int) (rowColors[0].getRed() * .90), (int) (rowColors[0].getGreen() * .95),
            (int) (rowColors[0].getBlue() * .95));

    int width = 0;

    TableColumn column = new TableColumn();
    column.setCellRenderer(new KeyRenderer(rowColors));
    column.setModelIndex(UIDefaultsTableModel.KEY_COLUMN);
    column.setHeaderValue("Key");
    column.setPreferredWidth(250);
    columnModel.addColumn(column);
    width += column.getPreferredWidth();

    column = new TableColumn();
    column.setCellRenderer(new RowRenderer(rowColors));
    column.setModelIndex(UIDefaultsTableModel.TYPE_COLUMN);
    column.setHeaderValue("Type");
    column.setPreferredWidth(250);
    columnModel.addColumn(column);
    width += column.getPreferredWidth();

    column = new TableColumn();
    column.setCellRenderer(new ValueRenderer(rowColors));
    column.setModelIndex(UIDefaultsTableModel.VALUE_COLUMN);
    column.setHeaderValue("Value");
    column.setPreferredWidth(300);
    columnModel.addColumn(column);
    width += column.getPreferredWidth();

    table.setColumnModel(columnModel);

    table.setPreferredScrollableViewportSize(new Dimension(width, 12 * rowHeight));

    return table;

}

From source file:RowHeaderTable.java

public RowHeaderTable() {
    super("Row Header Test");
    setSize(300, 200);//from w  ww .ja v a2  s.  com
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    TableModel tm = new AbstractTableModel() {
        String data[] = { "", "a", "b", "c", "d", "e" };

        String headers[] = { "Row #", "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" };

        public int getColumnCount() {
            return data.length;
        }

        public int getRowCount() {
            return 1000;
        }

        public String getColumnName(int col) {
            return headers[col];
        }

        // Synthesize some entries using the data values & the row #
        public Object getValueAt(int row, int col) {
            return data[col] + row;
        }
    };

    // Create a column model for the main table. This model ignores the
    // first
    // column added, and sets a minimum width of 150 pixels for all others.
    TableColumnModel cm = new DefaultTableColumnModel() {
        boolean first = true;

        public void addColumn(TableColumn tc) {
            // Drop the first column . . . that'll be the row header
            if (first) {
                first = false;
                return;
            }
            tc.setMinWidth(150); // just for looks, really...
            super.addColumn(tc);
        }
    };

    // Create a column model that will serve as our row header table. This
    // model picks a maximum width and only stores the first column.
    TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {
        boolean first = true;

        public void addColumn(TableColumn tc) {
            if (first) {
                tc.setMaxWidth(tc.getPreferredWidth());
                super.addColumn(tc);
                first = false;
            }
            // Drop the rest of the columns . . . this is the header column
            // only
        }
    };

    JTable jt = new JTable(tm, cm);

    // Set up the header column and get it hooked up to everything
    JTable headerColumn = new JTable(tm, rowHeaderModel);
    jt.createDefaultColumnsFromModel();
    headerColumn.createDefaultColumnsFromModel();

    // Make sure that selections between the main table and the header stay
    // in sync (by sharing the same model)
    jt.setSelectionModel(headerColumn.getSelectionModel());

    // Make the header column look pretty
    //headerColumn.setBorder(BorderFactory.createEtchedBorder());
    headerColumn.setBackground(Color.lightGray);
    headerColumn.setColumnSelectionAllowed(false);
    headerColumn.setCellSelectionEnabled(false);

    // Put it in a viewport that we can control a bit
    JViewport jv = new JViewport();
    jv.setView(headerColumn);
    jv.setPreferredSize(headerColumn.getMaximumSize());

    // With out shutting off autoResizeMode, our tables won't scroll
    // correctly (horizontally, anyway)
    jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    // We have to manually attach the row headers, but after that, the
    // scroll
    // pane keeps them in sync
    JScrollPane jsp = new JScrollPane(jt);
    jsp.setRowHeader(jv);
    jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
    getContentPane().add(jsp, BorderLayout.CENTER);
}

From source file:ru.develgame.jflickrorganizer.MainForm.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.//from   w  ww. j  a v a  2  s  . c om
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jLabelBackupFolder = new javax.swing.JLabel();
    jTextFieldBackupFolder = new javax.swing.JTextField();
    jButtonChooseBackupFolder = new javax.swing.JButton();
    jButtonBackup = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTreeAlbums = new javax.swing.JTree();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTablePhotos = new JTable() {
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component component = super.prepareRenderer(renderer, row, column);
            int rendererWidth = component.getPreferredSize().width + 5;
            TableColumn tableColumn = getColumnModel().getColumn(column);
            tableColumn.setPreferredWidth(
                    Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
            return component;
        }
    };
    jComboBoxVisibility = new javax.swing.JComboBox<>();
    jPanel1 = new javax.swing.JPanel();
    jLabelAll = new javax.swing.JLabel();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenuItemSetPassword = new javax.swing.JMenuItem();
    jMenuItemExit = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("MainForm"); // NOI18N
    setTitle(bundle.getString("MainForm.title")); // NOI18N
    setMinimumSize(new java.awt.Dimension(1024, 717));
    setName("Form"); // NOI18N

    jLabelBackupFolder.setText(bundle.getString("MainForm.jLabelBackupFolder.text")); // NOI18N
    jLabelBackupFolder.setName("jLabelBackupFolder"); // NOI18N

    jTextFieldBackupFolder.setName("jTextFieldBackupFolder"); // NOI18N

    jButtonChooseBackupFolder.setText(bundle.getString("MainForm.jButtonChooseBackupFolder.text")); // NOI18N
    jButtonChooseBackupFolder.setName("jButtonChooseBackupFolder"); // NOI18N
    jButtonChooseBackupFolder.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonChooseBackupFolderActionPerformed(evt);
        }
    });

    jButtonBackup.setText(bundle.getString("MainForm.jButtonBackup.text")); // NOI18N
    jButtonBackup.setName("jButtonBackup"); // NOI18N
    jButtonBackup.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonBackupActionPerformed(evt);
        }
    });

    jScrollPane1.setName("jScrollPane1"); // NOI18N

    jTreeAlbums.setName("jTreeAlbums"); // NOI18N
    jScrollPane1.setViewportView(jTreeAlbums);

    jScrollPane2.setName("jScrollPane2"); // NOI18N

    jTablePhotos.setAutoCreateRowSorter(true);
    jTablePhotos.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

    }, new String[] {

    }));
    jTablePhotos.setToolTipText(bundle.getString("MainForm.jTablePhotos.toolTipText")); // NOI18N
    jTablePhotos.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jTablePhotos.setName("jTablePhotos"); // NOI18N
    jTablePhotos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane2.setViewportView(jTablePhotos);

    jComboBoxVisibility.setName("jComboBoxVisibility"); // NOI18N

    jPanel1.setName("jPanel1"); // NOI18N

    jLabelAll.setText(bundle.getString("MainForm.jLabelAll.text")); // NOI18N
    jLabelAll.setName("jLabelAll"); // NOI18N

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout
            .setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                            jPanel1Layout.createSequentialGroup()
                                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabelAll).addContainerGap()));
    jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE).addComponent(jLabelAll)));

    jMenuBar1.setName("jMenuBar1"); // NOI18N

    jMenu1.setText(bundle.getString("MainForm.jMenu1.text")); // NOI18N
    jMenu1.setName("jMenu1"); // NOI18N

    jMenuItemSetPassword.setText(bundle.getString("MainForm.jMenuItemSetPassword.text")); // NOI18N
    jMenuItemSetPassword.setName("jMenuItemSetPassword"); // NOI18N
    jMenuItemSetPassword.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMenuItemSetPasswordActionPerformed(evt);
        }
    });
    jMenu1.add(jMenuItemSetPassword);

    jMenuItemExit.setText(bundle.getString("MainForm.jMenuItemExit.text")); // NOI18N
    jMenuItemExit.setName("jMenuItemExit"); // NOI18N
    jMenuItemExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMenuItemExitActionPerformed(evt);
        }
    });
    jMenu1.add(jMenuItemExit);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup().addComponent(jLabelBackupFolder)
                                    .addGap(68, 68, 68).addComponent(jTextFieldBackupFolder)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButtonChooseBackupFolder)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButtonBackup))
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout
                                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                    784, Short.MAX_VALUE)
                                            .addGroup(layout.createSequentialGroup()
                                                    .addComponent(jComboBoxVisibility,
                                                            javax.swing.GroupLayout.PREFERRED_SIZE, 271,
                                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addGap(0, 0, Short.MAX_VALUE)))))
                    .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                    Short.MAX_VALUE));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup().addContainerGap().addGroup(layout
                    .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldBackupFolder, javax.swing.GroupLayout.PREFERRED_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBackup).addComponent(jButtonChooseBackupFolder)
                    .addComponent(jLabelBackupFolder))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(jComboBoxVisibility, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 590,
                                            Short.MAX_VALUE))
                            .addComponent(jScrollPane1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel1,
                            javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                            javax.swing.GroupLayout.PREFERRED_SIZE)));

    pack();
}

From source file:edu.ku.brc.specify.utilapps.SetUpBuildDlg.java

/**
 * @param table//w  w  w. j a  v a  2s .c o 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
        } else {
            // ???
        }

        totalWidth += column.getPreferredWidth();
    }
}