Example usage for javax.swing JTable setModel

List of usage examples for javax.swing JTable setModel

Introduction

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

Prototype

@BeanProperty(description = "The model that is the source of the data for this view.")
public void setModel(final TableModel dataModel) 

Source Link

Document

Sets the data model for this table to dataModel and registers with it for listener notifications from the new data model.

Usage

From source file:de.codesourcery.eve.skills.ui.components.impl.AssetListComponent.java

@Override
protected JPanel createPanel() {

    // Merge controls.
    final JPanel mergeControlsPanel = new JPanel();
    mergeControlsPanel.setLayout(new GridBagLayout());
    mergeControlsPanel.setBorder(BorderFactory.createTitledBorder("Merging"));

    int y = 0;//from www . j av a 2s. co m

    // merge by type
    mergeAssetsByType.setSelected(true);
    mergeAssetsByType.addActionListener(actionListener);

    mergeControlsPanel.add(mergeAssetsByType, constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(new JLabel("Merge assets by type", SwingConstants.LEFT),
            constraints(1, y++).width(2).end());

    // "ignore different packaging"
    ignorePackaging.setSelected(true);
    ignorePackaging.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignorePackaging, constraints(1, y).anchorWest().end());
    final JLabel label1 = new JLabel("Merge different packaging", SwingConstants.RIGHT);
    mergeControlsPanel.add(label1, constraints(2, y++).end());

    // "ignore different locations"
    ignoreLocations.setSelected(true);
    ignoreLocations.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignoreLocations, constraints(1, y).anchorWest().end());
    final JLabel label2 = new JLabel("Merge different locations", SwingConstants.RIGHT);
    mergeControlsPanel.add(label2, constraints(2, y++).end());

    linkComponentEnabledStates(mergeAssetsByType, ignoreLocations, ignorePackaging, label1, label2);

    /*
     * Filter controls.
     */

    final JPanel filterControlsPanel = new JPanel();
    filterControlsPanel.setLayout(new GridBagLayout());
    filterControlsPanel.setBorder(BorderFactory.createTitledBorder("Filters"));

    y = 0;
    // filter by location combo box
    filterByLocation.addActionListener(actionListener);
    locationComboBox.addActionListener(actionListener);

    filterByLocation.setSelected(false);
    linkComponentEnabledStates(filterByLocation, locationComboBox);

    locationComboBox.setRenderer(new LocationRenderer());
    locationComboBox.setPreferredSize(new Dimension(150, 20));
    locationComboBox.setModel(locationModel);

    filterControlsPanel.add(filterByLocation, constraints(0, y).end());
    filterControlsPanel.add(locationComboBox, constraints(1, y++).end());

    // filter by type combo box
    filterByType.addActionListener(actionListener);
    typeComboBox.addActionListener(actionListener);

    filterByType.setSelected(false);

    linkComponentEnabledStates(filterByType, typeComboBox);

    typeComboBox.setPreferredSize(new Dimension(150, 20));
    typeComboBox.setModel(typeModel);

    filterControlsPanel.add(filterByType, constraints(0, y).end());
    filterControlsPanel.add(typeComboBox, constraints(1, y++).end());

    // filter by item category combobox
    filterByCategory.addActionListener(actionListener);
    categoryComboBox.addActionListener(actionListener);
    categoryComboBox.setRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {

            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            setText(getDisplayName((InventoryCategory) value));
            setEnabled(categoryComboBox.isEnabled());
            return this;
        }
    });

    filterByCategory.setSelected(false);
    linkComponentEnabledStates(filterByCategory, categoryComboBox);

    categoryComboBox.setPreferredSize(new Dimension(150, 20));
    categoryComboBox.setModel(categoryModel);

    filterControlsPanel.add(filterByCategory, constraints(0, y).end());
    filterControlsPanel.add(categoryComboBox, constraints(1, y++).end());

    // filter by item group combobox
    filterByGroup.addActionListener(actionListener);
    groupComboBox.addActionListener(actionListener);

    filterByGroup.setSelected(false);

    linkComponentEnabledStates(filterByGroup, groupComboBox);

    groupComboBox.setPreferredSize(new Dimension(150, 20));
    groupComboBox.setModel(groupModel);

    filterControlsPanel.add(filterByGroup, constraints(0, y).end());
    filterControlsPanel.add(groupComboBox, constraints(1, y++).end());

    /*
     * Table panel.
     */

    table = new JTable() {

        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {

            // subclassing hack is needed because table
            // returns different renderes depending on column type
            final TableCellRenderer result = super.getCellRenderer(row, column);

            return new TableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {

                    final Component comp = result.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);

                    final int modelRow = table.convertRowIndexToModel(row);
                    final Asset asset = model.getRow(modelRow);

                    final StringBuilder label = new StringBuilder("<HTML><BODY>");
                    label.append(asset.getItemId() + " - flags: " + asset.getFlags() + "<BR>");
                    if (asset.hasMultipleLocations()) {
                        label.append("<BR>");
                        for (ILocation loc : asset.getLocations()) {
                            label.append(loc.getDisplayName()).append("<BR>");
                        }
                    }

                    label.append("</BODY></HTML>");
                    ((JComponent) comp).setToolTipText(label.toString());

                    return comp;
                }
            };
        }
    };

    model.setViewFilter(this.viewFilter);

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateSelectedVolume();
        }
    });

    FixedBooleanTableCellRenderer.attach(table);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setModel(model);
    table.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    table.setRowSorter(model.getRowSorter());

    popupMenuBuilder.addItem("Refine...", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final ICharacter c = selectionProvider.getSelectedItem();
            final RefiningComponent comp = new RefiningComponent(c);
            comp.setItemsToRefine(assets);
            ComponentWrapper.wrapComponent("Refining", comp).setVisible(true);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (text)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            new PlainTextTransferable(toPlainText(assets)).putOnClipboard();
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (CSV)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

            clipboard.setContents(new PlainTextTransferable(toCsv(assets)), null);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.popupMenuBuilder.attach(table);

    final JScrollPane scrollPane = new JScrollPane(table);

    /*
     * Name filter
     */

    final JPanel nameFilterPanel = new JPanel();
    nameFilterPanel.setLayout(new GridBagLayout());
    nameFilterPanel.setBorder(BorderFactory.createTitledBorder("Filter by name"));
    nameFilterPanel.setPreferredSize(new Dimension(150, 70));
    nameFilter.setColumns(10);
    nameFilter.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }
    });

    nameFilterPanel.add(nameFilter, constraints(0, 0).resizeHorizontally().end());
    final JButton clearButton = new JButton("Clear");
    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameFilter.setText(null);
        }
    });
    nameFilterPanel.add(clearButton, constraints(1, 0).noResizing().end());

    // Selected volume
    final JPanel selectedVolumePanel = this.selectedVolume.getPanel();

    // add control panels to result panel
    final JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridBagLayout());

    topPanel.add(mergeControlsPanel, constraints(0, 0).height(2).weightX(0).anchorWest().end());
    topPanel.add(filterControlsPanel, constraints(1, 0).height(2).anchorWest().weightX(0).end());
    topPanel.add(nameFilterPanel, constraints(2, 0).height(1).anchorWest().useRemainingWidth().end());
    topPanel.add(selectedVolumePanel, constraints(2, 1).height(1).anchorWest().useRemainingWidth().end());

    final JSplitPane splitPane = new ImprovedSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, scrollPane);

    splitPane.setDividerLocation(0.3d);

    final JPanel content = new JPanel();
    content.setLayout(new GridBagLayout());
    content.add(splitPane, constraints().resizeBoth().useRemainingSpace().end());

    return content;
}

From source file:com.vgi.mafscaling.ClosedLoop.java

private JTable createAfrDataTable(JPanel panel, String tableName, int gridy) {
    final JTable afrTable = new JTable() {
        private static final long serialVersionUID = 6526901361175099297L;

        public boolean isCellEditable(int row, int column) {
            return false;
        };/*from   w w w.  jav  a 2s . c om*/
    };
    DefaultTableColumnModel afrModel = new DefaultTableColumnModel();
    final TableColumn afrColumn = new TableColumn(0, 250);
    afrColumn.setHeaderValue(tableName);
    afrModel.addColumn(afrColumn);
    JTableHeader lblAfrTableName = afrTable.getTableHeader();
    lblAfrTableName.setColumnModel(afrModel);
    lblAfrTableName.setReorderingAllowed(false);
    DefaultTableCellRenderer headerRenderer = (DefaultTableCellRenderer) lblAfrTableName.getDefaultRenderer();
    headerRenderer.setHorizontalAlignment(SwingConstants.LEFT);

    GridBagConstraints gbc_lblAfrTableName = new GridBagConstraints();
    gbc_lblAfrTableName.insets = new Insets((gridy == 0 ? 0 : 5), 0, 0, 0);
    gbc_lblAfrTableName.anchor = GridBagConstraints.PAGE_START;
    gbc_lblAfrTableName.fill = GridBagConstraints.HORIZONTAL;
    gbc_lblAfrTableName.gridx = 0;
    gbc_lblAfrTableName.gridy = gridy;
    panel.add(lblAfrTableName, gbc_lblAfrTableName);

    afrTable.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            afrColumn.setWidth(afrTable.getWidth());
        }
    });
    afrTable.getTableHeader().setReorderingAllowed(false);
    afrTable.setColumnSelectionAllowed(true);
    afrTable.setCellSelectionEnabled(true);
    afrTable.setBorder(new LineBorder(new Color(0, 0, 0)));
    afrTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    afrTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    afrTable.setModel(new DefaultTableModel(AfrTableRowCount, AfrTableColumnCount));
    Utils.initializeTable(afrTable, ColumnWidth);

    if (tableName.equals(Afr1TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    } else if (tableName.equals(Afr2TableName)) {
        Format[][] formatMatrix = { { new DecimalFormat("#"), new DecimalFormat("0.00") },
                { new DecimalFormat("#"), new DecimalFormat("#") } };
        NumberFormatRenderer renderer = (NumberFormatRenderer) afrTable.getDefaultRenderer(Object.class);
        renderer.setFormats(formatMatrix);
    }

    GridBagConstraints gbc_afrTable = new GridBagConstraints();
    gbc_afrTable.insets = new Insets(0, 0, 0, 0);
    gbc_afrTable.anchor = GridBagConstraints.PAGE_START;
    gbc_afrTable.gridx = 0;
    gbc_afrTable.gridy = gridy + 1;
    panel.add(afrTable, gbc_afrTable);

    excelAdapter.addTable(afrTable, true, false);

    return afrTable;
}

From source file:com.smanempat.controller.ControllerEvaluation.java

public void showDataSetModel(JTable tableDataSetModel, JTable tableTahunModel, JLabel totalDataModel)
        throws SQLException {
    int row;/*from w ww.  j  a  v a 2s  .  c  o  m*/
    int transMinat;
    tableModelDataSet1 = (DefaultTableModel) tableDataSetModel.getModel();
    row = tableModelDataSet1.getRowCount();
    for (int i = 0; i < row; i++) {
        tableModelDataSet1.removeRow(0);
    }
    row = tableTahunModel.getRowCount();
    boolean checkList;
    for (int i = 0; i < row; i++) {
        checkList = Boolean.valueOf("" + tableTahunModel.getValueAt(i, 1));
        if (checkList == true) {
            dbConnection = new DbConnection();
            connect = dbConnection.connect();
            query = "SELECT * FROM siswa WHERE tahun_ajaran = ?";
            pstmt = connect.prepareStatement(query);
            pstmt.setString(1, tableTahunModel.getValueAt(i, 0).toString());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                String nis = rs.getString("nis");
                String nama = rs.getString("nama");
                String jenisKelamin = rs.getString("jenis_kelamin");
                String nilaiUN = rs.getString("nilai_un");
                double meanUN = Double.parseDouble(nilaiUN) / 4;
                String ptBindo = rs.getString("pt_bhs_indonesia");
                String ptMtk = rs.getString("pt_matematika");
                String ptBing = rs.getString("pt_bhs_inggris");
                String ptIpa = rs.getString("pt_ipa");
                double meanPt = (Double.parseDouble(ptBindo) + Double.parseDouble(ptMtk)
                        + Double.parseDouble(ptBing) + Double.parseDouble(ptIpa)) / 4;
                String minat = rs.getString("minat");
                if (minat.equals("IPA")) {
                    transMinat = 1;
                } else {
                    transMinat = 0;
                }
                String jurusan = rs.getString("jurusan");
                Object tableContent[] = { nis, nilaiUN, meanUN, ptBindo, ptMtk, ptBing, ptIpa, meanPt, minat,
                        transMinat, jurusan };
                tableModelDataSet1.addRow(tableContent);
            }
        }
        tableDataSetModel.setModel(tableModelDataSet1);
        totalDataModel.setText(tableDataSetModel.getRowCount() + " Data");
    }
}

From source file:com.smanempat.controller.ControllerEvaluation.java

public void showDataSetTest(JTable tableDataSetTesting, JTable tableTahunTesting, JLabel labelTotalDataModel)
        throws SQLException {
    int row;/*from ww  w  . ja va  2  s .co m*/
    int transMinat;
    //modelEvaluation = new ModelEvaluation();
    tableModelDataSet2 = (DefaultTableModel) tableDataSetTesting.getModel();
    //tempArray = new ArrayList<String>();
    row = tableModelDataSet2.getRowCount();
    for (int i = 0; i < row; i++) {
        tableModelDataSet2.removeRow(0);
    }
    row = tableTahunTesting.getRowCount();
    boolean checkList;
    for (int i = 0; i < row; i++) {
        checkList = Boolean.valueOf("" + tableTahunTesting.getValueAt(i, 1));
        if (checkList == true) {
            dbConnection = new DbConnection();
            connect = dbConnection.connect();
            query = "SELECT * FROM siswa WHERE tahun_ajaran = ?";
            pstmt = connect.prepareStatement(query);
            pstmt.setString(1, tableTahunTesting.getValueAt(i, 0).toString());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                String nis = rs.getString("nis");
                String nama = rs.getString("nama");
                String jenisKelamin = rs.getString("jenis_kelamin");
                String nilaiUN = rs.getString("nilai_un");
                double meanUN = Double.parseDouble(nilaiUN) / 4;
                String ptBindo = rs.getString("pt_bhs_indonesia");
                String ptMtk = rs.getString("pt_matematika");
                String ptBing = rs.getString("pt_bhs_inggris");
                String ptIpa = rs.getString("pt_ipa");
                double meanPt = (Double.parseDouble(ptBindo) + Double.parseDouble(ptMtk)
                        + Double.parseDouble(ptBing) + Double.parseDouble(ptIpa)) / 4;
                String minat = rs.getString("minat");
                if (minat.equals("IPA")) {
                    transMinat = 1;
                } else {
                    transMinat = 0;
                }
                jurusan = rs.getString("jurusan");
                Object tableContent[] = { nis, nilaiUN, meanUN, ptBindo, ptMtk, ptBing, ptIpa, meanPt, minat,
                        transMinat };

                tableModelDataSet2.addRow(tableContent);
            }
        }
        tableDataSetTesting.setModel(tableModelDataSet2);
        labelTotalDataModel.setText(tableDataSetTesting.getRowCount() + " Data");
    }
}

From source file:com.SE.myPlayer.MusicPlayerGUI.java

public void tableReferesh(JTable songData_Table, String tableName, String columName) {
        int emptyResultSet = 0;

        try {//from ww w  .  jav a  2 s . co  m
            con = db.getCon();
            stmt = con.createStatement();
            ResultSet rs;

            switch (tableName) {
            case "library":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            case "playlist":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            default:
                rs = stmt.executeQuery(
                        "Select library.id_songs, library.song_location, library.song_name, library.song_album, library.song_artist, library.genre, library.year, library.time, library.comment from playlist INNER JOIN library ON library.id_songs = playlist.id_songs AND playlist.playlist_name = '"
                                + tableName + "' order by " + columName + "");
                break;
            }

            DefaultTableModel myModel = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };

            String[] songsColumnsName = { "Location", "Name", "Album", "Artist", "Genre", "Year", "Time",
                    "Comment" };
            myModel.setColumnIdentifiers(songsColumnsName);

            ResultSetMetaData rsmd = rs.getMetaData();
            int colNumbers = rsmd.getColumnCount();

            Object[] objects = new Object[colNumbers];

            while (rs.next()) {
                emptyResultSet = 1;
                for (int i = 0; i < colNumbers - 1; i++) {
                    objects[i] = rs.getObject(i + 2);
                }
                myModel.addRow(objects);
            }

            if (emptyResultSet == 0) {
                myModel.addRow(objects);
            }

            songData_Table.setModel(myModel);

            rs = stmt.executeQuery("select col_name from col_name where col_status = 0");

            while (rs.next()) {
                songData_Table.removeColumn(songData_Table.getColumn(rs.getString(1)));
            }

            songData_Table.getTableHeader().removeMouseListener(ma);
            songData_Table.getTableHeader().addMouseListener(ma);
            songData_Table.setDragEnabled(true);
            songData_Table.setDropTarget(new DropTarget() {
                @Override
                public synchronized void drop(DropTargetDropEvent dtde) {

                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    Transferable t = dtde.getTransferable();

                    try {
                        if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.javaFileListFlavor);
                            String files = fileList.toString();
                            finalString = convertFileString(files);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.stringFlavor);
                            String fileListString = fileList.toString();

                            fileListString = Arrays.toString(fileListString.split("\\n"));

                            String[] splitLocations = fileListString.split(",\\s");

                            for (int i = 0; i < splitLocations.length; i++) {
                                if (i == 0) {
                                    splitLocations[i] = splitLocations[i].substring(1,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                } else {
                                    splitLocations[i] = splitLocations[i].substring(0,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                }
                            }

                            for (int i = 0; i < splitLocations.length; i++) {
                                splitLocations[i] = sd.getLocations(splitLocations[i]);
                            }
                            finalString = Arrays.asList(splitLocations);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        }
                    } catch (UnsupportedFlavorException | IOException | InvalidDataException
                            | UnsupportedTagException ex) {
                        System.out.println("Error in second drop flavour............" + ex);
                    }
                }
            });

            if (con != null) {
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            System.out.println("Error in Stmt " + e);
        }
    }

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

/**
 * Parses the given import file according to the users selection and creates/updates the Preview table,
 * showing the user how the import options effect the way the data will be imported into the spreadsheet.
 * @param table - the table to display the data
 * @return//from ww  w .j  a v  a  2s.co  m
 * JTable - the table to display the data
 */
private JTable setCSVTableData(final JTable table) {
    try {
        log.debug("setTableData - file - " + configCSV.getFile().toString());
        CsvReader csv = new CsvReader(new FileInputStream(configCSV.getFile()), configCSV.getDelimiter(),
                configCSV.getCharset());
        csv.setEscapeMode(configCSV.getEscapeMode());
        csv.setTextQualifier(configCSV.getTextQualifier());

        String[] headers = {};
        Vector<String[]> tableDataVector = new Vector<String[]>();

        highestColumnCount = getLargestColumnCountFromCSV();

        if (configCSV.getFirstRowHasHeaders()) {
            csv.readHeaders();
            headers = csv.getHeaders();
        }

        int rowColumnCount = 0;
        while (csv.readRecord()) {
            //how many columns does this row of data contain
            rowColumnCount = csv.getColumnCount();
            //create an array that contains teh row data
            String[] rowData = new String[csv.getColumnCount()];
            for (int col = 0; col < csv.getColumnCount(); col++) {
                rowData[col] = csv.get(col);
            }
            //if the column count in this row of data is not as large
            //as the column header count, then "insert" blank string into the cells
            String[] newArray = padArray(highestColumnCount, rowData, false);
            //stick the row data into a vector because we do not know how many
            //rows of data there are
            tableDataVector.add(newArray);
        }

        if (!configCSV.getFirstRowHasHeaders() || headers == null) {
            //create headers with names Column1, Column2...
            headers = createDummyHeaders(rowColumnCount);
        }

        //if the header count is not as large as the longest column count in the data set
        //create dummy headers and append to end of table.
        headers = padArray(highestColumnCount, headers, true);

        log.debug("---------------------------------------------------");
        printArray(headers);
        log.debug("---------------------------------------------------");

        //pull row data out of vector and stick into an array for table model.
        String[][] tableData = new String[tableDataVector.size()][rowColumnCount];
        for (int i = 0; i < tableData.length; i++) {
            tableData[i] = tableDataVector.elementAt(i);
            printArray(tableData[i]);
        }

        if (checkForErrors(headers, tableData)) {
            errorPanel.showDataImportStatusPanel(true);
        } else {
            errorPanel.showDataImportStatusPanel(false);
        }

        if ((doesFirstRowHaveHeaders ? tableDataVector.size() - 1
                : tableDataVector.size()) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        model = new PreviewTableModel(headers, tableData);
        table.setModel(model);
        table.setColumnSelectionAllowed(false);
        table.setRowSelectionAllowed(false);
        table.setCellSelectionEnabled(false);
        table.getTableHeader().setReorderingAllowed(false);
        table.setPreferredScrollableViewportSize(new Dimension(500, 100));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));

        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return table;

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataImportDialog.class, ex);
        log.error("Error attempting to parse input csv file:" + ex);
    }
    return null;
}

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;//  ww  w  . j  a v a  2s  .  com
    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:interfaces.InterfazPrincipal.java

private void BotonBuscarClienteSaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonBuscarClienteSaldoActionPerformed
    String nombreCliente = nombreClienteBusquedaSaldo.getText();
    //08-11-2014 listar clientes por nombre
    ControladorCliente controladorCliente = new ControladorCliente();
    ArrayList<Cliente> listaClientes = new ArrayList<>();

    if (nombreCliente.equals("")) {
        listaClientes = controladorCliente.obtenerClientes();
    } else {//w w w.  ja  v a 2 s .c o m
        listaClientes = controladorCliente.obtenerClientes(nombreCliente, 0);
    }

    //08-11-2014 Crear dialogo de bsqueda
    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(300, 300);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    ;

    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaClientes.size(); i++) {
        Object[] data = { "1", "2" };
        data[0] = listaClientes.get(i).getCliente_id();
        data[1] = listaClientes.get(i).getNombre();
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("Identificacin").setMinWidth(110);
    tablaDialogo.getColumn("Nombre").setMinWidth(110);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                mostrarIdentificacionCliente.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 1));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoPersonaSaldo.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacionCliente)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);

                    TablaDeSaldoClientes.setModel(modeloClientes);
                    NumberFormat formatter = new DecimalFormat("#0");

                    String valorMovimiento = String.valueOf(formatter.format(Double.parseDouble(datos[4])));
                    Object[] rowData = { datos[1], datos[2], datos[3], valorMovimiento };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoClientes.setModel(modeloClientes);
                NumberFormat formatter = new DecimalFormat("#0");
                textoTotalDebe.setText(String.valueOf(formatter.format(pago)));
                dialogoEditar.dispose();

                //Mostrar en table de clientes los datos
                botonRegistrarAbono.setEnabled(true);
            }

        }
    });
}

From source file:interfaces.InterfazPrincipal.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String nombreCliente = nombreClienteReporteCliente.getText();
    String identificacion = identificacionClienteCliente.getText();
    try {//from w  ww  .  ja  v  a2 s .c om
        //08-11-2014 listar clientes por nombre
        ControladorCliente controladorCliente = new ControladorCliente();
        ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();

        if (nombreCliente.equals("") && identificacion.equals("")) {
            listaClientes = controladorCliente.obtenerClientes();
        } else {
            int identificacionNumerico = 0;
            if (!identificacion.equals("")) {
                identificacionNumerico = Integer.parseInt(identificacion);
            }
            listaClientes = controladorCliente.obtenerClientes(nombreCliente, identificacionNumerico);
        }

        //08-11-2014 Crear dialogo de bsqueda
        final JDialog dialogoEditar = new JDialog(this);

        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(300, 300);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 60, 10, 10);
        Font textoGrande = new Font("Arial", 1, 16);
        ediitarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(ediitarTextoPrincipalDialogo, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        final JTable tablaDialogo = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int column) {
                //all cells false
                return false;
            }
        };
        ;

        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2" };
            data[0] = listaClientes.get(i).getCliente_id();
            data[1] = listaClientes.get(i).getNombre();
            modeloTabla.addRow(data);
        }

        tablaDialogo.setModel(modeloTabla);
        tablaDialogo.getColumn("Identificacin").setMinWidth(110);
        tablaDialogo.getColumn("Nombre").setMinWidth(110);
        tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(tablaDialogo);
        scroll.setPreferredSize(new Dimension(220, 150));

        panelDialogo.add(scroll, c);

        c.insets = new Insets(0, 0, 0, 10);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonGuardarClienteDialogo = new JButton("Elegir");
        panelDialogo.add(botonGuardarClienteDialogo, c);

        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonCerrarClienteDialogo = new JButton("Cancelar");
        panelDialogo.add(botonCerrarClienteDialogo, c);

        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);

        botonCerrarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialogoEditar.dispose();
            }
        });

        botonGuardarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int row = tablaDialogo.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

                } else {
                    Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                    jTextFieldIdentificacionClienteReporte.setText(String.valueOf(identificacionCliente));
                    botonGenerarReporteCliente.setEnabled(true);
                    dialogoEditar.dispose();

                }

            }
        }); // TODO add your handling code here:     
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "El valor de la identificacin de ser numrico");

    }

}

From source file:interfaces.InterfazPrincipal.java

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
    // TODO add your handling code here:
    String nombre = jTextFieldNombreSaldoProveedores.getText();
    ControladorProveedores controladorProveedores = new ControladorProveedores();
    ArrayList<Proveedores> listaProveedores = controladorProveedores.obtenerProveedores("", nombre);

    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar proveedores");
    dialogoEditar.setSize(500, 300);/*  w w w .  j  a  va  2  s  . co m*/
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar Proveedores");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 3;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    ;
    modeloTabla.addColumn("ID");
    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaProveedores.size(); i++) {
        Object[] data = { "1", "2", "3" };
        data[0] = listaProveedores.get(i).getID();
        data[1] = listaProveedores.get(i).getIdentificacion();
        data[2] = listaProveedores.get(i).getNombre();
        System.out.println("Nombre!!" + data[2]);
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("ID").setMinWidth(70);
    tablaDialogo.getColumn("Identificacin").setMinWidth(60);
    tablaDialogo.getColumn("Nombre").setMinWidth(150);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                Object idCliente = tablaDialogo.getValueAt(row, 1);
                mostrarIDProveedor.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 2));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoNombreProveedor.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoProveedor.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoCompras controladorFlujoCompra = new ControladorFlujoCompras();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<Flujo_Compra> flujosProveedor = controladorFlujoCompra.obtenerFlujosCompras(
                        " where ID_CompraProveedor in (select ID_CompraProveedor from Compra_Proveedores where IDProveedor = "
                                + String.valueOf(identificacionCliente) + ") order by ID_CompraProveedor");
                double pago = 0.0;

                for (int i = 0; i < flujosProveedor.size(); i++) {
                    Flujo_Compra datos = flujosProveedor.get(i);
                    Object[] rowData = { datos.getID_CompraProveedor(), datos.getTipo_flujo(), datos.getFecha(),
                            datos.getMonto() };

                    if (datos.getTipo_flujo().equals("deuda")) {
                        pago += Double.parseDouble(datos.getMonto() + "");
                    } else {
                        pago -= Double.parseDouble(datos.getMonto() + "");
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoProveedor.setModel(modeloClientes);
                deudaActualProveedor.setText(String.valueOf(pago));
                dialogoEditar.dispose();

                //Mostrar en table de clientes los datos
                botonRegistrarAbono.setEnabled(true);
            }

        }

    });

}