Example usage for javax.swing.table DefaultTableModel DefaultTableModel

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

Introduction

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

Prototype

public DefaultTableModel(Object[][] data, Object[] columnNames) 

Source Link

Document

Constructs a DefaultTableModel and initializes the table by passing data and columnNames to the setDataVector method.

Usage

From source file:GUI.Starts.java

/**
 * Creates new form Starts//from   w w w .ja v a2s .  c o m
 */
public Starts() throws FileNotFoundException, IOException {
    CSVReader reader = new CSVReader(new FileReader("data_astra.csv"));
    List myEntries = reader.readAll();
    String[] columnnames = (String[]) myEntries.get(0);
    tableModel = new DefaultTableModel(columnnames, myEntries.size() - 1);
    int rowcount = tableModel.getRowCount();
    for (int x = 0; x < rowcount + 1; x++) {
        int columnnumber = 0;
        // if x = 0 this is the first row...skip it... data used for columnnames
        if (x > 0) {
            for (String thiscellvalue : (String[]) myEntries.get(x)) {
                tableModel.setValueAt(thiscellvalue, x - 1, columnnumber);
                columnnumber++;
            }
        }

    }
    initComponents();
    predict();
    initGraphs();
    this.setLocationRelativeTo(null);
    //        CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 
    //        myEntries = reader.readAll();

}

From source file:lectorarchivos.VerCSV.java

public static void llenarTabla(JTable tabla, File fichero) throws FileNotFoundException, IOException {
    //Almacenamos la direccion donde se encuenta el fichero en un String
    String rutaFichero = fichero.getAbsolutePath().toString();
    BufferedReader br = null;/*from w  ww  . j a v  a 2  s  .c  om*/
    String line = "";
    //Asignar un separador
    char csvSplitBy = ';';
    char quote = '"';
    CSVReader reader = null;

    //Realizar lectura del fichero para coger los titulos
    String titulos[] = new String[5];

    titulos[0] = "Fecha";
    titulos[1] = "Hora";
    titulos[2] = "Nmero de serie";
    titulos[3] = "Lectura";
    titulos[4] = "Consumo";

    //Array de filas
    String col[] = new String[5];

    //Creacion del modelo
    model = new DefaultTableModel(null, titulos);

    //Recoger fecha del item actual en string
    String fechaActual = null;
    //Recoger la fecha anterior en un string
    String fechaAnterior = null;

    //Recoger las lecturas
    String lecturaActual = null;
    String lecturaAnterior = null;

    //Consumo
    double consumo = 0;

    //Lectura del fichero
    try {
        reader = new CSVReader(new FileReader(rutaFichero), csvSplitBy, quote);
        String[] nextLine = null;

        while ((nextLine = reader.readNext()) != null) {
            //System.out.println(Arrays.toString(nextLine));
            //Asignar a cada fila el valor
            col[0] = nextLine[0];//Lnea de la fecha Actual
            col[1] = nextLine[1];
            col[2] = nextLine[2];//Nmero de serire

            col[3] = nextLine[12];//Lectura
            col[4] = nextLine[11];//Consumo

            if (fechaActual == null && lecturaActual == null) {
                //Aqu se asigna la fecha actual;
                fechaActual = col[0];
                //Aqu se le asigna la lectura actual
                //lecturaActual = col[3];
            } else {
                //Se le asigna la fecha a fechaAnterior
                fechaAnterior = col[0];
                //Aqu se le asigna la lectura anterior
                //lecturaAnterior = col[3];

                //Comprobar fechActual con anterior
                if (fechaActual.compareTo(fechaAnterior) == 1) {
                    //La fecha sera menor
                } else if (fechaActual.compareTo(fechaAnterior) == -1) {
                    //Es que la fecha es mayor
                } else {
                    //La fecha es menor
                }

                //Mostrar fecha actual y menor
                System.out.println("Fecha actual --> " + fechaActual);
                System.out.println("Fecha anterior --> " + fechaAnterior);
                System.out.println("----------------------------------------");

                //Antes de vaciar nada sacamos el consumo de cada cosa
                //consumo = Double.parseDouble(lecturaActual)-Double.parseDouble(lecturaAnterior);

                //Ahora asignamos el consumo a la col[4];
                //col[4] = String.valueOf(consumo);

                //Vaciamos las acturales fecha y lectura
                fechaActual = null;

            }

            //Aadimos la columna al modelo
            model.addRow(col);
        }

        ArrayList<Double> consumoRecogido = new ArrayList<Double>();

        //Recorrer el modelo
        for (int i = 0; i < model.getRowCount(); i++) {
            codigoContadores.add(model.getValueAt(i, 2).toString());

            if (lecturaActual == null) {
                lecturaActual = model.getValueAt(i, 3).toString();
                System.out.println("Lectura actual --> " + lecturaActual);
            } else {
                lecturaAnterior = model.getValueAt(i, 3).toString();
                System.out.println("Lectura anterior --> " + lecturaAnterior);

                //Lectura anterior - actual = consumo
                consumo = Double.parseDouble(lecturaActual) - Double.parseDouble(lecturaAnterior);
                System.out.println("Consumo = " + consumo);

                //Insertamos el consumo dentro de un arraylist
                consumoRecogido.add(consumo);

                //model.setValueAt(consumo, i, 4);

                System.out.println("---------------------------------------------------");

                lecturaActual = lecturaAnterior;
            }
        }
        consumoRecogido.add(0.0);

        System.out.println(consumoRecogido.toString());
        System.out.println(model.getRowCount());

        //Ahora vamos metiendo el consumo recogido dentro del modelo
        for (int i = 0; i < consumoRecogido.size(); i++) {
            model.setValueAt(consumoRecogido.get(i).toString(), i, 4);
        }

        //Recorrer array de codigoContadores
        System.out.println("Tamao de la lista de numContadores: " + codigoContadores.size());
        System.out.println("Datos del array: " + codigoContadores.toString());

        //Leer el XML para mostrar el nombre del contador
        leerXML();

        //Editar el modelo de la tabla
        tabla.setModel(model);

        //Llamamos al mtodo para mostrar la grfica
        mostrarGrafica(jTableInfoCSV);

    } catch (Exception e) {

    } finally {
        if (null != reader) {
            reader.close();
        }
    }
}

From source file:frames.consulta.java

void cargartablapacientes(String valor) {
    String[] titulos = { "Cedula", "Nombre", "Apellido", "Edad", "Direccion" };
    String[] registro = new String[5];
    modelo = new DefaultTableModel(null, titulos);

    String sSQL = "";
    if (valor.equals("")) {
        sSQL = "SELECT * FROM pacientes";
    } else {//from w w w.j  a v  a 2  s  .  c om
        sSQL = "SELECT * FROM pacientes WHERE " + atributo + " LIKE '%" + valor + "%'";

    }

    try {
        Statement st = cn.createStatement();
        ResultSet rs = st.executeQuery(sSQL);

        while (rs.next()) {

            registro[0] = rs.getString("cedula");
            registro[1] = rs.getString("nombre");
            registro[2] = rs.getString("apellido");
            registro[3] = rs.getString("edad");
            registro[4] = rs.getString("direccion");
            modelo.addRow(registro);
        }

        tblconsulta.setModel(modelo);
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }

}

From source file:FillViewportHeightDemo.java

private static DefaultTableModel getDefaultTableModel() {
    String[] cols = { "Foo", "Toto", "Kala", "Pippo", "Boing" };
    return new DefaultTableModel(null, cols);
}

From source file:com.jtk.pengelolaanujian.controller.panitiaController.PrintSoalController.java

public List<StorageSoal> searchSoalStorage(String kodeSoal, JTable jTable) {
    StorageSoalFacade storageSoalFacade = new StorageSoalFacade();
    StafFacade stafFacade = new StafFacade();
    List<StorageSoal> storageSoals = storageSoalFacade.findByKodeSoal(kodeSoal);
    Object[] columnsName = { "Nama File", "Tanggal Upload", "Uploader" };

    DefaultTableModel dtm = new DefaultTableModel(null, columnsName) {
        @Override// w ww.  ja v  a 2  s  . co  m
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    for (StorageSoal soal : storageSoals) {
        Object[] o = new Object[4];
        o[0] = soal.getNamaFile();
        o[1] = sdf.format(soal.getStsoalTglUpload());
        o[2] = stafFacade.findByStafNip(soal.getStafNip()).getStafNama();

        dtm.addRow(o);
    }
    jTable.setModel(dtm);

    return storageSoals;
}

From source file:TableRowColumnTest.java

public PlanetTableFrame() {
    setTitle("TableRowColumnTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    TableModel model = new DefaultTableModel(cells, columnNames) {
        public Class<?> getColumnClass(int c) {
            return cells[0][c].getClass();
        }/*from w ww  .j a v  a  2  s . c  o m*/
    };

    table = new JTable(model);

    table.setRowHeight(100);
    table.getColumnModel().getColumn(COLOR_COLUMN).setMinWidth(250);
    table.getColumnModel().getColumn(IMAGE_COLUMN).setMinWidth(100);

    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    sorter.setComparator(COLOR_COLUMN, new Comparator<Color>() {
        public int compare(Color c1, Color c2) {
            int d = c1.getBlue() - c2.getBlue();
            if (d != 0)
                return d;
            d = c1.getGreen() - c2.getGreen();
            if (d != 0)
                return d;
            return c1.getRed() - c2.getRed();
        }
    });
    sorter.setSortable(IMAGE_COLUMN, false);
    add(new JScrollPane(table), BorderLayout.CENTER);

    removedRowIndices = new HashSet<Integer>();
    removedColumns = new ArrayList<TableColumn>();

    final RowFilter<TableModel, Integer> filter = new RowFilter<TableModel, Integer>() {
        public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
            return !removedRowIndices.contains(entry.getIdentifier());
        }
    };

    // create menu

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu selectionMenu = new JMenu("Selection");
    menuBar.add(selectionMenu);

    rowsItem = new JCheckBoxMenuItem("Rows");
    columnsItem = new JCheckBoxMenuItem("Columns");
    cellsItem = new JCheckBoxMenuItem("Cells");

    rowsItem.setSelected(table.getRowSelectionAllowed());
    columnsItem.setSelected(table.getColumnSelectionAllowed());
    cellsItem.setSelected(table.getCellSelectionEnabled());

    rowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setRowSelectionAllowed(rowsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(rowsItem);

    columnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setColumnSelectionAllowed(columnsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(columnsItem);

    cellsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setCellSelectionEnabled(cellsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(cellsItem);

    JMenu tableMenu = new JMenu("Edit");
    menuBar.add(tableMenu);

    JMenuItem hideColumnsItem = new JMenuItem("Hide Columns");
    hideColumnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedColumns();
            TableColumnModel columnModel = table.getColumnModel();

            // remove columns from view, starting at the last
            // index so that column numbers aren't affected

            for (int i = selected.length - 1; i >= 0; i--) {
                TableColumn column = columnModel.getColumn(selected[i]);
                table.removeColumn(column);

                // store removed columns for "show columns" command

                removedColumns.add(column);
            }
        }
    });
    tableMenu.add(hideColumnsItem);

    JMenuItem showColumnsItem = new JMenuItem("Show Columns");
    showColumnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // restore all removed columns
            for (TableColumn tc : removedColumns)
                table.addColumn(tc);
            removedColumns.clear();
        }
    });
    tableMenu.add(showColumnsItem);

    JMenuItem hideRowsItem = new JMenuItem("Hide Rows");
    hideRowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedRows();
            for (int i : selected)
                removedRowIndices.add(table.convertRowIndexToModel(i));
            sorter.setRowFilter(filter);
        }
    });
    tableMenu.add(hideRowsItem);

    JMenuItem showRowsItem = new JMenuItem("Show Rows");
    showRowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            removedRowIndices.clear();
            sorter.setRowFilter(filter);
        }
    });
    tableMenu.add(showRowsItem);

    JMenuItem printSelectionItem = new JMenuItem("Print Selection");
    printSelectionItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedRows();
            System.out.println("Selected rows: " + Arrays.toString(selected));
            selected = table.getSelectedColumns();
            System.out.println("Selected columns: " + Arrays.toString(selected));
        }
    });
    tableMenu.add(printSelectionItem);
}

From source file:org.jfree.chart.demo.selection.SelectionDemo8.java

/**
 * A demonstration application showing how to create a simple time series
 * chart. This example uses monthly data.
 *
 * @param title  the frame title.//from   w  ww . ja  v  a2  s. co  m
 */
public SelectionDemo8(String title) {
    super(title);
    ChartPanel chartPanel = (ChartPanel) createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    chartPanel.setRangeZoomable(false);

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    this.dataset = (TimeSeriesCollection) plot.getDataset();
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);

    this.model = new DefaultTableModel(new String[] { "Series:", "Item:", "Period:", "Value:" }, 0);
    this.table = new JTable(this.model);
    TableColumnModel tcm = this.table.getColumnModel();
    tcm.getColumn(3).setCellRenderer(new NumberCellRenderer());
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);

}

From source file:view.ViewReportUI.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.//from   w ww  .  j  av a 2  s .  c  o m
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jPanel1 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle(" Expense Report");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent evt) {
            formWindowClosing(evt);
        }
    });

    String col[] = { "Amount", "Store", "Date of Purchase", "Date Addded" };
    DefaultTableModel tableModel = new DefaultTableModel(col, 0) {
        public boolean isCellEditable(int row, int column) {
            return false;//This causes all cells to be not editable
        }
    };
    jTable1.setModel(tableModel);
    for (model.InvoiceModel in : myInvoice) {

        Object[] objs = { "$" + in.getAmount(), in.getStore(), in.getDateOfPurchase(), in.getAddedDate() };
        tableModel.addRow(objs);
    }

    jTable1.setGridColor(Color.gray);
    jTable1.getTableHeader().setBackground(new Color(102, 178, 255));
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTable1MouseClicked(evt);
        }
    });
    jScrollPane1.setViewportView(jTable1);

    jButton1.setText("Close");

    jPanel1.setLayout(new java.awt.BorderLayout());
    PieDataset dataset = createDataset();
    // based on the dataset we create the chart
    JFreeChart chart = createChart(dataset, "Hello");
    // we put the chart into a panel
    this.chartPanel = new ChartPanel(chart);
    // default size
    chartPanel.setPreferredSize(new Dimension(500, 270));
    //        this.jPanel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //
    System.out.println(chartPanel == null);
    jPanel1.add(chartPanel);
    jPanel1.validate();

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                    layout.createSequentialGroup()
                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1).addGap(242, 242, 242))
            .addGroup(layout.createSequentialGroup().addGap(15, 15, 15)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 536,
                                    Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap(14, Short.MAX_VALUE)));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 293,
                            javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
                            javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jButton1)
                    .addGap(20, 20, 20)));

    pack();
    setLocationRelativeTo(null);
}

From source file:org.jfree.chart.demo.selection.SelectionDemo5Category.java

public SelectionDemo5Category(String title) {
    super(title);
    JPanel chartPanel = createDemoPanel();
    chartPanel.setPreferredSize(new Dimension(500, 270));

    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);/*from   w  w w. j  a  v  a 2 s. c  o m*/

    this.model = new DefaultTableModel(new String[] { "row:", "column:", "value:" }, 0);
    this.table = new JTable(this.model);
    TableColumnModel tcm = this.table.getColumnModel();
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);
}

From source file:org.jfree.chart.demo.selection.SelectionDemo4.java

/**
 * Creates a new demo.//w ww. j  a v  a  2  s. co m
 * 
 * @param title  the frame title.
 */
public SelectionDemo4(String title) {
    super(title);
    ChartPanel chartPanel = (ChartPanel) createDemoPanel();
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

    JFreeChart chart = chartPanel.getChart();
    XYPlot plot = (XYPlot) chart.getPlot();
    this.dataset = (HistogramDataset) plot.getDataset();
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    split.add(chartPanel);

    this.model = new DefaultTableModel(new String[] { "Item:", "Bin Start:", "Bin End:", "Value:" }, 0);
    this.table = new JTable(this.model);
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroller = new JScrollPane(this.table);
    p.add(scroller);
    p.setBorder(BorderFactory.createCompoundBorder(new TitledBorder("Selected Items: "),
            new EmptyBorder(4, 4, 4, 4)));
    split.add(p);
    setContentPane(split);
}