Example usage for javax.swing JTable getColumnCount

List of usage examples for javax.swing JTable getColumnCount

Introduction

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

Prototype

@BeanProperty(bound = false)
public int getColumnCount() 

Source Link

Document

Returns the number of columns in the column model.

Usage

From source file:org.omegat.gui.align.AlignPanelController.java

private static void resizeRows(JTable table) {
    for (int row = 0; row < table.getRowCount(); row++) {
        int max = 0;
        for (int col = BeadTableModel.COL_SRC; col < table.getColumnCount(); col++) {
            int colWidth = table.getColumnModel().getColumn(col).getWidth();
            TableCellRenderer cellRenderer = table.getCellRenderer(row, col);
            Component c = table.prepareRenderer(cellRenderer, row, col);
            c.setBounds(0, 0, colWidth, Integer.MAX_VALUE);
            int height = c.getPreferredSize().height;
            max = Math.max(max, height);
        }//from   ww  w.  java  2 s  .  c om
        table.setRowHeight(row, max);
    }
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.GrandLivrePanel.java

/**
 * Cree un JTable contenant les ecritures du compte pass en argument
 * //from www . j a v  a 2s  .c o  m
 * @param compte
 * @return null si aucune ecriture
 */
private JTable createJTableCompte(Compte compte) {

    // on cree la JTable
    final JTable tableTmp = creerJTable(compte);

    if (tableTmp != null) {

        // On met en place le renderer
        EcritureGrandLivreRenderer ecritureRenderer = new EcritureGrandLivreRenderer(
                ((TableSorter) tableTmp.getModel()));

        for (int j = 0; j < tableTmp.getColumnCount(); j++) {
            tableTmp.getColumnModel().getColumn(j).setCellRenderer(ecritureRenderer);
        }

        // Gestion de la souris sur la JTable
        tableTmp.addMouseListener(new MouseAdapter() {

            public void mousePressed(final MouseEvent mE) {

                if (mE.getButton() == MouseEvent.BUTTON3) {
                    JPopupMenu menuDroit = new JPopupMenu();

                    menuDroit.add(new AbstractAction("Voir la source") {

                        public void actionPerformed(ActionEvent e) {
                            int row = tableTmp.rowAtPoint(mE.getPoint());

                            TableSorter s = (TableSorter) tableTmp.getModel();

                            int modelIndex = s.modelIndex(row);
                            ConsultCompteModel consultCompteModel = ((ConsultCompteModel) s.getTableModel());
                            Ecriture ecriture = consultCompteModel.getEcritures().get(modelIndex);

                            MouvementSQLElement.showSource(ecriture.getIdMvt());

                        }
                    });
                    menuDroit.show(mE.getComponent(), mE.getX(), mE.getY());
                }
            }
        });

    }
    return tableTmp;
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public TransferHandler dragRows(final JTable table, final List<String> specs) {
    TransferHandler th = null;//  w w w .ja va 2 s. c om
    try {
        final DataFlavor ndf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
        final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
        final String charset = df.getParameter("charset");
        final Transferable transferable = new Transferable() {
            @Override
            public Object getTransferData(DataFlavor arg0) throws UnsupportedFlavorException, IOException {
                if (arg0.equals(ndf)) {
                    int[] rr = currentRowSelection; //table.getSelectedRows();
                    List<String> selseq = new ArrayList<String>(rr.length);
                    for (int r : rr) {
                        int i = table.convertRowIndexToModel(r);
                        selseq.add(specs.get(i));
                    }
                    return selseq;
                } else {
                    String ret = "";//makeCopyString();
                    for (int r = 0; r < table.getRowCount(); r++) {
                        Object o = table.getValueAt(r, 0);
                        if (o != null) {
                            ret += o.toString();
                        } else {
                            ret += "";
                        }
                        for (int c = 1; c < table.getColumnCount(); c++) {
                            o = table.getValueAt(r, c);
                            if (o != null) {
                                ret += "\t" + o.toString();
                            } else {
                                ret += "\t";
                            }
                        }
                        ret += "\n";
                    }
                    //return arg0.getReaderForText( this );
                    return new ByteArrayInputStream(ret.getBytes(charset));
                }
                //return ret;
            }

            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { df, ndf };
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor arg0) {
                if (arg0.equals(df) || arg0.equals(ndf)) {
                    return true;
                }
                return false;
            }
        };

        th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            public int getSourceActions(JComponent c) {
                return TransferHandler.COPY_OR_MOVE;
            }

            public boolean canImport(TransferHandler.TransferSupport support) {
                return true;
            }

            protected Transferable createTransferable(JComponent c) {
                currentRowSelection = table.getSelectedRows();

                return transferable;
            }

            public boolean importData(TransferHandler.TransferSupport support) {
                try {
                    System.err.println(table.getSelectedRows().length);

                    DataFlavor[] dfs = support.getDataFlavors();
                    if (support.isDataFlavorSupported(ndf)) {
                        Object obj = support.getTransferable().getTransferData(ndf);
                        ArrayList<String> seqs = (ArrayList<String>) obj;

                        /*ArrayList<String> newlist = new ArrayList<String>( serifier.lgse.size() );
                        for( int r = 0; r < table.getRowCount(); r++ ) {
                           int i = table.convertRowIndexToModel(r);
                           newlist.add( specs.get(i) );
                        }
                        serifier.lgseq.clear();
                        serifier.lgseq = newlist;*/

                        Point p = support.getDropLocation().getDropPoint();
                        int k = table.rowAtPoint(p);

                        specs.removeAll(seqs);
                        for (String s : seqs) {
                            specs.add(k++, s);
                        }

                        TableRowSorter<TableModel> trs = (TableRowSorter<TableModel>) table.getRowSorter();
                        trs.setSortKeys(null);

                        table.tableChanged(new TableModelEvent(table.getModel()));

                        return true;
                    } /* else if( support.isDataFlavorSupported( df ) ) {                     
                        Object obj = support.getTransferable().getTransferData( df );
                        InputStream is = (InputStream)obj;
                                
                        System.err.println( charset );
                        importReader( new BufferedReader(new InputStreamReader(is, charset)) );
                                
                        updateView();
                                
                        return true;
                      }  else if( support.isDataFlavorSupported( DataFlavor.stringFlavor ) ) {                     
                        Object obj = support.getTransferable().getTransferData( DataFlavor.stringFlavor );
                        String str = (String)obj;
                        importReader( new BufferedReader( new StringReader(str) ) );
                                
                        updateView();
                                
                        return true;
                      }*/
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
    return th;
}

From source file:org.svv.acmate.gui.ACTestingPanel.java

private void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 80; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width + 1, width);
        }/*from w w w.j  a v  a  2 s  .  co  m*/
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

From source file:org.tellervo.desktop.io.ImportDialog.java

@SuppressWarnings("unused")
private static void updateRowHeights(JTable table) {
    try {//from   ww  w  .  j  a  v  a2  s .c  o m
        for (int row = 0; row < table.getRowCount(); row++) {
            int rowHeight = table.getRowHeight();

            for (int column = 0; column < table.getColumnCount(); column++) {
                Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
                rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
            }

            table.setRowHeight(row, rowHeight);
        }
    } catch (ClassCastException e) {
    }
}

From source file:org.yccheok.jstock.gui.JTableUtilities.java

public static void setJTableOptions(JTable jTable, GUIOptions.JTableOptions jTableOptions) {
    if (jTableOptions.getColumnSize() <= 0) {
        // A bug introduced in version 1.0.5p. Due to incorrect
        // implementation of Utils.toXML, we may get a table option with 0
        // column turned on. To avoid all columns being turned off, we will
        // return early.
        return;//from w w w .  j  a va  2 s .  co  m
    }

    final Locale locale = jTableOptions.getLocale();
    // HACKING!
    boolean first_column_hacking_required = false;

    // Remove unwanted column. MUST BE DONE FIRST!
    for (int i = 0; i < jTable.getColumnCount(); i++) {
        final String name = jTable.getColumnName(i);

        // In to avoid the following situation.
        // 1. GUIOptions is being saved when we are in Chinese locale.
        // 2. Application is restarted in English locale.
        // 3. We are trying to compare English wording with Chinese wording.
        //
        // Before performing comparison, we shall convert name, to the locale
        // of table options.
        final java.util.List<String> keys = getKeys(name, Locale.getDefault());

        // Ensure correct resource file is being loaded.
        // When ResourceBundle.getBundle(..., locale) is being called, the
        // system will try to search in the following sequence.
        // 1. gui_<locale>.properties.
        // 2. gui_<default_locale>.properties.
        // 3. gui.properties.
        final Locale oldLocale = Locale.getDefault();
        Locale.setDefault(locale);
        try {
            final ResourceBundle bundle = ResourceBundle.getBundle("org.yccheok.jstock.data.gui", locale);
            Locale.setDefault(oldLocale);

            // Try all the keys.
            boolean found = false;
            for (String key : keys) {
                final String translated_name = bundle.getString(key);
                if (jTableOptions.contains(translated_name)) {
                    found = true;
                    break;
                }
            }

            /* Remove any unwanted columns. */
            if (found == false) {
                // HACKING!
                // Some customers complain their first column of Watchlist,
                // or Portfolio are being hidden. I'm not sure why that
                // happen. YES! I have really no idea why that happen!
                // This is a hacking way "if (i > 0)" to prevent such 
                // problem. Shh...
                if (i > 0) {
                    removeTableColumn(jTable, name);
                    i--;
                } else {
                    first_column_hacking_required = true;
                }
            }
        } finally {
            Locale.setDefault(oldLocale);
        }
    }

    final int optionsCount = jTableOptions.getColumnSize();
    final int tableCount = jTable.getColumnCount();

    // HACKING!
    // jTableOptions doesn't have first column information if first_column_hacking_required
    // is true. When perform column moving, we will start from 2nd column if
    // first_column_hacking_required is true. Assume first column will always
    // stay in first column.
    int target = first_column_hacking_required ? 1 : 0;

    /* Sort the columns according to user preference. */
    for (int i = 0; i < optionsCount; i++) {
        final String name = jTableOptions.getColumnName(i);
        final java.util.List<String> keys = getKeys(name, locale);
        assert (keys != null);

        int index = -1;
        for (int j = 0; j < tableCount; j++) {
            // Try all the keys.
            boolean found = false;
            String translated_name = null;
            for (String key : keys) {
                translated_name = GUIBundle.getString(key);
                if (jTable.getColumnName(j).equals(translated_name)) {
                    found = true;
                    break;
                }
            }

            if (found) {
                /* Restore width. */
                jTable.getColumn(translated_name).setPreferredWidth(jTableOptions.getColumnWidth(i));

                index = j;
                break;
            }
        }

        if (index >= 0) {
            jTable.moveColumn(index, target++);
        }
    }
}

From source file:org.yccheok.jstock.gui.JTableUtilities.java

public static void insertTableColumnFromModel(JTable jTable, Object value, int clickedColumnIndex) {
    boolean isVisible = true;

    try {/*from  w w  w.j  a  v  a 2 s .  c  om*/

        TableColumn tableColumn = jTable.getColumn(value);

    }

    catch (java.lang.IllegalArgumentException exp) {

        isVisible = false;

    }

    if (isVisible)
        return;

    TableModel tableModel = jTable.getModel();

    final int modelIndex = getModelColumnIndex(jTable, value);

    Class c = tableModel.getColumnClass(modelIndex);

    TableColumn tableColumn = new javax.swing.table.TableColumn(modelIndex, 0, jTable.getDefaultRenderer(c),
            jTable.getDefaultEditor(c));

    jTable.addColumn(tableColumn);

    makeTableColumnWidthFit(jTable, jTable.getColumnCount() - 1, 5);

    // If we right clicked on the 3rd column, and select a new column, we
    // would like the new column to be inserted into 4th column. Note that,
    // clickedColumnIndex will be < 0, if we right clicked on empty area.
    if (clickedColumnIndex < 0) {
        // Have it in the last column when we right clicked on empty area.
        jTable.moveColumn(jTable.getColumnCount() - 1, jTable.getColumnCount() - 1);
    } else {
        // +1, as we want our newly inserted column to be at the right of
        // clicked column.
        jTable.moveColumn(jTable.getColumnCount() - 1,
                Math.min(jTable.getColumnCount() - 1, clickedColumnIndex + 1));
    }
}

From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java

public void _refreshGUIAfterFeeCalculationEnabledOptionsChanged() {
    this.buyTreeTable.repaint();
    this.sellTreeTable.repaint();
    this.updateWealthHeader();

    // Add/ remove columns based on user option.
    final JStockOptions jStockOptions = JStock.instance().getJStockOptions();
    JTable[] tables = { this.sellTreeTable, this.buyTreeTable };
    String[] names = { GUIBundle.getString("PortfolioManagementJPanel_Broker"),
            GUIBundle.getString("PortfolioManagementJPanel_ClearingFee"),
            GUIBundle.getString("PortfolioManagementJPanel_StampDuty") };

    for (JTable table : tables) {
        for (String name : names) {
            if (jStockOptions.isFeeCalculationEnabled()) {
                final int columnCount = table.getColumnCount();
                JTableUtilities.insertTableColumnFromModel(table, name, columnCount);
            } else {
                JTableUtilities.removeTableColumn(table, name);
            }/* ww w .j a va  2  s . co  m*/
        }
    }
}

From source file:org.yccheok.jstock.gui.PortfolioManagementJPanel.java

public boolean saveGUIOptions() {
    if (Utils.createCompleteDirectoryHierarchyIfDoesNotExist(
            org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "config") == false) {
        return false;
    }/*from  w ww . j  a v  a 2s  .  com*/

    final GUIOptions guiOptions = new GUIOptions();

    final org.jdesktop.swingx.JXTreeTable[] treeTables = { buyTreeTable, sellTreeTable };

    for (org.jdesktop.swingx.JXTreeTable treeTable : treeTables) {
        final javax.swing.table.JTableHeader jTableHeader = treeTable.getTableHeader();
        final JTable jTable = jTableHeader.getTable();
        final GUIOptions.JTableOptions jTableOptions = new GUIOptions.JTableOptions();

        final int count = jTable.getColumnCount();
        for (int i = 0; i < count; i++) {
            final String name = jTable.getColumnName(i);
            final TableColumn column = jTable.getColumnModel().getColumn(i);
            jTableOptions.addColumnOption(
                    GUIOptions.JTableOptions.ColumnOption.newInstance(name, column.getWidth()));
        }

        guiOptions.addJTableOptions(jTableOptions);
    }

    guiOptions.addDividerLocation(jSplitPane1.getDividerLocation());

    File f = new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "config" + File.separator
            + "portfoliomanagementjpanel.xml");
    return org.yccheok.jstock.gui.Utils.toXML(guiOptions, f);
}

From source file:vista.promocion.DiagPromocion.java

private void configurarTabla(JTable tbl) {
    JViewport scroll = (JViewport) tbl.getParent();
    int ancho = scroll.getWidth();
    int anchoColumna = 0;
    TableColumnModel modeloColumna = tbl.getColumnModel();
    TableColumn columnaTabla;/*from w w w.  j a  v a2s  .c o  m*/
    for (int i = 0; i < tbl.getColumnCount(); i++) {
        columnaTabla = modeloColumna.getColumn(i);
        switch (i) {
        case 0:
            anchoColumna = (1 * ancho) / 100;
            break;
        case 1:
            anchoColumna = (20 * ancho) / 100;
            break;
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
            anchoColumna = (5 * ancho) / 100;
            break;
        }
        columnaTabla.setPreferredWidth(anchoColumna);
        tbl.setColumnModel(modeloColumna);
    }
    tbl.getTableHeader().setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 10));
    tbl.getTableHeader().setBackground(java.awt.Color.WHITE);
    tbl.getTableHeader().setForeground(Color.BLACK);
    //Si le queremos cambiar el tamao a la tablita
    tbl.setFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 10));
}