Example usage for javax.swing.table DefaultTableModel getColumnCount

List of usage examples for javax.swing.table DefaultTableModel getColumnCount

Introduction

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

Prototype

public int getColumnCount() 

Source Link

Document

Returns the number of columns in this data table.

Usage

From source file:lob.VisualisationGUI.java

public void clearTable(final JTable table) {

    DefaultTableModel dm = (DefaultTableModel) table.getModel();

    for (int i = 0; i < dm.getRowCount(); i++) {
        for (int j = 0; j < dm.getColumnCount(); j++) {
            dm.setValueAt("", i, j);
        }/*from   ww  w  .j a va2s  .  c  o m*/
    }
}

From source file:de.fionera.javamailer.gui.mainView.controllerMain.java

/**
 * Adds the Actionlisteners to the Mainview
 *
 * @param viewMain The Mainview//from ww w  .j  ava  2  s.  c om
 */
private void addActionListener(viewMain viewMain) {
    /**
     * Changes the Amount in the AmountLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderAmountMails().addChangeListener(e -> {
        Main.amountMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberAmountMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Changes the Delay in the DelayLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderDelayMails().addChangeListener(e -> {
        Main.delayMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberDelayMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Closes the Program, when close is clicked
     */
    viewMain.getCloseItem().addActionListener(e -> System.exit(0));

    /**
     * Opens the Settings when the settingsbutton is clicked
     */
    viewMain.getSettingsItem().addActionListener(e -> new controllerSettings());

    /**
     * Save current Setup
     */
    viewMain.getSaveSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();
        JFrame parentFrame = new JFrame();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");

        int userSelection = jChooser.showSaveDialog(parentFrame);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = new File(jChooser.getSelectedFile() + ".jms");

            saveSetup(viewMain, fileToSave, new ObjectMapper());
        }
    });

    /**
     * Load Setup
     */
    viewMain.getLoadSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");
        jChooser.showOpenDialog(null);

        File file = jChooser.getSelectedFile();

        if (file != null) {
            if (file.getName().endsWith("jms")) {
                try {
                    loadSetup(viewMain, file, new ObjectMapper());
                } catch (Exception error) {
                    error.printStackTrace();
                }
            }
        }
    });

    /**
     * Opens the Open File dialog and start the Parsing of it
     */
    viewMain.getSelectRecipientsPanel().getSelectExcelFileButton().addActionListener(e -> {
        DefaultTableModel model;
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel 97 - 2003 (.xls)", "xls"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel (.xlsx)", "xlsx"));
        jChooser.setDialogTitle("Select only Excel workbooks");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("xls")) {
                ArrayList returnedData = parseFilesForImport.parseXLSFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else if (file.getName().endsWith("xlsx")) {
                ArrayList returnedData = parseFilesForImport.parseXLSXFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else {
                JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",
                        JOptionPane.ERROR_MESSAGE);

                model = new DefaultTableModel();
            }
        } else {
            model = new DefaultTableModel();

        }

        viewMain.getSelectRecipientsPanel().getTable().setModel(model);

        int tableWidth = model.getColumnCount() * 150;
        int tableHeight = model.getRowCount() * 25;
        viewMain.getSelectRecipientsPanel().getTable().setPreferredSize(new Dimension(tableWidth, tableHeight));
        viewMain.getCheckAllSettings().getLabelRecipientsAmount().setText("" + model.getRowCount());
        viewMain.getCheckAllSettings().getLabelTimeAmount()
                .setText(""
                        + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                        + " Seconds");
    });

    /**
     * Starts the sending of th Mails, when the send button is clicked
     */
    viewMain.getCheckAllSettings().getSendMails().addActionListener(e -> {

        String subject = viewMain.getSetMailSettingsPanel().getFieldSubject().getText();
        Sender sender = (Sender) viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem();
        JTable table = viewMain.getSelectRecipientsPanel().getTable();

        if (table != null && sender != null && !subject.equals("")) {
            new sendMails(viewMain);
        }
    });

    /**
     * Clears the Table on buttonclick
     */
    viewMain.getSelectRecipientsPanel().getClearTableButton().addActionListener(e -> {
        viewMain.getSelectRecipientsPanel().getTable().setModel(new DefaultTableModel());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * Removes a single Row on menu click in the editMailPanel
     */
    viewMain.getSelectRecipientsPanel().getDeleteRow().addActionListener(e -> {
        ((DefaultTableModel) viewMain.getSelectRecipientsPanel().getTable().getModel())
                .removeRow(viewMain.getSelectRecipientsPanel().getTable().getSelectedRowCount());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * The Changes the displayed Value when the Time in the Timespinner is getting changed.
     */
    viewMain.getSetMailSettingsPanel().getTimeSpinner().addChangeListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());

    });
    viewMain.getSetMailSettingsPanel().getDatePicker().addActionListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());
    });

    /**
     * Actionevent for the Edit Sender Button
     */
    viewMain.getSetMailSettingsPanel().getButtonEditSender()
            .addActionListener(e -> new controllerEditSender(controllerMain));

    /**
     * Actionevent for the Import Button in the EditMail View
     */
    viewMain.getEditMailPanel().getImportWord().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Word 97 - 2003 (.doc)", "doc"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("HTML File (.html)", "html"));
        jChooser.setDialogTitle("Select only Word Documents");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("doc")) {
                String returnedData = parseFilesForImport.parseDOCFile(file);
                viewMain.getEditMailPanel().setEditorText(returnedData);

            } else if (file.getName().endsWith("html")) {
                String content = "";
                try {
                    content = Jsoup.parse(file, "UTF-8").toString();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                viewMain.getEditMailPanel().setEditorText(content);

            } else {
                JOptionPane.showMessageDialog(null, "Please select a Document file.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    /**
     * The Tab Changelistener
     * The first if Statement sets the Labels on the Checkallsettings Panel to the right Values
     */
    viewMain.getTabbedPane().addChangeListener(e -> {
        if (viewMain.getTabbedPane().getSelectedComponent() == viewMain.getCheckAllSettings()) {

            viewMain.getCheckAllSettings().getLabelMailBelow()
                    .setText(viewMain.getEditMailPanel().getEditorText()); //Displays the Mail

            viewMain.getCheckAllSettings().getLabelRecipientsAmount()
                    .setText("" + viewMain.getSelectRecipientsPanel().getTable().getModel().getRowCount()); //Displays the Amount of Recipients

            if (viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem() != null) {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText(
                        viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem().toString());
            } else {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText("Select a Sender first");
            }

            viewMain.getCheckAllSettings().getLabelSubjectInserted()
                    .setText(viewMain.getSetMailSettingsPanel().getFieldSubject().getText()); //Displays the Subject

            if (viewMain.getSetMailSettingsPanel().getCheckBoxDelayMails().isSelected()) {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(true);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(true);

                viewMain.getCheckAllSettings().getLabelDelayNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()); //The Delay Number
                viewMain.getCheckAllSettings().getLabelAmountNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()); //The Amount of Mail in one package
                viewMain.getCheckAllSettings().getLabelTimeAmount()
                        .setText(""
                                + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                        * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                        / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                                + " Seconds"); //The Time the Sending needs

            } else {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(false);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(false);
            }

            if (viewMain.getSetMailSettingsPanel().getCheckBoxSendLater().isSelected()) {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingAt()
                        .setText(viewMain.getSetMailSettingsPanel().getDate().toString());

            } else {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(false);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(false);
            }

        }
    });

}

From source file:grupob.TipoProceso.java

private void btnGuardarInstitucionalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarInstitucionalActionPerformed
    // TODO add your handling code here:
    DefaultTableModel modelo = (DefaultTableModel) tblInstitucional.getModel();
    if (0 < modelo.getRowCount()) {
        modelo.getColumnCount();
        Institucion institucion = new Institucion();
        for (int i = 0; i < modelo.getRowCount(); i++) {
            institucion.setId(listaInstituciones.get(i).getId());
            institucion.setNombre(tblInstitucional.getValueAt(i, 0).toString());

            String n = tblInstitucional.getValueAt(i, 1).toString();
            int num = -1;
            try {
                num = Integer.parseInt(n);

            } catch (Exception ex) {

                JOptionPane.showMessageDialog(null,
                        "Error: Ingreso un valor distinto de un numero en la fila: " + (i + 1) + " columna: 2");
                return;

            }/*from   w  w w .ja  v  a 2s  . c  om*/

            if (num < 0) {
                JOptionPane.showMessageDialog(null,
                        "Error: Ingreso un numero negativo en la fila: " + (i + 1) + " columna: 2");
                return;
            }

            institucion.setCantidadVotantesRegistrados(num);

            institucion.setTipoProceso(5);//Tipo de proceso 5
            for (int j = 0; i < listaLocalesI.size(); j++) {
                if (listaLocalesI.get(j).getNombre().equals(tblInstitucional.getValueAt(i, 2).toString())) {
                    institucion.setIdLocal(listaLocalesI.get(j).getId());
                    break;
                }
            }
            Manager.updateInstitucion(institucion);
            //            System.out.println(listaInstituciones.get(i).getId());
            //            System.out.println(tblInstitucional.getValueAt(i, 0).toString());
            //            System.out.println(tblInstitucional.getValueAt(i, 1).toString());
            //            System.out.println(tblInstitucional.getValueAt(i, 2).toString());        

        }

        //            
    }

    JOptionPane.showMessageDialog(this, "Se guardaron los cambios con exito");

}

From source file:dataviewer.DataViewer.java

private void renderData(DefaultTableModel model) {
    tb_data.setVisible(false);/*w w w . java 2  s.c o m*/

    tb_data.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            c.setBackground(row % 2 == 0 ? Color.WHITE : new Color(240, 240, 240));

            if (table.isCellSelected(row, column)) {
                c.setBackground(new Color(200, 0, 0));
                c.setForeground(Color.white);
            } else if (table.isRowSelected(row)) {
                c.setBackground(new Color(0, 0, 200));
                c.setForeground(Color.white);
            } else {
                c.setForeground(Color.black);
            }
            return c;
        }
    });

    tb_data.setGridColor(new Color(220, 220, 220));
    tb_data.setShowVerticalLines(true);
    tb_data.setModel(model);

    for (int i = 0; i < model.getColumnCount(); ++i) {
        if (model.getColumnName(i).equals("_N_")) {
            TableRowSorter trs = new TableRowSorter(model);
            trs.setComparator(i, new IntComparator());
            tb_data.setRowSorter(trs);
        }
    }

    for (int j = 0; j < tb_data.getColumnCount(); j++) {
        int width = 0;
        TableColumn col = tb_data.getColumnModel().getColumn(j);
        TableCellRenderer renderer = tb_data.getTableHeader().getDefaultRenderer();
        Component comp = renderer.getTableCellRendererComponent(tb_data, col.getHeaderValue(), false, false, 0,
                0);
        width = Math.max(comp.getPreferredSize().width, width);
        for (int i = 0; i < tb_data.getRowCount(); i++) {
            renderer = tb_data.getCellRenderer(i, j);
            comp = tb_data.prepareRenderer(renderer, i, j);
            width = Math.max(comp.getPreferredSize().width, width);
        }
        tb_data.getColumnModel().getColumn(j).setPreferredWidth(width + 20);
    }

    tb_data.setVisible(true);

}

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowserAdvancedFilter.java

public void saveSelections() {
    DefaultTableModel contentSearchModel = ((DefaultTableModel) contentSearchTable.getModel());
    DefaultTableModel metaDataSearchModel = ((DefaultTableModel) metaDataSearchTable.getModel());
    ItemSelectionTableModel<Integer, String> connectorModel = ((ItemSelectionTableModel<Integer, String>) connectorTable
            .getModel());/*from  w ww .j a va2s.c o m*/

    cachedSettings.clear();

    cachedSettings.put("messageIdLowerField", messageIdLowerField.getText());
    cachedSettings.put("messageIdUpperField", messageIdUpperField.getText());
    cachedSettings.put("originalIdLowerField", originalIdLowerField.getText());
    cachedSettings.put("originalIdUpperField", originalIdUpperField.getText());
    cachedSettings.put("importIdLowerField", importIdLowerField.getText());
    cachedSettings.put("importIdUpperField", importIdUpperField.getText());
    cachedSettings.put("serverIdField", serverIdField.getText());
    cachedSettings.put("sendAttemptsLower", sendAttemptsLower.getValue());
    cachedSettings.put("sendAttemptsUpper", sendAttemptsUpper.getValue());
    cachedSettings.put("attachment", attachmentCheckBox.isSelected());
    cachedSettings.put("error", errorCheckBox.isSelected());

    Object[][] contentSearchData = new Object[contentSearchModel.getRowCount()][contentSearchModel
            .getColumnCount()];
    for (int row = 0; row < contentSearchModel.getRowCount(); row++) {
        for (int column = 0; column < contentSearchModel.getColumnCount(); column++) {
            contentSearchData[row][column] = contentSearchModel.getValueAt(row, column);
        }
    }
    cachedSettings.put("contentSearchTable", contentSearchData);

    Object[][] metaDataSearchData = new Object[metaDataSearchModel.getRowCount()][metaDataSearchModel
            .getColumnCount()];
    for (int row = 0; row < metaDataSearchModel.getRowCount(); row++) {
        for (int column = 0; column < metaDataSearchModel.getColumnCount(); column++) {
            metaDataSearchData[row][column] = metaDataSearchModel.getValueAt(row, column);
        }
    }
    cachedSettings.put("metaDataSearchTable", metaDataSearchData);

    Boolean[] connectorData = new Boolean[connectorModel.getRowCount()];
    for (int row = 0; row < connectorModel.getRowCount(); row++) {
        connectorData[row] = (Boolean) connectorModel.getValueAt(row, ItemSelectionTableModel.CHECKBOX_COLUMN);
    }

    cachedSettings.put("connectorTable", connectorData);
}

From source file:gtu._work.etc.GoogleContactUI.java

void googleTableMouseClicked(MouseEvent evt) {
    try {//ww  w  .j a  v a  2 s.co m
        JPopupMenuUtil popupUtil = JPopupMenuUtil.newInstance(googleTable).applyEvent(evt);

        //CHANGE ENCODE
        popupUtil.addJMenuItem("set encode", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String code = StringUtils.defaultString(JOptionPaneUtil.newInstance().iconPlainMessage()
                            .showInputDialog("input file encode", "ENCODE"), "UTF8");
                    encode = Charset.forName(code).displayName();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
                System.err.println("encode : " + encode);
            }
        });

        //SIMPLE LOAD GOOGLE CSV FILE
        popupUtil.addJMenuItem("open Google CSV file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile("csv", ".csv")
                        .showOpenDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                try {
                    if (file.getName().endsWith(".csv")) {
                        DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                        LineNumberReader reader = new LineNumberReader(
                                new InputStreamReader(new FileInputStream(file), GOOGLE_CVS_ENCODE));
                        for (String line = null; (line = reader.readLine()) != null;) {
                            if (reader.getLineNumber() == 1) {
                                continue;
                            }
                            model.addRow(line.split(","));
                        }
                        reader.close();
                        googleTable.setModel(model);
                        JTableUtil.newInstance(googleTable).hiddenAllEmptyColumn();
                    }
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //SAVE CSV FILE FOR GOOGLE
        popupUtil.addJMenuItem("save to Google CVS file", new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = JFileChooserUtil.newInstance().selectFileOnly().addAcceptFile(".csv", ".csv")
                        .showSaveDialog().getApproveSelectedFile();
                if (file == null) {
                    errorMessage("file is not correct!");
                    return;
                }
                file = FileUtil.getIndicateFileExtension(file, ".csv");
                try {
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(file), GOOGLE_CVS_ENCODE));
                    StringBuilder sb = new StringBuilder();
                    for (Object title : googleColumns) {
                        sb.append(title + ",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    System.out.println(sb);
                    writer.write(sb.toString());
                    writer.newLine();
                    DefaultTableModel model = (DefaultTableModel) googleTable.getModel();
                    for (int row = 0; row < model.getRowCount(); row++) {
                        sb = new StringBuilder();
                        for (int col = 0; col < model.getColumnCount(); col++) {
                            String colVal = StringUtils.defaultString((String) model.getValueAt(row, col), "");
                            if (colVal.equalsIgnoreCase("null")) {
                                colVal = "";
                            }
                            sb.append(colVal + ",");
                        }
                        sb.deleteCharAt(sb.length() - 1);
                        System.out.println(sb);
                        writer.write(sb.toString());
                        writer.newLine();
                    }
                    writer.flush();
                    writer.close();
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                }
            }
        });

        //PASTE CLIPBOARD
        popupUtil.addJMenuItem("paste clipboard", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_multiRowData(true);
            }
        });

        popupUtil.addJMenuItem("paste clipboard to selected cell", new ActionListener() {
            public void actionPerformed(ActionEvent paramActionEvent) {
                JTableUtil.newInstance(googleTable).pasteFromClipboard_singleValueToSelectedCell();
            }
        });

        JMenuItem addEmptyRowItem = JTableUtil.newInstance(googleTable).jMenuItem_addRow(false,
                "add row count?");
        addEmptyRowItem.setText("add row");
        JMenuItem removeColumnItem = JTableUtil.newInstance(googleTable).jMenuItem_removeColumn(null);
        removeColumnItem.setText("remove column");
        JMenuItem removeRowItem = JTableUtil.newInstance(googleTable).jMenuItem_removeRow(null);
        removeRowItem.setText("remove row");
        JMenuItem removeAllRowItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_removeAllRow("remove all row?");
        removeAllRowItem.setText("remove all row");
        JMenuItem clearSelectedCellItem = JTableUtil.newInstance(googleTable)
                .jMenuItem_clearSelectedCell("are you sure clear selected area?");
        clearSelectedCellItem.setText("clear selected area");
        popupUtil.addJMenuItem(addEmptyRowItem, removeColumnItem, removeRowItem, removeAllRowItem,
                clearSelectedCellItem);
        popupUtil.show();
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:edu.ku.brc.specify.conversion.SpecifyDBConverter.java

/**
 * /*ww w. j a  v a2s. co m*/
 */
protected void createTableSummaryPage() {
    TableWriter tblWriter = convLogger.getWriter("TableSummary.html", "Table Summary");
    tblWriter.startTable();
    tblWriter.println("<tr><th>Table</th><th>Count</th></tr>");
    int total = 0;
    for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
        Integer count = BasicSQLUtils.getCount("select count(*) from " + ti.getName());
        if (count != null && count > 0) {
            tblWriter.log(ti.getName(), count.toString());
        }
        total += count;
    }
    tblWriter.println("<tr><td>Total Records</td><td>" + total + "</td></tr>");
    tblWriter.endTable();

    String sql;

    //----------------------------------------------------------------------------------
    tblWriter.println("<H3>Col Obj Counts By Discipline/Collection</H3>");
    sql = " SELECT cct.CollectionObjectTypeName, cs.SeriesName, Count(cc.CollectionObjectCatalogID) FROM catalogseries AS cs "
            + "Inner Join collectionobjectcatalog AS cc ON cs.CatalogSeriesID = cc.CatalogSeriesID "
            + "Inner Join collectionobjecttype AS cct ON cc.CollectionObjectTypeID = cct.CollectionObjectTypeID "
            + "Inner Join collectionobject AS co ON cc.CollectionObjectCatalogID = co.CollectionObjectID "
            + " WHERE co.DerivedFromID IS NULL " + "GROUP BY cct.CollectionObjectTypeName, cs.SeriesName";

    showTable(tblWriter, "Specify 5", false, sql, "Discipline", "Collection", "Count");

    sql = "SELECT d.Name, c.CollectionName, Count(co.CollectionObjectID) AS `Count` FROM discipline AS d "
            + "Inner Join collection AS c ON d.UserGroupScopeId = c.DisciplineID "
            + "Inner Join collectionobject AS co ON co.CollectionID = c.UserGroupScopeId "
            + "GROUP BY d.Name, c.CollectionName";
    tblWriter.println("<BR>");
    showTable(tblWriter, "Specify 6", true, sql, "Discipline", "Collection", "Count");

    //----------------------------------------------------------------------------------
    /*tblWriter.println("<H3>Collecting Events Counts By Discipline</H3>");
    sql = " SELECT ct.CollectionObjectTypeName, Count(ce.CollectingEventID) FROM collectionobjecttype AS ct " +
    "Inner Join collectingevent AS ce ON ct.CollectionObjectTypeID = ce.BiologicalObjectTypeCollectedID " +
    "GROUP BY ct.CollectionObjectTypeName";
    showTable(tblWriter, "Specify 5", false, sql, "Discipline", "Count");
            
    sql = " SELECT d.Name, Count(ce.CollectingEventID) FROM discipline AS d " +
    "Inner Join collectingevent AS ce ON d.UserGroupScopeId = ce.DisciplineID " +
    "GROUP BY d.Name";
    tblWriter.println("<BR>");
    showTable(tblWriter, "Specify 6", true, sql, "Discipline", "Count");
    */
    //----------------------------------------------------------------------------------
    tblWriter.println("<H3>Col Obj Counts By Collection</H3>");
    sql = " SELECT cs.SeriesName, Count(cc.CollectionObjectCatalogID) FROM catalogseries AS cs "
            + "Inner Join collectionobjectcatalog AS cc ON cs.CatalogSeriesID = cc.CatalogSeriesID "
            + "Inner Join collectionobject AS co ON cc.CollectionObjectCatalogID = co.CollectionObjectID "
            + " WHERE co.DerivedFromID IS NULL " + "GROUP BY cs.SeriesName";

    showTable(tblWriter, "Specify 5", false, sql, "Collection", "Count");

    sql = " SELECT c.CollectionName, Count(co.CollectionObjectID) FROM collection AS c "
            + "Inner Join collectionobject AS co ON c.UserGroupScopeId = co.CollectionID "
            + "GROUP BY c.CollectionName";
    tblWriter.println("<BR>");
    showTable(tblWriter, "Specify 6", true, sql, "Collection", "Count");

    //----------------------------------------------------------------------------------
    tblWriter.println("<H3>Locality Counts</H3>");
    sql = " SELECT Count(LocalityID) FROM locality";
    showTable(tblWriter, "Specify 5", false, sql, "Count");

    sql = " SELECT Count(LocalityID) FROM locality";
    tblWriter.println("<BR>");
    showTable(tblWriter, "Specify 6", true, sql, "Count");

    //----------------------------------------------------------------------------------
    tblWriter.println("<H3>Locality Counts By Discipline</H3>");
    sql = " SELECT ct.CollectionObjectTypeName, Count(locid) FROM collectionobjecttype AS ct "
            + "Inner Join (SELECT ce.CollectingEventID as ceid, ce.BiologicalObjectTypeCollectedID as botid, locality.LocalityID as locid FROM collectingevent ce Inner Join locality ON ce.LocalityID = locality.LocalityID GROUP BY locality.LocalityID) T1 ON ct.CollectionObjectTypeID = T1.botid "
            + "GROUP BY ct.CollectionObjectTypeName";

    showTable(tblWriter, "Specify 5", false, sql, "Discipline", "Count");

    sql = " SELECT d.Name, Count(l.LocalityID) FROM discipline AS d "
            + "Inner Join locality AS l ON d.UserGroupScopeId = l.DisciplineID " + "GROUP BY d.Name";
    tblWriter.println("<BR>");
    showTable(tblWriter, "Specify 6", true, sql, "Discipline", "Count");

    //----------------------------------------------------------------------------------
    tblWriter.startTable();
    tblWriter.logHdr(CollectionInfoModel.getHeaders());

    DefaultTableModel model = CollectionInfo.getCollectionInfoTableModel(true);
    Object[] row = new Object[model.getColumnCount()];
    for (int r = 0; r < model.getRowCount(); r++) {
        for (int i = 0; i < model.getColumnCount(); i++) {
            row[i] = model.getValueAt(r, i);
        }
        tblWriter.logObjRow(row);
    }
    tblWriter.endTable();
    tblWriter.close();

    /*
    tblWriter.startTable();
    tblWriter.logHdr("&nbsp;", "Specify 5", "Specify 6");
    for (Triple<String, String, String> qry : getSummaryQueries())
    {
            
    }
    tblWriter.endTable();
    */
}

From source file:edu.ku.brc.specify.tasks.subpane.ESResultsTablePanel.java

/**
 * @param table// ww w .  j a va 2s. c o  m
 * @param model
 */
protected void 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()];
    int[] strWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        TableCellRenderer headerRenderer = col.getHeaderRenderer();
        if (headerRenderer instanceof JLabel) {
            ((JLabel) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER);
        }

        // Get width of column header
        TableCellRenderer renderer = col.getCellRenderer();
        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
        int strWidth = 0;
        boolean isString = model.getColumnClass(i) == String.class;
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            Object objVal = table.getValueAt(r, vColIndex);
            if (isString && objVal != null) {
                strWidth = Math.max(strWidth, ((String) objVal).length());
            }
            comp = renderer.getTableCellRendererComponent(table, objVal, false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

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

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            TableColumn col = colModel.getColumn(i);
            TableCellRenderer renderer = col.getCellRenderer();
            if (renderer != null) {
                ((JLabel) renderer).setHorizontalAlignment(
                        strWidths[i] > 20 ? SwingConstants.LEFT : SwingConstants.CENTER);
                //((JLabel)renderer).setHorizontalAlignment(SwingConstants.LEFT);
            }

            if (model.getColumnCount() > 3 && renderedWidthTotal > preferredWidthTotal) {
                col.setPreferredWidth(colWidths[i]);
            }
        }
    }

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

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

From source file:library.Form_Library.java

License:asdf

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    JFileChooser chooser = new JFileChooser();
    int k = chooser.showSaveDialog(this);
    if (k == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {/*  w  w  w . j  a  v  a  2s.  c  o m*/
            FileWriter out = new FileWriter(file + ".xls");
            BufferedWriter bu = new BufferedWriter(out);
            DefaultTableModel model = (DefaultTableModel) tbBookAdmin.getModel();
            for (int i = 0; i < model.getColumnCount(); i++) {
                bu.write(model.getColumnName(i) + "\t");
            }
            bu.write("\n");
            for (int i = 0; i < model.getRowCount(); i++) {
                for (int j = 0; j < model.getColumnCount(); j++) {
                    bu.write(model.getValueAt(i, j) + "\t");
                }
                bu.write("\n");
            }
            bu.close();
            JOptionPane.showMessageDialog(this, "Saved");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Can't Save");
        }
    }
}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *///  w  ww . j a  v a 2 s  .c  o  m
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}