Example usage for javax.swing JTable getModel

List of usage examples for javax.swing JTable getModel

Introduction

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

Prototype

public TableModel getModel() 

Source Link

Document

Returns the TableModel that provides the data displayed by this JTable .

Usage

From source file:logdruid.ui.DateEditor.java

private void initColumnSizes(JTable theTable) {
    MyTableModel2 model = (MyTableModel2) theTable.getModel();
    TableColumn column = null;//from   w  w w  .j a  v a 2s  .  c o  m
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    // Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 3; i++) {
        column = theTable.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        /*
         * comp = table.getDefaultRenderer(model.getColumnClass(i)).
         * getTableCellRendererComponent( table, longValues[i], false,
         * false, 0, i);
         */
        cellWidth = comp.getPreferredSize().width;

        if (DEBUG) {
            logger.info("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth
                    + "; cellWidth = " + cellWidth);
        }

        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:com.emr.schemas.SavedProcessesDataMover.java

/**
 * Constructor/*w w w. j ava2s .  c  om*/
 */
public SavedProcessesDataMover() {
    initComponents();
    this.setClosable(true);
    final Action processDelete = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable) e.getSource();
            int modelRow = Integer.valueOf(e.getActionCommand());
            String foreignKeysTable = (String) tblProcesses.getModel().getValueAt(modelRow, 0);
            if (foreignKeysTable == null || "".equals(foreignKeysTable)) {
                JOptionPane.showMessageDialog(null, "Table is Empty", "Empty Table", JOptionPane.ERROR_MESSAGE);
            } else {

            }
        }

    };
    final SQLiteGetProcesses sp = new SQLiteGetProcesses();
    sp.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent event) {
            switch (event.getPropertyName()) {
            case "progress":
                System.out.println("Fetching data from db");
                break;
            case "state":
                switch ((SwingWorker.StateValue) event.getNewValue()) {
                case DONE:
                    try {
                        model = sp.get();
                        tblProcesses.setModel(model);
                        tblProcesses.getColumnModel().getColumn(0).setMaxWidth(300);
                        //hide irrelevant columns
                        tblProcesses.getColumnModel().getColumn(2).setMinWidth(0);
                        tblProcesses.getColumnModel().getColumn(2).setMaxWidth(0);
                        tblProcesses.getColumnModel().getColumn(3).setMinWidth(0);
                        tblProcesses.getColumnModel().getColumn(3).setMaxWidth(0);
                        tblProcesses.getColumnModel().getColumn(4).setMinWidth(0);
                        tblProcesses.getColumnModel().getColumn(4).setMaxWidth(0);
                        tblProcesses.getColumnModel().getColumn(5).setMinWidth(0);
                        tblProcesses.getColumnModel().getColumn(5).setMaxWidth(0);
                        tblProcesses.getColumnModel().getColumn(6).setMinWidth(0);
                        tblProcesses.getColumnModel().getColumn(6).setMaxWidth(0);

                        ButtonColumn buttonColumn = new ButtonColumn(tblProcesses, processDelete, 7, "Delete");
                    } catch (final CancellationException ex) {
                        Logger.getLogger(SavedProcessesDataMover.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(SavedProcessesDataMover.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        Logger.getLogger(SavedProcessesDataMover.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    break;
                }
                break;
            }
        }

    });
    sp.execute();

    tblProcesses.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                JTable target = (JTable) e.getSource();
                int rowIndex = target.getSelectedRow();
                String selectQry = (String) target.getModel().getValueAt(rowIndex, 2);
                String destinationTable = (String) target.getModel().getValueAt(rowIndex, 3);
                String truncateFirst = (String) target.getModel().getValueAt(rowIndex, 4);
                String destinationColumns = (String) target.getModel().getValueAt(rowIndex, 5);
                String columnsToBeMapped = (String) target.getModel().getValueAt(rowIndex, 6);
                lblUpdateText.setText("<html><b color='red'>Moving Data</b></html>");
                dbProgressBar.setIndeterminate(true);
                new DBUpdater(selectQry, destinationTable, truncateFirst, destinationColumns, columnsToBeMapped)
                        .execute();
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

}

From source file:Import.pnl_import_vcf.java

private void btn_importActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_importActionPerformed
    // TODO add your handling code here:
    String[] singleColumns = singleColumns();
    String[] selectedFamilies = selectedFamilies();
    CheckBoxList checkList = new CheckBoxList();
    DefaultListModel model = new DefaultListModel();
    for (String a : singleColumns) {
        model.addElement(a);/*from  w w  w  .  ja va2s  .  com*/
    }
    checkList.setModel(model);
    String filePath = filePathField.getText();
    if (rbt_existing_tbl.isSelected()) {
        try {
            String[] selectedTableFamilies = tableFamilies();
            JTable tableMap = new JTable();
            DefaultTableModel tableMapModel = (DefaultTableModel) tableMap.getModel();
            setMapTable(tableMap, tableMapModel, selectedFamilies, selectedTableFamilies);
            int map = JOptionPane.showConfirmDialog(null, tableMap, "Please map to column",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null);
            if (map == 2) {
                return;
            }
            Object[] o = getMapPair(tableMapModel);
            String selectTableName = tbl_hbase_tables.getValueAt(tbl_hbase_tables.getSelectedRow(), 0)
                    .toString();
            String[] mappedFamilies = (String[]) o[1];
            String[] mappedTableFamilies = (String[]) o[0];
            String[] keys = getKey(selectTableName);
            importToTable.importDataJob importData = new importDataJob();
            importData.importData(filePath, selectTableName, mappedTableFamilies, mappedFamilies, keys);
        } catch (Exception ex) {
            Logger.getLogger(pnl_import_vcf.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            int key = JOptionPane.showConfirmDialog(null, checkList, "Please choose Key",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null);
            if (key == 2) {
                return;
            }
            Object[] selectedKey = checkList.getCheckBoxListSelectedValues();
            File f = new File(filePath);
            String fname = f.getName();
            String tableName = FilenameUtils.removeExtension(fname);
            writeKey(selectedKey, tableName);
            writeType(tableName);
            createColumnsTxt(tableName);
            ArrayList<String> list = new ArrayList<>();
            for (Object o : selectedKey) {
                list.add(o.toString());
            }
            String[] keys = list.toArray(new String[list.size()]);
            importToNewTable.createDataJob importData = new createDataJob();
            importData.importData(filePath, selectedFamilies, keys);
        } catch (Exception ex) {
            Logger.getLogger(pnl_import_vcf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    filePathField.setText(null);
    DefaultDualListModel dualModel = new DefaultDualListModel();
    list_dual_hbase_column_family.setModel(dualModel);
    pnl_import_vcf.showHBaseTables runabletask = new pnl_import_vcf.showHBaseTables();
    new Thread(runabletask).start();
}

From source file:computer_store.GUI.java

/**
 * Takes a JTable and a ResultSet as parameters and populates the JTable with the supplied ResultSet
 * @param table/*w  ww.  j a  v a2 s  .  c  om*/
 * @param rs 
 */
private void fillTable(javax.swing.JTable table, java.sql.ResultSet rs) {
    try {

        //To remove previously added rows
        while (table.getRowCount() > 0) {
            ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        Object[] ids = new Object[columns];
        while (rs.next()) {
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++) {
                row[i - 1] = rs.getObject(i);
            }
            ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
        }
        for (int i = 1; i <= columns; i++) {
            ids[i - 1] = rs.getMetaData().getColumnName(i);
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids);
        rs.close();
    } catch (Exception e) {
        System.out.print(e);
    }
}

From source file:mekhq.Utilities.java

/**
 * Export a JTable to a CSV file//from  w ww.j  a va2 s.c  om
 * @param table
 * @param file
 * @return report
 */
public static String exportTabletoCSV(JTable table, File file) {
    String report;
    try {
        TableModel model = table.getModel();
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath()));
        String[] columns = new String[model.getColumnCount()];
        for (int i = 0; i < model.getColumnCount(); i++) {
            columns[i] = model.getColumnName(i);
        }
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(columns));

        for (int i = 0; i < model.getRowCount(); i++) {
            Object[] towrite = new String[model.getColumnCount()];
            for (int j = 0; j < model.getColumnCount(); j++) {
                // use regex to remove any HTML tags
                towrite[j] = model.getValueAt(i, j).toString().replaceAll("\\<[^>]*>", "");
            }
            csvPrinter.printRecord(towrite);
        }

        csvPrinter.flush();
        csvPrinter.close();

        report = model.getRowCount() + " " + resourceMap.getString("RowsWritten.text");
    } catch (Exception ioe) {
        MekHQ.getLogger().log(Utilities.class, "exportTabletoCSV", LogLevel.INFO, "Error exporting JTable");
        report = "Error exporting JTable. See log for details.";
    }
    return report;
}

From source file:computer_store.GUI.java

private void fillCompTable(javax.swing.JTable table, java.sql.ResultSet rs) {
    try {//from   w  w  w . j  a  v  a2s .co m

        //To remove previously added rows
        while (table.getRowCount() > 0) {
            ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        int rows = 0;
        java.util.ArrayList<String> helper = new java.util.ArrayList();
        //Adding column titles
        Object[] ids = new Object[columns];
        for (int i = 1; i <= columns; i++) {
            ids[i - 1] = rs.getMetaData().getColumnName(i);
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids);
        //Adding rows from ResultSet to table model.
        while (rs.next()) {
            helper.add(rs.getString("name"));
            rows++;
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++) {
                row[i - 1] = rs.getObject(i);
            }
            ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
        }

        //Adding new column with restock numbers            
        Object[] restock = new Object[rows];
        for (int i = 0; i < restock.length; i++) {
            restock[i] = handler.getCompRestock(helper.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("# to Restock", restock);
        //Adding selling prices
        Object[] sellPrice = new Object[rows];
        for (int i = 0; i < sellPrice.length; i++) {
            sellPrice[i] = ((int) jTable1.getValueAt(i, 1)) * 1.3;
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("Selling price", sellPrice);

        rs.close();
    } catch (Exception e) {
        System.out.print(e);
    }
}

From source file:computer_store.GUI.java

private void fillSysTable(javax.swing.JTable table, java.sql.ResultSet rs) {
    try {//from  w  ww. ja v a2s . c o m

        //To remove previously added rows
        while (table.getRowCount() > 0) {
            ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        int rows = 0;
        //Adding column headers
        Object[] ids = new Object[columns];
        for (int i = 1; i <= columns; i++) {
            ids[i - 1] = rs.getMetaData().getColumnName(i);
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids);
        java.util.ArrayList<String> systems = new java.util.ArrayList();
        //Adding rows from ResultSet
        while (rs.next()) {
            systems.add(rs.getString(1));
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++) {
                row[i - 1] = rs.getObject(i);
            }
            ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
            rows++;
        }
        //Adding new column with prices
        Object[] prices = new Object[rows];
        for (int i = 0; i < prices.length; i++) {
            prices[i] = handler.getSystemPrice(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("Price", prices);
        //Adding new column with selling prices
        Object[] sellPrices = new Object[rows];
        for (int i = 0; i < sellPrices.length; i++) {
            sellPrices[i] = handler.getSystemSellPrice(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("Selling price", sellPrices);
        //Adding new column with current stock
        Object[] inStock = new Object[rows];
        for (int i = 0; i < prices.length; i++) {
            inStock[i] = handler.systemsInStock(systems.get(i));
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).addColumn("In stock", inStock);

        rs.close();
    } catch (Exception e) {
        System.out.print(e);
    }
}

From source file:king.flow.action.DefaultMsgSendAction.java

private void showOnComponent(Object metaNode, TLSResult result) {
    Component meta = (Component) metaNode;
    getLogger(CommunicationWorker.class.getName()).log(Level.INFO, "Display component[{0}] type : {1}",
            new Object[] { String.valueOf(meta.getId()), meta.getType().value() });
    JsonParser jsonParser;//from   w  w w  . j  a  v a  2s . co  m
    JsonArray arrays;
    switch (meta.getType()) {
    case TABLE:
        try {
            jsonParser = new JsonParser();
            arrays = jsonParser.parse(result.getOkMsg()).asArray();
            JTable table = getBlock(meta.getId(), JTable.class);
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            for (Iterator it = arrays.iterator(); it.hasNext();) {
                JsonArray row = (JsonArray) it.next();
                Vector<String> rowData = new Vector<>();
                for (Object v : row) {
                    rowData.add(v.toString());
                }
                model.addRow(rowData);
            }
        } catch (Exception e) {
            getLogger(CommunicationWorker.class.getName()).log(Level.WARNING,
                    "Invalid array data [ {0} ] for TABLE component[{1}], \n exception is {2}",
                    new Object[] { result.getOkMsg(), String.valueOf(meta.getId()), e });
        }
        break;
    case ADVANCED_TABLE:
        try {
            jsonParser = new JsonParser();
            JsonObject jsonObj = jsonParser.parse(result.getOkMsg()).asObject();
            Integer total = jsonObj.getInt(ADVANCED_TABLE_TOTAL_PAGES);
            Integer page = jsonObj.getInt(ADVANCED_TABLE_CURRENT_PAGE);
            arrays = jsonObj.getArray(ADVANCED_TABLE_VALUE);
            getLogger(CommunicationWorker.class.getName()).log(Level.INFO,
                    "Dump JSON DATA for ADVANCED_TABLE: \n{0} \ntotal: {1} \npage: {2}",
                    new Object[] { jsonObj.toString(), total, page });
            JXMsgPanel advanceTable = getBlock(meta.getId(), JXMsgPanel.class);
            advanceTable.refreshTotalPages(total);
            advanceTable.refreshCurrentPage(page);
            advanceTable.refreshTable(arrays);
        } catch (Exception e) {
            getLogger(CommunicationWorker.class.getName()).log(Level.WARNING,
                    "Invalid complex data [ {0} ] for ADVANCED_TABLE component[{1}] \n exception is {2}",
                    new Object[] { result.getOkMsg(), String.valueOf(meta.getId()), e });
        }
        break;
    case LABEL:
        JLabel label = getBlock(meta.getId(), JLabel.class);
        if (result.getRetCode() == 0) {
            label.setText(StringEscapeUtils.unescapeHtml(result.getOkMsg()));
        } else {
            label.setText(StringEscapeUtils.unescapeHtml(result.getErrMsg()));
        }
        break;
    case TEXT_FIELD:
        JTextField textField = getBlock(meta.getId(), JTextField.class);
        if (result.getRetCode() == 0) {
            textField.setText(result.getOkMsg());
        } else {
            CommonUtil.showErrorMsg(textField.getTopLevelAncestor(), result.getErrMsg());
        }
        break;
    default:
        getLogger(CommunicationWorker.class.getName()).log(Level.WARNING,
                "Unsupported displayed component type : {0}", meta.getType());
    }
}

From source file:com.willwinder.universalgcodesender.uielements.panels.ControllerProcessorSettingsPanel.java

private JTable initCustomRemoverTable(JTable table) {
    final String[] columnNames = { Localization.getString("settings.processors.enabled"),
            Localization.getString("PatternRemover") };

    final Class[] columnTypes = { Boolean.class, String.class };

    DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override//from  ww w.ja v  a 2 s  .com
        public Class<?> getColumnClass(int idx) {
            return columnTypes[idx];
        }
    };

    table.setModel(model);
    table.getTableHeader().setReorderingAllowed(false);
    table.getModel().addTableModelListener((TableModelEvent e) -> change());

    return table;
}

From source file:au.org.ala.delta.editor.ui.ActionSetsDialog.java

private void updateGUI() {
    Map<DirectiveType, List<DirectiveFile>> files = new HashMap<DirectiveFile.DirectiveType, List<DirectiveFile>>();

    for (DirectiveType type : DirectiveType.values()) {
        files.put(type, new ArrayList<DirectiveFile>());
    }//from ww w  . ja  va 2 s .  c om
    int numFiles = _model.getDirectiveFileCount();
    for (int i = 1; i <= numFiles; i++) {
        DirectiveFile file = _model.getDirectiveFile(i);
        files.get(file.getType()).add(file);
    }
    conforTable.setModel(new DirectiveFileTableModel(files.get(DirectiveType.CONFOR)));
    configureWidths(conforTable);
    intkeyTable.setModel(new DirectiveFileTableModel(files.get(DirectiveType.INTKEY)));
    configureWidths(intkeyTable);
    distTable.setModel(new DirectiveFileTableModel(files.get(DirectiveType.DIST)));
    configureWidths(distTable);
    keyTable.setModel(new DirectiveFileTableModel(files.get(DirectiveType.KEY)));
    configureWidths(keyTable);

    JTable[] tables = { conforTable, intkeyTable, distTable, keyTable };

    for (JTable table : tables) {
        TableRowSorter<? extends TableModel> sorter = new TableRowSorter<DirectiveFileTableModel>(
                (DirectiveFileTableModel) table.getModel());
        table.setRowSorter(sorter);
    }

    updateAction();
}