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:frames.MainGUI.java

public void LoadFeeDataToJTable(JTable t, File file) {
    try {//from   w w  w  .  j a  v  a 2  s  .c  o m
        CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        //t.setModel(tm);
        DefaultTableModel model = new DefaultTableModel();
        //model.setRowCount(0);
        for (CSVRecord c : parser) {
            if (c.getRecordNumber() == 1) {

                model.addColumn(c.get(datatype.GlobalVariable.TYPE));
                model.addColumn(c.get(datatype.GlobalVariable.AMOUNT));
                model.addColumn(c.get(datatype.GlobalVariable.PAID_BY));
                model.addColumn(c.get(datatype.GlobalVariable.PAYER));
                t.setModel(model);
                model = (DefaultTableModel) t.getModel();
                continue;
            }
            model.addRow(
                    new Object[] { c.get(datatype.GlobalVariable.TYPE), c.get(datatype.GlobalVariable.AMOUNT),
                            c.get(datatype.GlobalVariable.PAID_BY), c.get(datatype.GlobalVariable.PAYER) });
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:frames.MainGUI.java

public void LoadRentToJtable(JTable t, File file) {
    try {/*from   w  w  w  .  j  a  va 2 s  . co  m*/
        CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        //t.setModel(tm);
        DefaultTableModel model = new DefaultTableModel();
        //model.setRowCount(0);
        for (CSVRecord c : parser) {
            if (c.getRecordNumber() == 1) {
                model.addColumn("??");
                model.addColumn("");
                model.addColumn("?");
                model.addColumn("?");
                model.addColumn("");
                model.addColumn("");
                t.setModel(model);
                model = (DefaultTableModel) t.getModel();
                continue;
            }
            model.addRow(new Object[] { c.get(0), c.get(1), c.get(2), c.get(3), c.get(4), c.get(5) });
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:edu.ku.brc.specify.config.init.secwiz.UserPanel.java

/**
 * /*w w w .jav  a 2s .  c  om*/
 */
private void printUserData() {
    JTable printTable = new JTable();

    int i = 0;
    Object[][] pValueObjs = new Object[userModel.getUserData().size()][6];
    for (UserData ud : userModel.getUserData()) {
        pValueObjs[i++] = ud.getData();
    }

    String[] headers = { "Username", "Passsword", "Last Name", "First Name", "EMail", "New Password" };
    DefaultTableModel model = new DefaultTableModel(pValueObjs, headers) {
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }
    };
    printTable.setModel(model);

    PrintTableHelper pth = new PrintTableHelper(printTable);
    pth.printGrid(UIRegistry.getResourceString("SUMMARY"));
}

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

private void showXLS(JTextField txtFileDirectory, JTable tablePreview)
        throws FileNotFoundException, IOException {
    DefaultTableModel tableModel = new DefaultTableModel();
    File fileName = new File(txtFileDirectory.getText());
    FileInputStream inputStream = new FileInputStream(fileName);
    HSSFWorkbook workBook = new HSSFWorkbook(inputStream);
    HSSFSheet sheet = workBook.getSheetAt(0);

    int rowValue = sheet.getLastRowNum() + 1;
    int colValue = sheet.getRow(0).getLastCellNum();
    String[][] data = new String[rowValue][colValue];
    String[] colName = new String[colValue];
    for (int i = 0; i < rowValue; i++) {
        HSSFRow row = sheet.getRow(i);//from  ww w . j a  va 2 s.c  om
        for (int j = 0; j < colValue; j++) {
            HSSFCell cell = row.getCell(j);
            int type = cell.getCellType();
            Object returnCellValue = null;
            if (type == 0) {
                returnCellValue = cell.getNumericCellValue();
            } else if (type == 1) {
                returnCellValue = cell.getStringCellValue();
            }

            data[i][j] = returnCellValue.toString();
        }
    }

    for (int i = 0; i < colValue; i++) {
        colName[i] = data[0][i];
    }

    tableModel = new DefaultTableModel(data, colName);
    tablePreview.setModel(tableModel);
    tableModel.removeRow(0);
}

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

private void showXLSX(JTextField txtFileDirectory, JTable tablePreview)
        throws FileNotFoundException, IOException {
    DefaultTableModel tableModel = new DefaultTableModel();
    File fileName = new File(txtFileDirectory.getText());
    FileInputStream inputStream = new FileInputStream(fileName);
    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
    XSSFSheet sheet = workbook.getSheetAt(0);

    int rowValue = sheet.getLastRowNum() + 1;
    int colValue = sheet.getRow(0).getLastCellNum();
    String[][] data = new String[rowValue][colValue];
    String[] colName = new String[colValue];
    for (int i = 0; i < rowValue; i++) {
        XSSFRow row = sheet.getRow(i);/*from  w  ww.  j av  a 2s  .  c  o  m*/
        for (int j = 0; j < colValue; j++) {
            XSSFCell cell = row.getCell(j);
            int type = cell.getCellType();
            Object returnCellValue = null;
            if (type == 0) {
                returnCellValue = cell.getNumericCellValue();
            } else if (type == 1) {
                returnCellValue = cell.getStringCellValue();
            }

            data[i][j] = returnCellValue.toString();
        }
    }

    for (int i = 0; i < colValue; i++) {
        colName[i] = data[0][i];
    }

    tableModel = new DefaultTableModel(data, colName);
    tablePreview.setModel(tableModel);
    tableModel.removeRow(0);
}

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

private double[][] evaluationModel(JTable tableResult, JTable tableConfMatrix, JLabel totalAccuracy,
        JTable tableTahunTesting, JTable tableDataSetTesting, String[] knnValue, int i, int[] tempK,
        JPanel panelChart) throws SQLException {
    int actIPA = 0;
    int actIPS = 0;
    int trueIPA = 0;
    int falseIPA = 0;
    int trueIPS = 0;
    int falseIPS = 0;

    double recIPA;
    double recIPS;
    double preIPA;
    double preIPS;
    double accuracy;

    DefaultTableModel tableModelRes = new DefaultTableModel();
    tableModelRes = (DefaultTableModel) tableResult.getModel();
    String[] tempJurusan = getJurusanTest(tableTahunTesting, tableDataSetTesting);

    for (int j = 0; j < tableDataSetTesting.getRowCount(); j++) {
        String nis = tableDataSetTesting.getValueAt(j, 0).toString();
        String jurusan = tempJurusan[j];
        String classified = knnValue[j];
        Object[] tableContent = { nis, jurusan, classified };
        tableModelRes.addRow(tableContent);
        tableResult.setModel(tableModelRes);
    }//from ww w  .j  ava2  s  . c o m

    /*Hitung Jumlah Data Actual IPA dan IPS*/
    for (int j = 0; j < tempJurusan.length; j++) {
        if (tempJurusan[j].equals("IPA")) {
            actIPA = actIPA + 1;
        } else if (tempJurusan[j].equals("IPS")) {
            actIPS = actIPS + 1;
        }
    }

    /*Hitung Jumlah Data Classified IPA dan IPS*/
    for (int j = 0; j < knnValue.length; j++) {
        if (tableResult.getValueAt(j, 1).equals("IPA")) {
            if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) {
                trueIPA = trueIPA + 1;
            } else {
                falseIPS = falseIPS + 1;
            }
        } else if (tableResult.getValueAt(j, 1).equals("IPS")) {
            if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) {
                trueIPS = trueIPS + 1;
            } else {
                falseIPA = falseIPA + 1;
            }
        }
    }

    /*Hitung Nilai Recall, Precision, dan Accuracy*/
    preIPA = (double) trueIPA / (trueIPA + falseIPA);
    preIPS = (double) trueIPS / (trueIPS + falseIPS);
    recIPA = (double) trueIPA / (trueIPA + falseIPS);
    recIPS = (double) trueIPS / (trueIPS + falseIPA);
    accuracy = (double) (trueIPA + trueIPS) / (trueIPA + trueIPS + falseIPA + falseIPS);

    /*Tampung Nilai Recall, Precision, dan Accuracy*/
    double[][] tempEval = new double[3][tempK.length];
    tempEval[0][i] = accuracy;
    tempEval[1][i] = recIPA;
    tempEval[2][i] = preIPA;

    /*Set Nilai TF, TN, FP, FN ke Tabel Confusion Matrix*/
    tableConfMatrix.setValueAt("Actual IPA", 0, 0);
    tableConfMatrix.setValueAt("Actual IPS", 1, 0);
    tableConfMatrix.setValueAt("Class Precision", 2, 0);
    tableConfMatrix.setValueAt(trueIPA, 0, 1);
    tableConfMatrix.setValueAt(falseIPS, 0, 2);
    tableConfMatrix.setValueAt(falseIPA, 1, 1);
    tableConfMatrix.setValueAt(trueIPS, 1, 2);

    /*Set Nilai Recall, Precision, dan Accuracy ke Tabel Confusion Matrix*/
    if (Double.isNaN(preIPA)) {
        tableConfMatrix.setValueAt("NaN" + " %", 2, 1);
    } else {
        tableConfMatrix.setValueAt(df.format(preIPA * 100) + " %", 2, 1);
    }
    if (Double.isNaN(preIPS)) {
        tableConfMatrix.setValueAt("NaN" + " %", 2, 2);
    } else {
        tableConfMatrix.setValueAt(df.format(preIPS * 100) + " %", 2, 2);
    }
    if (Double.isNaN(recIPA)) {
        tableConfMatrix.setValueAt("NaN" + " %", 0, 3);
    } else {
        tableConfMatrix.setValueAt(df.format(recIPA * 100) + " %", 0, 3);
    }
    if (Double.isNaN(recIPS)) {
        tableConfMatrix.setValueAt("NaN" + " %", 1, 3);
    } else {
        tableConfMatrix.setValueAt(df.format(recIPS * 100) + " %", 1, 3);
    }
    if (Double.isNaN(accuracy)) {
        totalAccuracy.setText("Overall Accuracy is " + "NaN" + " %");
    } else {
        totalAccuracy.setText("Overall Accuracy is " + df.format(accuracy * 100) + " %");
    }

    tableModelRes.setRowCount(0);

    return tempEval;
}

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

public void showClassificationResult(JTable tableResult, JTable tablePreview, String[] knnValue,
        int rowCountData, JLabel labelSiswaIPA, JLabel labelSiswaIPS, JLabel labelKeterangan,
        JYearChooser jYearChooser1, JYearChooser jYearChooser2, int kValue) {
    DefaultTableModel tableModelResult = new DefaultTableModel();
    tableModelResult = (DefaultTableModel) tableResult.getModel();
    int jumlahSiswaIPA = 0;
    int jumlahSiswaIPS = 0;

    for (int i = 0; i < rowCountData; i++) {
        if (knnValue[i].equals("IPA")) {
            jumlahSiswaIPA = jumlahSiswaIPA + 1;
        } else if (knnValue[i].equalsIgnoreCase("IPS")) {
            jumlahSiswaIPS = jumlahSiswaIPS + 1;
        }/*from  ww w  .  j  a  v a 2 s .co  m*/

        String nis = tablePreview.getValueAt(i, 0).toString();
        String nama = tablePreview.getValueAt(i, 1).toString();
        String jenKel = tablePreview.getValueAt(i, 2).toString();
        String nilaiUN = tablePreview.getValueAt(i, 3).toString();
        String ptBindo = tablePreview.getValueAt(i, 4).toString();
        String ptMtk = tablePreview.getValueAt(i, 5).toString();
        String ptBing = tablePreview.getValueAt(i, 6).toString();
        String ptIpa = tablePreview.getValueAt(i, 7).toString();
        String minat = tablePreview.getValueAt(i, 8).toString();
        String jurusan = knnValue[i];
        Object[] resultData = { nis, nama, jenKel, nilaiUN, ptBindo, ptMtk, ptBing, ptIpa, minat, jurusan };
        tableModelResult.addRow(resultData);
    }
    tableResult.setModel(tableModelResult);
    labelSiswaIPA.setText(jumlahSiswaIPA + "");
    labelSiswaIPS.setText(jumlahSiswaIPS + "");
    labelKeterangan.setText("Hasil Klasifikasi Penjurusan Siswa Pada Tahun Ajaran " + jYearChooser1.getYear()
            + "/" + jYearChooser2.getYear() + ", dengan paramater K = " + kValue + " adalah sebagai berikut ");
}

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

private double[][] evaluationModel(JTable tableResult, JTable tableConfMatrix, JLabel totalAccuracy,
        JTable tableTahunTesting, JTable tableDataSetTesting, String[] knnValue, int nilaiK, JPanel panelChart)
        throws SQLException {
    int actIPA = 0;
    int actIPS = 0;
    int trueIPA = 0;
    int falseIPA = 0;
    int trueIPS = 0;
    int falseIPS = 0;
    int classIPA = 0;
    int classIPS = 0;

    double recIPA;
    double recIPS;
    double preIPA;
    double preIPS;
    double accuracy;

    DefaultTableModel tableModelConf = (DefaultTableModel) tableConfMatrix.getModel();
    DefaultTableModel tableModelRes = (DefaultTableModel) tableResult.getModel();
    String[] tempJurusan = getJurusanTest(tableTahunTesting, tableDataSetTesting);

    if (tableModelRes.getRowCount() != 0) {
        tableModelRes.setRowCount(0);/*from   w w  w. j a v  a2s  .com*/
    }

    for (int j = 0; j < tableDataSetTesting.getRowCount(); j++) {
        String nis = tableDataSetTesting.getValueAt(j, 0).toString();
        String jurusan = tempJurusan[j];
        String classified = knnValue[j];
        Object[] tableContent = { nis, jurusan, classified };
        tableModelRes.addRow(tableContent);
        tableResult.setModel(tableModelRes);
    }

    /*Hitung Jumlah Data Actual IPA dan IPS*/
    for (int j = 0; j < tempJurusan.length; j++) {
        if (tempJurusan[j].equals("IPA")) {
            actIPA = actIPA + 1;
        } else if (tempJurusan[j].equals("IPS")) {
            actIPS = actIPS + 1;
        }
    }

    /*Hitung Jumlah Data Classified IPA dan IPS*/
    for (int j = 0; j < knnValue.length; j++) {
        if (tableResult.getValueAt(j, 1).equals("IPA")) {
            if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) {
                trueIPA = trueIPA + 1;
            } else {
                falseIPS = falseIPS + 1;
            }
        } else if (tableResult.getValueAt(j, 1).equals("IPS")) {
            if (tableResult.getValueAt(j, 1).equals(tableResult.getValueAt(j, 2))) {
                trueIPS = trueIPS + 1;
            } else {
                falseIPA = falseIPA + 1;
            }
        }
    }
    //        System.out.println("trueIPA =" + trueIPA);
    //        System.out.println("falseIPA =" + falseIPA);
    //        System.out.println("falseIPS =" + falseIPS);
    //        System.out.println("trueIPS =" + trueIPS);

    /*Hitung Nilai Recall, Precision, dan Accuracy*/
    preIPA = (double) trueIPA / (trueIPA + falseIPA);
    preIPS = (double) trueIPS / (trueIPS + falseIPS);
    recIPA = (double) trueIPA / (trueIPA + falseIPS);
    recIPS = (double) trueIPS / (trueIPS + falseIPA);
    accuracy = (double) (trueIPA + trueIPS) / (trueIPA + trueIPS + falseIPA + falseIPS);

    /*Tampung Nilai Recall, Precision, dan Accuracy*/
    double[][] tempEval = new double[3][1];
    tempEval[0][0] = accuracy;
    tempEval[1][0] = recIPA;
    tempEval[2][0] = preIPA;

    /*Set Nilai TF, TN, FP, FN ke Tabel Confusion Matrix*/
    tableModelConf.setValueAt("Actual IPA", 0, 0);
    tableModelConf.setValueAt("Actual IPS", 1, 0);
    tableModelConf.setValueAt("Class Precision", 2, 0);
    tableModelConf.setValueAt(trueIPA, 0, 1);
    tableModelConf.setValueAt(falseIPS, 0, 2);
    tableModelConf.setValueAt(falseIPA, 1, 1);
    tableModelConf.setValueAt(trueIPS, 1, 2);

    /*Set Nilai Recall, Precision, dan Accuracy ke Tabel Confusion Matrix*/
    if (Double.isNaN(preIPA)) {
        tableModelConf.setValueAt("NaN" + " %", 2, 1);
    } else {
        tableModelConf.setValueAt(df.format(preIPA * 100) + " %", 2, 1);
    }
    if (Double.isNaN(preIPS)) {
        tableModelConf.setValueAt("NaN" + " %", 2, 2);
    } else {
        tableModelConf.setValueAt(df.format(preIPS * 100) + " %", 2, 2);
    }
    if (Double.isNaN(recIPA)) {
        tableModelConf.setValueAt("NaN" + " %", 0, 3);
    } else {
        tableModelConf.setValueAt(df.format(recIPA * 100) + " %", 0, 3);
    }
    if (Double.isNaN(recIPS)) {
        tableModelConf.setValueAt("NaN" + " %", 1, 3);
    } else {
        tableModelConf.setValueAt(df.format(recIPS * 100) + " %", 1, 3);
    }
    if (Double.isNaN(accuracy)) {
        totalAccuracy.setText("Overall Accuracy is " + "NaN" + " %");
    } else {
        totalAccuracy.setText("Overall Accuracy is " + df.format(accuracy * 100) + " %");
    }
    //        System.out.println("Recall IPA = " + recIPA);
    //        System.out.println("Recall IPA =" + recIPS);
    //        System.out.println("Precision IPA  = " + preIPA);
    //        System.out.println("Precision IPS  = " + preIPS);
    //        System.out.println("Overall Accuracy  = " + accuracy);
    return tempEval;
}

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

/**
 * Parses the given import xls 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./*w  w  w. ja  va 2s  .  co  m*/
 * 
 * @param table - the table to display the data
 * @return JTable - the table to display the data
 */
private JTable setXLSTableData(final JTable table) {
    int numRows = 0;
    int numCols = 0;
    String[] headers = {};
    Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>();
    Vector<String> rowData = new Vector<String>();
    Vector<String> headerVector = new Vector<String>();
    DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    try {
        log.debug("setXLSTableData - file - " + configXLS.getFile().toString());

        InputStream input = new FileInputStream(configXLS.getFile());
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols);
        if (badHeads.size() > 0 && doesFirstRowHaveHeaders) {
            if (table != null) {
                ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle());
            }
            this.doesFirstRowHaveHeaders = false;
            try {
                ignoreActions = true;
                this.containsHeaders.setSelected(false);
            } finally {
                ignoreActions = false;
            }
            if (table != null) {
                return table;
            }
        }
        boolean firstRow = true;

        //quick fix to prevent ".0" at end of catalog numbers etc
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(20);
        nf.setGroupingUsed(false); //gets rid of commas

        int maxCols = 0;

        // Iterate over each row in the sheet
        Iterator<?> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            numCols = 0;
            rowData = new Vector<String>();
            HSSFRow row = (HSSFRow) rows.next();
            //log.debug(row.getLastCellNum()+"  "+row.getPhysicalNumberOfCells());
            int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
            if (maxSize > maxCols) {
                maxCols = maxSize;
            }
            while (numCols < maxSize) {
                if (emptyCols.indexOf(new Integer(numCols)) == -1) {
                    HSSFCell cell = row.getCell(numCols);
                    String value = null;
                    // if cell is blank, set value to ""
                    if (cell == null) {
                        value = "";
                    } else {
                        int type = cell.getCellType();

                        switch (type) {
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            // The best I can do at this point in the app is to guess if a
                            // cell is a date.
                            // Handle dates carefully while using HSSF. Excel stores all
                            // dates as numbers, internally.
                            // The only way to distinguish a date is by the formatting of
                            // the cell. (If you
                            // have ever formatted a cell containing a date in Excel, you
                            // will know what I mean.)
                            // Therefore, for a cell containing a date, cell.getCellType()
                            // will return
                            // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility
                            // function,
                            // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell
                            // can be a date.
                            // This function checks the format against a few internal
                            // formats to decide the issue,
                            // but by its very nature it is prone to false negatives.
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                                //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                            } else {
                                double numeric = cell.getNumericCellValue();
                                value = nf.format(numeric);
                            }
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getRichStringCellValue().getString();
                            break;

                        case HSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = Boolean.toString(cell.getBooleanCellValue());
                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW");
                            break;

                        default:
                            value = "";
                            log.error("unsuported cell type");
                            break;
                        }
                    }
                    if (firstRow && doesFirstRowHaveHeaders) {
                        checkUserColInfo(value, numCols);
                    }
                    if (isUserCol(numCols)) {
                        rowData.add(value.toString());
                    }
                }
                numCols++;
            }
            if (doesFirstRowHaveHeaders && firstRow) {
                headerVector = rowData;
                headers = new String[rowData.size()];
            } else if (!doesFirstRowHaveHeaders && firstRow) {
                //headers = createDummyHeaders(rowData.size());
                tableDataVector.add(rowData);
            } else {
                tableDataVector.add(rowData);
            }
            firstRow = false;
            numRows++;
        }
        maxCols -= emptyCols.size();
        if (!doesFirstRowHaveHeaders) {
            headerVector = createDummyHeadersAsVector(maxCols);
            headers = new String[maxCols];
        }
        for (int i = 0; i < headerVector.size(); i++) {
            headers[i] = headerVector.elementAt(i);
        }
        printArray(headers);

        String[][] tableData = new String[tableDataVector.size()][maxCols];
        for (int i = 0; i < tableDataVector.size(); i++) {
            Vector<String> v = tableDataVector.get(i);
            for (int j = 0; j < v.size(); j++) {
                tableData[i][j] = v.get(j).toString();
            }

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

        if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        log.debug(headers);
        log.debug(tableData);
        model = new PreviewTableModel(headers, tableData);
        JTable result = null;
        if (table == null) {
            result = new JTable();
            result.setColumnSelectionAllowed(false);
            result.setRowSelectionAllowed(false);
            result.setCellSelectionEnabled(false);
            result.getTableHeader().setReorderingAllowed(false);
            result.setPreferredScrollableViewportSize(new Dimension(500, 100));
            result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            result = table;
        }
        result.setModel(model);
        result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return result;
    } catch (Exception ex) {
        UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE"));
        if (table != null) {
            String[] columnNames = {};
            String[][] blankData = { {} };
            model = new PreviewTableModel(columnNames, blankData);
            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;
        }
        //log.error("Error attempting to parse input xls file:" + ex);
        //ex.printStackTrace();
    }

    return null;
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table/* www .  j av  a  2 s. co m*/
 * @param model
 * @return
 */
public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

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

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

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

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

    return table;
}