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.table.EventRecordingEditorTable.java

private void initColumnSizes(JTable theTable) {
    MyTableModel model = (MyTableModel) theTable.getModel();
    TableColumn column = null;/*from  w w w  . j  a  v  a 2 s .com*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

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

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

        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:GUI.MainJF.java

public void LlenarTabla() {
    String[] columnNames = { "ID", "Nombre", "Email", "Edad", "Tipo", "", "" };
    Object[][] data = null;//from  w w w .  j av  a2  s . c o m
    DefaultTableModel model = new DefaultTableModel(data, columnNames);

    HttpResponse response;
    response = JSON.request(Config.URL + "usuarios/listar.json");
    JSONObject jObject = JSON.JSON(response);
    try {
        JSONArray jsonArr = jObject.getJSONArray("data");

        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject data_json = jsonArr.getJSONObject(i);
            model.addRow(
                    new Object[] { data_json.get("idUsuario").toString(), data_json.get("nombre").toString(),
                            data_json.get("email").toString(), data_json.get("edad").toString(),
                            data_json.get("descripcion").toString(), "Editar", "Eliminar" });
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    tb_usuarios.setModel(model);

    Action editar = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {

            JTable table = (JTable) e.getSource();
            int modelRow = Integer.valueOf(e.getActionCommand());

            String id = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 0);
            String nombre = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 1);
            String email = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 2);
            String edad = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 3);
            String tipo = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 4);

            FormUsuarios U = new FormUsuarios();

            U.setID(id);
            U.setNombre(nombre);
            U.setEmail(email);
            U.setEdad(edad);
            U.setTipo(tipo);

            U.setLocationRelativeTo(null);
            U.setVisible(true);
        }
    };
    ButtonColumn botonEditar = new ButtonColumn(tb_usuarios, editar, 5);
    botonEditar.setMnemonic(KeyEvent.VK_D);

    Action eliminar = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            JTable table = (JTable) e.getSource();
            int modelRow = Integer.valueOf(e.getActionCommand());
            String id = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 0);
            String nombre = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 1);

            int rs = JOptionPane.showConfirmDialog(null,
                    "Estas seguro que deseas eliminas el usuario: " + nombre + " ?", "Eliminar",
                    JOptionPane.YES_NO_OPTION);
            if (rs == JOptionPane.YES_OPTION) {

                List<NameValuePair> parametros = new ArrayList<NameValuePair>();
                parametros.add(new BasicNameValuePair("idUsuario", id));

                HttpResponse response = JSON.request(Config.URL + "usuarios/eliminar.json", parametros);
                JSONObject jObject = JSON.JSON(response);
                int code = Integer.parseInt(jObject.get("code").toString());

                /*if(code == 201){
                JOptionPane.showMessageDialog(null, "Usuario eliminado");
                //((DefaultTableModel)table.getModel()).removeRow(modelRow);
                }else{
                JOptionPane.showMessageDialog(null, "Error eliminar Usuario");
                }*/
            }

        }
    };
    ButtonColumn botonEliminar = new ButtonColumn(tb_usuarios, eliminar, 6);
    botonEliminar.setMnemonic(KeyEvent.VK_D);
    model.fireTableDataChanged();

}

From source file:cz.lidinsky.editor.TableCellEditor.java

/**
 *  Returnes appropriate component based on the value datatype.
 *//*from   w ww .  j  a  v a  2  s . co  m*/
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
        int column) {
    KeyValueTableModel tableModel = (KeyValueTableModel) table.getModel();
    valueClass = tableModel.getCellClass(row, column);
    if (Color.class.isAssignableFrom(valueClass)) {
        type = COLOR;
        currentColor = (Color) value;
        return button;
    } else if (selected instanceof Changer && ((String) table.getValueAt(row, 0)).equals("Property")) {
        type = COMBO;
        // get appropriate object
        Changer changer = (Changer) selected;
        // get parent of the object
        Object parent = changer.getParent();
        // get list of appropriate methods
        fillComboBox(parent, changer.getPropertyClass());
        // create component
        // return it
        return comboBox;
    } else if (Method.class.isAssignableFrom(valueClass) && selected instanceof Changer) {
        type = COMBO;
        // get appropriate object
        Changer changer = (Changer) selected;
        // get parent of the object
        Object parent = changer.getParent();
        // get list of appropriate methods
        fillComboBox(parent, changer.getPropertyClass());
        // create component
        // return it
        return comboBox;
    } else if (valueClass == boolean.class) {
        type = CHECK;
        checkBox.setSelected(((Boolean) value).booleanValue());
        return checkBox;
    } else {
        type = TEXT;
        if (value == null)
            value = "";
        textField.setText(value.toString());
        return textField;
    }
}

From source file:logdruid.ui.mainpanel.MetadataRecordingSelectorPanel.java

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

    for (int i = 0; i < 4; i++) {
        column = theTable.getColumnModel().getColumn(i);
        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;
        cellWidth = comp.getPreferredSize().width;
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:com.aw.swing.mvp.binding.component.BndSJTable.java

/**
 * Get the JTableModel//from www .  ja  v a 2  s .  co  m
 *
 * @return
 */
private static JTableModel getJTableModel(JTable jTable) {
    JTableModel jTableModel = null;
    if (jTable.getModel() instanceof JTableModel) {
        jTableModel = (JTableModel) jTable.getModel();
    }
    return jTableModel;
}

From source file:ExtendedDnDDemo.java

protected void importString(JComponent c, String str) {
    JTable target = (JTable) c;
    DefaultTableModel model = (DefaultTableModel) target.getModel();
    int index = target.getSelectedRow();

    //Prevent the user from dropping data back on itself.
    //For example, if the user is moving rows #4,#5,#6 and #7 and
    //attempts to insert the rows after row #5, this would
    //be problematic when removing the original rows.
    //So this is not allowed.
    if (rows != null && index >= rows[0] - 1 && index <= rows[rows.length - 1]) {
        rows = null;/*from   w w  w.j a  v a2s.c om*/
        return;
    }

    int max = model.getRowCount();
    if (index < 0) {
        index = max;
    } else {
        index++;
        if (index > max) {
            index = max;
        }
    }
    addIndex = index;
    String[] values = str.split("\n");
    addCount = values.length;
    int colCount = target.getColumnCount();
    for (int i = 0; i < values.length && i < colCount; i++) {
        model.insertRow(index++, values[i].split(","));
    }
}

From source file:ExtendedDnDDemo.java

protected void cleanup(JComponent c, boolean remove) {
    JTable source = (JTable) c;
    if (remove && rows != null) {
        DefaultTableModel model = (DefaultTableModel) source.getModel();

        //If we are moving items around in the same table, we
        //need to adjust the rows accordingly, since those
        //after the insertion point have moved.
        if (addCount > 0) {
            for (int i = 0; i < rows.length; i++) {
                if (rows[i] > addIndex) {
                    rows[i] += addCount;
                }//w ww . j  av a  2 s.  c o m
            }
        }
        for (int i = rows.length - 1; i >= 0; i--) {
            model.removeRow(rows[i]);
        }
    }
    rows = null;
    addCount = 0;
    addIndex = -1;
}

From source file:logdruid.ui.RecordingList.java

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

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

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;
        cellWidth = comp.getPreferredSize().width;
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:DefaultsDisplay.java

protected void initFilters(JTable table) {
    TableRowSorter sorter = new TableRowSorter(table.getModel());
    table.setRowSorter(sorter);/*w  w w. java  2s.co m*/

    if (visualsFilter == null) {
        visualsFilter = new RowFilter<UIDefaultsTableModel, Integer>() {
            public boolean include(Entry<? extends UIDefaultsTableModel, ? extends Integer> entry) {
                UIDefaultsTableModel model = entry.getModel();
                Object defaultsValue = model.getValueAt(entry.getIdentifier().intValue(),
                        UIDefaultsTableModel.VALUE_COLUMN);

                return defaultsValue instanceof Color || defaultsValue instanceof Font
                        || defaultsValue instanceof Icon;
            }
        };
    }

    if (onlyVisualsCheckBox.isSelected()) {
        sorter.setRowFilter(visualsFilter);
    }
}

From source file:Software_Jframes.chart.java

void print_excel_report(JTable jTable5) {
    Access ac = new Access();
    try {/*from w  ww .  j a  v  a2s . co  m*/
        String filename = ac.chooseFile();

        WritableWorkbook wworkbook;
        wworkbook = Workbook.createWorkbook(new File(filename + ".xls"));
        WritableSheet wsheet = wworkbook.createSheet("First Sheet", 0);

        DefaultTableModel dtm = (DefaultTableModel) jTable5.getModel();
        Vector v = new Vector();
        int count_row = dtm.getRowCount();
        int count_col = dtm.getColumnCount();

        jxl.write.Label label1 = new jxl.write.Label(0, 0, "Good Name");
        wsheet.addCell(label1);
        jxl.write.Label label2 = new jxl.write.Label(1, 0, "Project Name");
        wsheet.addCell(label2);
        jxl.write.Label label3 = new jxl.write.Label(2, 0, "Cost");
        wsheet.addCell(label3);

        int i = 0;
        int j = 0;

        for (i = 0; i < count_row; i++) {
            for (j = 0; j < count_col; j++) {
                int temp_i = i + 2;
                jxl.write.Label label = new jxl.write.Label(j, temp_i, dtm.getValueAt(i, j) + "");
                wsheet.addCell(label);
            }
        }
        wworkbook.write();
        wworkbook.close();
        JOptionPane.showMessageDialog(null, "Successfully Create a excel file");

    } catch (Exception e) {
        e.printStackTrace();
    }
}