Example usage for javax.swing JTable getRowCount

List of usage examples for javax.swing JTable getRowCount

Introduction

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

Prototype

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

Source Link

Document

Returns the number of rows that can be shown in the JTable, given unlimited space.

Usage

From source file:marytts.tools.redstart.AdminWindow.java

private void buildPromptTable() {

    this.promptArray = this.currentSession.getPromptArray();

    System.out.println("Loading prompts...");
    Test.output("Array contains " + promptArray.length + " prompts.");

    // Make column names array
    String[] columnNames = new String[3];
    columnNames[REC_STATUS_COLUMN] = "Status";
    columnNames[BASENAME_COLUMN] = "Basename";
    columnNames[PROMPT_TEXT_COLUMN] = "Prompt Preview";

    // Now create the table itself        
    JTable table = new JTable(new PromptTableModel(promptArray, columnNames, redAlertMode));
    table.setColumnSelectionAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Set alignment for the status colum to centered
    DefaultTableCellRenderer renderer = new ClippingColorRenderer();
    renderer.setHorizontalAlignment(JTextField.CENTER);
    table.getColumnModel().getColumn(REC_STATUS_COLUMN).setCellRenderer(renderer);

    // Set selection highlight colour to light blue
    table.setSelectionBackground(new java.awt.Color(153, 204, 255));

    // Add listeners
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent evt) {
            displayPromptText();//from ww  w  .j  av  a  2s.c o m
        }
    });

    // Store the table in an instance field accessible to the entire class
    this.jTable_PromptSet = table;

    Thread recordingStatusInitialiser = new Thread() {
        public void run() {
            updateAllRecStatus();
        }
    };
    recordingStatusInitialiser.start();

    // Display table in the appropriate component pane
    jScrollPane_PromptSet.setViewportView(table);

    if (promptArray.length > 0) {
        table.setRowSelectionInterval(0, 0); // Show first row of prompt table as selected               
        displayPromptText(); // Display the prompt text for the first prompt in the prompt display pane 
    }
    setColumnWidths();

    System.out.println("Total " + table.getRowCount() + " prompts loaded.");

}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table/*from  w  ww.  j  a v  a  2  s .c  o  m*/
 * @param model
 * @return
 */
public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        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;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);

    return table;
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

private int getRealRowCount(JTable table) {
    int ret = table.getRowCount();
    if (table.getRowSorter() != null) {
        ret = table.getRowSorter().getViewRowCount();
    }// w w w .  j  a  v  a  2s . c  o m

    return ret;
}

From source file:library.Form_Library.java

License:asdf

public static void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 15; // 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 av  a  2  s.c o m*/
        if (width > 300) {
            width = 300;
        }
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

From source file:app.RunApp.java

/**
 * Action for Export button//from ww w  . java 2 s  .  c o  m
 * 
 * @param evt Event
 * @param jtable Table
 */
private void buttonExportActionPerformed(java.awt.event.ActionEvent evt, JTable jtable) {
    if (jtable.getRowCount() == 0 || dataset == null) {
        JOptionPane.showMessageDialog(null, "The table is empty.", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    JFileChooser fc = new JFileChooser();

    //FileNameExtensionFilter fname = new FileNameExtensionFilter(".xls", "xls"); 
    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".csv", "csv");

    //Remove default
    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        FileFilter f1 = fc.getFileFilter();

        if (f1.getDescription().equals(".csv")) {
            try {
                String path = file.getAbsolutePath() + ".csv";

                BufferedWriter bw = new BufferedWriter(new FileWriter(path));
                PrintWriter wr = new PrintWriter(bw);

                switch (comboBoxLabelsInformation.getSelectedIndex()) {
                case 1:
                    ResultsIOUtils.saveTableLabelsetsFrequencyCsv(wr, jtable, labelsetStringsByFreq);
                    break;
                case 6:
                    ResultsIOUtils.saveTableLabelsetsIRCsv(wr, jtable, labelsetStringByIR);
                    break;
                default:
                    ResultsIOUtils.saveTableCsv(wr, jtable);
                    break;
                }

                wr.close();
                bw.close();

                JOptionPane.showMessageDialog(null, "File saved.", "Successful",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException | HeadlessException e1) {
                JOptionPane.showMessageDialog(null, "File not saved correctly.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }

        }
    }
}

From source file:app.RunApp.java

/**
 * Action for Export button//from  w  w  w. j a v a 2s  . com
 * 
 * @param evt Event
 * @param jtable Table
 * @param columns Columns
 * @param table Table type
 */
private void buttonExportActionPerformed(java.awt.event.ActionEvent evt, JTable jtable, JTable columns,
        String table) {
    if (jtable.getRowCount() == 0 || dataset == null) {
        JOptionPane.showMessageDialog(null, "The table is empty.", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    JFileChooser fc = new JFileChooser();

    //FileNameExtensionFilter fname = new FileNameExtensionFilter(".xls", "xls"); 
    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".csv", "csv");

    //Remove default
    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        FileFilter f1 = fc.getFileFilter();

        //Saving csv chi_phi
        if (f1.getDescription().equals(".csv")) {
            BufferedWriter bw;
            PrintWriter wr;

            try {
                String path = file.getAbsolutePath() + ".csv";
                bw = new BufferedWriter(new FileWriter(path));
                wr = new PrintWriter(bw);

                switch (table) {
                case "ChiPhi":
                    ResultsIOUtils.saveChiPhiTableCsv(wr, chiPhiCoefficients, dataset.getLabelNames());
                    break;
                case "Coocurrence":
                    ResultsIOUtils.saveCoocurrenceTableCsv(wr, coocurrenceCoefficients,
                            dataset.getLabelNames());
                    break;
                case "Heatmap":
                    ResultsIOUtils.saveHeatmapTableCsv(wr, heatmapCoefficients, dataset.getLabelNames());
                    break;
                default:
                    JOptionPane.showMessageDialog(null, "File not saved correctly.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    break;
                }

                wr.close();
                bw.close();

                JOptionPane.showMessageDialog(null, "File saved.", "Successful",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException | HeadlessException e1) {
                JOptionPane.showMessageDialog(null, "File not saved correctly.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void testFilter(FilterTestType testType)
        throws BadLocationException, InterruptedException, ReflectiveOperationException {
    MainGui mainGui = new MainGui(mockManyBrowsersPanel);
    mainGui.setMainCallbacks(mockMainCallbacks);

    Mockito.when(mockConfiguration.useSpanTable()).thenReturn(testType == CHANGE_TEXT);

    mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
    mainGui.initializeGui(TestUtilities.getSixTestArticles());

    waitForGuiTasks();/*  w  w  w  . ja  v  a 2  s .  co m*/

    JTable table = (JTable) findComponent(mockContentPane, JTable.class);
    assertNotNull(table);

    assertEquals(mockConfiguration.useSpanTable() ? 12 : 6, table.getRowCount());

    JTextField filterTextField = (JTextField) findComponent(mockContentPane, JTextField.class);
    assertNotNull(filterTextField);
    AbstractDocument document = (AbstractDocument) filterTextField.getDocument();

    document.insertString(0, "title:title1", null);

    assertEquals(mockConfiguration.useSpanTable() ? 2 : 1, table.getRowCount());

    if (testType == REMOVE_TEXT) {
        document.remove(0, document.getLength());
    } else if (testType == CHANGE_TEXT) {
        document.replace(6, 6, "title2", null);

        // Since change is implemented as remove and insert, the fireChangedUpdate method is called with reflection.
        AbstractDocument.DefaultDocumentEvent mockEvent = Mockito
                .mock(AbstractDocument.DefaultDocumentEvent.class);
        Method method = AbstractDocument.class.getDeclaredMethod("fireChangedUpdate", DocumentEvent.class);
        method.setAccessible(true);
        method.invoke(document, mockEvent);
    } else if (testType == NO_MATCHES) {
        document.insertString(document.getLength(), "-some-nonsense", null);
    }

    checkArticlesInGui(testType, mainGui, table.getRowCount());
}

From source file:op.tools.SYSTools.java

public static void packColumn(JTable table, int vColIndex, int margin) {
    TableModel model = table.getModel();
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }/*  w w w  .  jav  a 2  s . c  o  m*/
    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);

    OPDE.debug("packColumn/3: col=" + vColIndex + "  width=" + width);
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

/**
 * @deprecated Move to ResultController hierarchy.
 *//*from w w w  .  j ava  2 s.  c o m*/
private void cmdRestoreCurrentCollectableInDetails() {
    assert getCollectStateModel().getCollectState()
            .equals(new CollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW));

    if (stopEditingInDetails()) {
        final String sMessage = getSpringLocaleDelegate().getMessage("GenericObjectCollectController.75",
                "Soll der angezeigte Datensatz ({0}) wirklich wiederhergestellt werden?",
                getSelectedCollectable().getIdentifierLabel());
        final int iBtn = JOptionPane.showConfirmDialog(getTab(), sMessage, getSpringLocaleDelegate().getMessage(
                "GenericObjectCollectController.28", "Datensatz wiederherstellen"), JOptionPane.YES_NO_OPTION);

        if (iBtn == JOptionPane.OK_OPTION)
            UIUtils.runCommand(getTab(), new Runnable() {
                @Override
                public void run() {
                    try {
                        // try to find next or previous object:
                        final JTable tblResult = getResultTable();
                        final int iSelectedRow = tblResult.getSelectedRow();
                        if (iSelectedRow < 0)
                            throw new IllegalStateException();

                        final int iNewSelectedRow;
                        if (iSelectedRow < tblResult.getRowCount() - 1)
                            // the selected row is not the last row: select the next row
                            iNewSelectedRow = iSelectedRow;
                        else if (iSelectedRow > 0)
                            // the selected row is not the first row: select the previous row
                            iNewSelectedRow = iSelectedRow - 1;
                        else {
                            // the selected row is the single row: don't select a row
                            assert tblResult.getRowCount() == 1;
                            assert iSelectedRow == 0;
                            iNewSelectedRow = -1;
                        }

                        checkedRestoreCollectable(getSelectedCollectable());
                        getResultTableModel().remove(getSelectedCollectable());
                        getSearchStrategy().search(true);

                        if (iNewSelectedRow == -1) {
                            tblResult.clearSelection();
                            // switch to new mode:
                            getResultController().getSearchResultStrategy().refreshResult();
                        } else {
                            tblResult.setRowSelectionInterval(iNewSelectedRow, iNewSelectedRow);
                            // go into view mode again:
                            cmdEnterViewMode();
                        }
                    } catch (CommonPermissionException ex) {
                        final String sErrorMessage = getSpringLocaleDelegate().getMessage(
                                "GenericObjectCollectController.67",
                                "Sie verf\u00fcgen nicht \u00fcber die ausreichenden Rechte, um diesen Datensatz wiederherzustellen.");
                        Errors.getInstance().showExceptionDialog(getTab(), sErrorMessage, ex);
                    } catch (CommonBusinessException ex) {
                        Errors.getInstance().showExceptionDialog(getTab(),
                                getSpringLocaleDelegate().getMessage("GenericObjectCollectController.33",
                                        "Der Datensatz konnte nicht wiederhergestellt werden."),
                                ex);
                    }
                }
            });
    }
    setDeleteButtonToggleInDetails();
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

/**
 * Delete the selected object physically.
 * This is mostly a copy from CollectController.cmdDelete; just the message and the called delete method are different.
 *//*from  w w  w . j  a  v  a2  s.c  o m*/
protected void cmdDeletePhysically() {
    assert getCollectStateModel().getCollectState()
            .equals(new CollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW));

    if (stopEditingInDetails()) {
        final String sMessage = getSpringLocaleDelegate().getMessage("GenericObjectCollectController.73",
                "Soll der angezeigte Datensatz ({0}) wirklich endg\u00fcltig aus der Datenbank gel\u00f6scht werden?\nDieser Vorgang kann nicht r\u00fcckg\u00e4ngig gemacht werden! ",
                getSelectedCollectable().getIdentifierLabel());
        final int iBtn = JOptionPane.showConfirmDialog(getTab(), sMessage, getSpringLocaleDelegate()
                .getMessage("GenericObjectCollectController.24", "Datensatz endg\u00fcltig l\u00f6schen"),
                JOptionPane.YES_NO_OPTION);

        if (iBtn == JOptionPane.OK_OPTION)
            UIUtils.runCommand(getTab(), new Runnable() {
                @Override
                public void run() {
                    try {
                        // try to find next or previous object:
                        final JTable tblResult = getResultTable();
                        final int iSelectedRow = tblResult.getSelectedRow();
                        if (iSelectedRow < 0)
                            throw new IllegalStateException();

                        final int iNewSelectedRow;
                        if (iSelectedRow < tblResult.getRowCount() - 1)
                            // the selected row is not the last row: select the next row
                            iNewSelectedRow = iSelectedRow;
                        else if (iSelectedRow > 0)
                            // the selected row is not the first row: select the previous row
                            iNewSelectedRow = iSelectedRow - 1;
                        else {
                            // the selected row is the single row: don't select a row
                            assert tblResult.getRowCount() == 1;
                            assert iSelectedRow == 0;
                            iNewSelectedRow = -1;
                        }

                        checkedDeleteCollectablePhysically(getSelectedCollectable());

                        if (iNewSelectedRow == -1) {
                            tblResult.clearSelection();
                            // switch to new mode:
                            setCollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_NEW);
                        } else {
                            tblResult.setRowSelectionInterval(iNewSelectedRow, iNewSelectedRow);
                            // go into view mode again:
                            setCollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW);
                        }
                    } catch (CommonPermissionException ex) {
                        final String sErrorMessage = getSpringLocaleDelegate().getMessage(
                                "GenericObjectCollectController.70",
                                "Sie verf\u00fcgen nicht \u00fcber die ausreichenden Rechte, um dieses Objekt zu l\u00f6schen.");
                        Errors.getInstance().showExceptionDialog(getTab(), sErrorMessage, ex);
                    } catch (CommonBusinessException ex) {
                        if (!handlePointerException(ex))
                            Errors.getInstance().showExceptionDialog(getTab(),
                                    getSpringLocaleDelegate().getMessage("GenericObjectCollectController.18",
                                            "Das Objekt konnte nicht gel\u00f6scht werden."),
                                    ex);
                    }
                }
            });
    }
}