Example usage for javax.swing.table TableModel getRowCount

List of usage examples for javax.swing.table TableModel getRowCount

Introduction

In this page you can find the example usage for javax.swing.table TableModel getRowCount.

Prototype

public int getRowCount();

Source Link

Document

Returns the number of rows in the model.

Usage

From source file:Main.java

/**
 *  Calculates the optimal width for the column of the given table. The
 *  calculation is based on the preferred width of the header and cell
 *  renderer.//  ww  w .  j a va  2 s .  c  o  m
 *  <br>
 *  Taken from the newsgoup de.comp.lang.java with some modifications.<br>
 *  Taken from FOPPS/EnhancedTable - http://fopps.sourceforge.net/<br>
 *
 *  @param table    the table to calculate the column width
 *  @param col      the column to calculate the widths
 *  @return         the width, -1 if error
 */
public static int calcColumnWidth(JTable table, int col) {
    int width = calcHeaderWidth(table, col);
    if (width == -1)
        return width;

    TableColumnModel columns = table.getColumnModel();
    TableModel data = table.getModel();
    int rowCount = data.getRowCount();
    TableColumn column = columns.getColumn(col);
    try {
        for (int row = rowCount - 1; row >= 0; --row) {
            Component c = table.prepareRenderer(table.getCellRenderer(row, col), row, col);
            width = Math.max(width, c.getPreferredSize().width + 10);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return width;
}

From source file:au.com.jwatmuff.eventmanager.export.CSVExporter.java

public static void generateFromTable(TableModel tm, OutputStream out) {
    int rows = tm.getRowCount();
    int cols = tm.getColumnCount();
    Object[][] table = new Object[rows + 1][cols];
    for (int j = 0; j < cols; j++)
        table[0][j] = tm.getColumnName(j);
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            table[i + 1][j] = tm.getValueAt(i, j);

    generateFromArray(table, out);/*from w w  w.  j a v a2  s . c  om*/
}

From source file:Main.java

/**
 * Adjusts the widths and heights of the cells of the supplied table to fit their contents.
 *//*from   www . j a v a  2 s  .c o  m*/
public static void sizeToContents(JTable table) {
    TableModel model = table.getModel();
    TableColumn column = null;
    Component comp = null;
    int ccount = table.getColumnModel().getColumnCount(), rcount = model.getRowCount(), cellHeight = 0;

    for (int cc = 0; cc < ccount; cc++) {
        int headerWidth = 0, cellWidth = 0;
        column = table.getColumnModel().getColumn(cc);
        try {
            comp = column.getHeaderRenderer().getTableCellRendererComponent(null, column.getHeaderValue(),
                    false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;
        } catch (NullPointerException e) {
            // getHeaderRenderer() this doesn't work in 1.3
        }

        for (int rr = 0; rr < rcount; rr++) {
            Object cellValue = model.getValueAt(rr, cc);
            comp = table.getDefaultRenderer(model.getColumnClass(cc)).getTableCellRendererComponent(table,
                    cellValue, false, false, 0, cc);
            Dimension psize = comp.getPreferredSize();
            cellWidth = Math.max(psize.width, cellWidth);
            cellHeight = Math.max(psize.height, cellHeight);
        }
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }

    if (cellHeight > 0) {
        table.setRowHeight(cellHeight);
    }
}

From source file:Main.java

protected static boolean contains(int row, TableModel model) {
    if (model == null) {
        return false;
    }//from   www. j a  v a2  s  . c om
    if (row < 0) {
        return false;
    }
    if (row >= model.getRowCount()) {
        return false;
    }
    return true;
}

From source file:Main.java

/**
 * Save the contents of a table to a TSV file
 * Note:  uses toString() on the header cells as well as the data cells.  If you've got funny columns,
 * expect funny behavior//from w w w .ja v a  2 s.c  o  m
 * @param table
 * @param outFile
 * @throws IOException
 */
public static void SaveTableAsTSV(JTable table, File outFile) throws IOException {
    PrintWriter outPW = new PrintWriter(outFile);

    TableModel tableModel = table.getModel();
    TableColumnModel columnModel = table.getColumnModel();

    StringBuffer headerLineBuf = new StringBuffer();
    for (int i = 0; i < columnModel.getColumnCount(); i++) {
        if (i > 0)
            headerLineBuf.append("\t");
        headerLineBuf.append(columnModel.getColumn(i).getHeaderValue().toString());
    }
    outPW.println(headerLineBuf.toString());
    outPW.flush();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        StringBuffer lineBuf = new StringBuffer();
        for (int j = 0; j < tableModel.getColumnCount(); j++) {
            if (j > 0)
                lineBuf.append("\t");
            lineBuf.append(tableModel.getValueAt(i, j).toString());
        }
        outPW.println(lineBuf.toString());
        outPW.flush();
    }
    outPW.close();
}

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  ww w.  j  a  va2s .com*/
 */
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:edu.ku.brc.specify.utilapps.SetUpBuildDlg.java

/**
 * @param table/*from   ww w. ja  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();
    }
}

From source file:com.limegroup.gnutella.gui.GUIUtils.java

/**
 * It will adjust the column width to match the widest element.
 * (You might not want to use this for every column, consider some columns might be really long)
 * @param model/*  w  w w  .  j  ava 2  s .c  om*/
 * @param columnIndex
 * @param table
 * @return
 */
public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding,
        JTable table) {

    if (columnIndex > model.getColumnCount() - 1) {
        //invalid column index
        return;
    }

    if (!model.getColumnClass(columnIndex).equals(String.class)) {
        return;
    }

    String longestValue = "";
    for (int row = 0; row < model.getRowCount(); row++) {
        String strValue = (String) model.getValueAt(row, columnIndex);
        if (strValue != null && strValue.length() > longestValue.length()) {
            longestValue = strValue;
        }
    }

    Graphics g = table.getGraphics();

    try {
        int suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g)
                .getWidth();
        table.getColumnModel().getColumn(columnIndex)
                .setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth) + rightPadding);
    } catch (Exception e) {
        table.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);
        e.printStackTrace();
    }

}

From source file:com.aw.swing.mvp.cmp.RowSelectorMediator.java

/**
 * AWProcess when a user change the text contained for the textfield
 *
 * @param e/*from   w  w w .j a v a 2s  . c  om*/
 */
private void textFieldChanged(DocumentEvent e) {
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Processing text field change with column index: " + columnIndex + " changed event " + e + " ");
    }

    String prefix = textField.getText();
    if (prefix.length() == 0) {
        table.clearSelection();
        return;
    }

    boolean found = false;
    TableModel m = table.getModel();

    for (int i = 0; found == false && i < m.getRowCount(); i++) {
        Object o = m.getValueAt(i, columnIndex);
        if (o == null) {
            continue;
        }

        String s = o.toString();
        if (s.toUpperCase().startsWith(prefix.toUpperCase())) {
            table.setRowSelectionInterval(i, i);
            Rectangle rect = table.getCellRect(i, columnIndex, true);
            table.scrollRectToVisible(rect);

            found = true;
        }
    }

    if (!found) {
        table.clearSelection();
    }
}

From source file:MainFrame.MainFrame.java

public MainFrame() {
    //Create menu
    this.menuBar = new JMenuBar();
    this.menuProxy = new JMenu("Proxy");
    this.menuBar.add(menuProxy);
    this.cbMenuItem = new JCheckBoxMenuItem("? proxy");
    this.cbMenuItem.setMnemonic(KeyEvent.VK_C);

    ActionListener aListener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            AbstractButton aButton = (AbstractButton) event.getSource();
            boolean selected = aButton.getModel().isSelected();
            if (selected) {
                SingleDataHolder.getInstance().isProxyActivated = true;
                SingleDataHolder.getInstance().proxyIpAdress = MainFrame.this.proxyIpAdress.getText();
                SingleDataHolder.getInstance().proxyPort = Integer.parseInt(MainFrame.this.proxyPort.getText());
                SingleDataHolder.getInstance().proxyLogin = MainFrame.this.proxyLogin.getText();
                SingleDataHolder.getInstance().proxyPassword = String
                        .valueOf(MainFrame.this.proxyPassword.getPassword());
            } else {
                SingleDataHolder.getInstance().isProxyActivated = false;
            }//from   w  w  w .  j  a  va2  s .  c  o m
        }
    };
    this.cbMenuItem.addActionListener(aListener);

    this.proxyIpAdress = new JTextField();
    this.proxyPort = new JTextField();
    this.proxyLogin = new JTextField();
    ;
    this.proxyPassword = new JPasswordField();
    this.menuProxy.add(this.cbMenuItem);
    this.menuProxy.add(new JLabel("IP ?"));
    this.menuProxy.add(this.proxyIpAdress);
    this.menuProxy.add(new JLabel("? "));
    this.menuProxy.add(this.proxyPort);
    this.menuProxy.add(new JLabel(""));
    this.menuProxy.add(this.proxyLogin);
    this.menuProxy.add(new JLabel(""));
    this.menuProxy.add(this.proxyPassword);
    this.setJMenuBar(this.menuBar);

    communicator = new HttpCommunicator();
    myActionListener = new mainFrameActionListener();
    mainPanel = new JPanel(new BorderLayout());
    this.setContentPane(mainPanel);

    JPanel P = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 5));
    mainPanel.add(P, BorderLayout.NORTH);

    //Create Group label
    labelGroup = new JLabel("");
    P.add(labelGroup);
    //Create Group combo
    comboGroup = new JComboBox();
    comboGroup.addItem("?");
    comboGroup.addActionListener(myActionListener);
    P.add(comboGroup);

    //Create Date label
    labelDate = new JLabel("");
    P.add(labelDate);
    //Create Date combo
    comboDate = new JComboBox();
    comboDate.addItem("?");
    comboDate.addActionListener(myActionListener);
    P.add(comboDate);

    //Create Delete button
    buttonDelete = new JButton("");
    buttonDelete.setEnabled(false);
    buttonDelete.addActionListener(myActionListener);
    P.add(buttonDelete);

    //this.checkConnection = new CheckConnection(buttonDelete);

    buttonPasswordsManager = new JButton(" ");
    buttonPasswordsManager.addActionListener(myActionListener);
    P.add(buttonPasswordsManager);

    try {
        Image img = ImageIO.read(getClass().getResource("resources/table_refresh.png"));
        this.buttonRefresh = new JButton(new ImageIcon(img));
        this.buttonRefresh.addActionListener(myActionListener);
        this.buttonRefresh.setToolTipText(" ");
        P.add(buttonRefresh);
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    //CreateLessonTableModel
    lessonTableModel = new LessonTableModel();

    try {
        communicator.setCombos(comboGroup, comboDate, lessonTableModel);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, " ? ? .");
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    //CreateTable
    table = new JTable(lessonTableModel);
    table.setFillsViewportHeight(true);
    table.setAutoCreateRowSorter(true);

    JScrollPane scrollP = new JScrollPane(table);
    mainPanel.add(scrollP, BorderLayout.CENTER);
    //Create Table sorter
    sorter = new TableRowSorter<LessonTableModel>(lessonTableModel);
    table.setRowSorter(sorter);
    table.getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel) e.getSource();
            for (int i = 0; i < model.getRowCount(); i++) {
                if ((boolean) model.getValueAt(i, 2) == true) {
                    buttonDelete.setEnabled(true);
                    return;
                }
            }
            buttonDelete.setEnabled(false);
        }
    });

    //Standart block
    this.setSize(700, 400);
    this.setTitle(" ");
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent we) {
            System.exit(0);
        }
    });
    try {
        Image img = ImageIO.read(getClass().getResource("resources/appIcon.png"));
        this.setIconImage(img);
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.setVisible(true);
}