Example usage for javax.swing JFileChooser setCurrentDirectory

List of usage examples for javax.swing JFileChooser setCurrentDirectory

Introduction

In this page you can find the example usage for javax.swing JFileChooser setCurrentDirectory.

Prototype

@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.")
public void setCurrentDirectory(File dir) 

Source Link

Document

Sets the current directory.

Usage

From source file:edu.harvard.mcz.imagecapture.jobs.JobCleanDirectory.java

private List<File> getFileList() {
    ArrayList<File> files = new ArrayList<File>();
    String pathToCheck = "";
    // Find the path in which to include files.
    File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
    File startPoint = null;/*  w ww  .  j  a v a  2 s. co m*/
    // If it isn't null, retrieve the image base directory from properties, and test for read access.
    if (Singleton.getSingletonInstance().getProperties().getProperties()
            .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                "Can't start scan.  Don't know where images are stored.  Set imagbase property.", "Can't Scan.",
                JOptionPane.ERROR_MESSAGE);
    } else {
        imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
        if (imagebase != null) {
            if (imagebase.canRead()) {
                startPoint = imagebase;
            } else {
                // If it can't be read, null out imagebase
                imagebase = null;
            }
        }
        if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
            // A scan start point has been provided, don't launch a dialog.
            startPoint = startPointSpecific;
        }
        if (imagebase == null || scan == SCAN_SELECT) {
            // launch a file chooser dialog to select the directory to scan
            final JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                fileChooser.setCurrentDirectory(startPointSpecific);
            } else {
                if (Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                    fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                            .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                }
            }
            int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                log.debug("Selected base directory: " + file.getName() + ".");
                startPoint = file;
            } else {
                //TODO: handle error condition
                log.error("Directory selection cancelled by user.");
            }
        }

        // Check that startPoint is or is within imagebase.
        if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
            String base = Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
            log.error("Tried to scan directory (" + startPoint.getPath() + ") outside of base image directory ("
                    + base + ")");
            String message = "Can't scan and cleanup files outside of base image directory (" + base + ")";
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
        } else if (ImageCaptureProperties.getPathBelowBase(startPoint).trim().length() == 0) {
            String base = Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
            log.error("Tried to scan directory (" + startPoint.getPath()
                    + ") which is the base image directory.");
            String message = "Can only scan and cleanup files in a selected directory within the base directory  ("
                    + base + ").\nYou must select some subdirectory within the base directory to cleanup.";
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Can't Cleanup image base directory.", JOptionPane.YES_NO_OPTION);

        } else {
            if (!startPoint.canRead()) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                        "Can't Scan.", JOptionPane.YES_NO_OPTION);
            } else {
                pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);

                // retrieve a list of image records in the selected directory
                ICImageLifeCycle ils = new ICImageLifeCycle();
                List<ICImage> images = ils.findAllInDir(pathToCheck);
                Iterator<ICImage> iter = images.iterator();
                while (iter.hasNext()) {
                    ICImage image = iter.next();
                    File imageFile = new File(
                            ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));
                    files.add(imageFile);
                    counter.incrementFilesSeen();
                }

            }
        }
    }

    log.debug("Found " + files.size() + " Image files in directory to check.");

    return files;
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void loadReference() throws Exception {
    JFileChooser chooser = new JFileChooser("Please choose a reference file or directory.");

    chooser.setCurrentDirectory(frame.defaultDirectory);
    // TODO: detect if all directory formats are not readable and in this case dont allow directory opening
    chooser.setFileSelectionMode(//from ww w . ja va 2 s  .c  o  m
            ReferenceFormats.REFERENCE_FORMATS.directoryFormats.isEmpty() ? JFileChooser.FILES_ONLY
                    : JFileChooser.FILES_AND_DIRECTORIES);
    for (ReferenceFormat format : ReferenceFormats.REFERENCE_FORMATS.readableFormats) {
        chooser.addChoosableFileFilter(
                new FilesystemFilter(format.getFileExtension(), format.getDescription()));
    }
    chooser.setAcceptAllFileFilterUsed(true);

    int returnVal = chooser.showOpenDialog(frame);
    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;
    }

    ReferenceFormat format = null;
    System.out.print("Loading...");
    frame.setTitle("Loading...");
    File f = chooser.getSelectedFile();
    Collection<ReferenceFormat> formats;

    if (f.isDirectory()) {
        formats = ReferenceFormats.REFERENCE_FORMATS.directoryFormats;
    } else {
        formats = ReferenceFormats.REFERENCE_FORMATS.extensionToFormats
                .get(f.getName().substring(f.getName().lastIndexOf(".") + 1));
    }

    if (formats == null || formats.isEmpty()) {
        throw new Exception("No format available that can read files with the "
                + f.getName().substring(f.getName().lastIndexOf(".") + 1) + " extension.");
    }
    if (formats.size() == 1) {
        format = formats.iterator().next();
    } else {
        format = formatChooser(formats);
    }

    if (format == null) {
        return;
    }
    Reference reference = format.readReference(chooser.getSelectedFile(), true, frame.loadLimit);
    if (!reference.links.isEmpty()) {
        Link firstLink = reference.links.iterator().next();
        frame.dataSourceName1 = EvaluationFrame.getProbableDatasourceName(firstLink.uris.first);
        frame.dataSourceName2 = EvaluationFrame.getProbableDatasourceName(firstLink.uris.second);
    }
    frame.setReference(reference);

    //frame.loadPositiveNegativeNT(chooser.getSelectedFile());
    System.out.println("loading finished, " + reference.links.size() + " links loaded.");

}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveReferenceXML() {
    JFileChooser chooser = new JFileChooser(
            "Save as alignment xml format. YOUR EVALUATION WILL NOT BE SAVED, ONLY A COPY OF THE INPUT.");
    chooser.setCurrentDirectory(new File("."));
    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile().exists() && (JOptionPane.showConfirmDialog(frame,
                "File already exists. Overwrite?") != JOptionPane.YES_OPTION)) {
            return;
        }/*from w w  w. ja v  a2s.  c o  m*/
        frame.saveReferenceXML(chooser.getSelectedFile(), true);
    }
}

From source file:edu.harvard.mcz.imagecapture.jobs.JobRecheckForTemplates.java

private List<ICImage> getFileList() {
    List<ICImage> files = new ArrayList<ICImage>();
    if (scan != SCAN_ALL) {
        String pathToCheck = "";
        // Find the path in which to include files.
        File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
        File startPoint = null;//from   w w w  . j  av a  2s .c  o m
        // If it isn't null, retrieve the image base directory from properties, and test for read access.
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                    "Can't start scan.  Don't know where images are stored.  Set imagbase property.",
                    "Can't Scan.", JOptionPane.ERROR_MESSAGE);
        } else {
            imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
            if (imagebase != null) {
                if (imagebase.canRead()) {
                    startPoint = imagebase;
                } else {
                    // If it can't be read, null out imagebase
                    imagebase = null;
                }
            }
            if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
                // A scan start point has been provided, don't launch a dialog.
                startPoint = startPointSpecific;
            }
            if (imagebase == null || scan == SCAN_SELECT) {
                // launch a file chooser dialog to select the directory to scan
                final JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                    fileChooser.setCurrentDirectory(startPointSpecific);
                } else {
                    if (Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                        fileChooser
                                .setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                                        .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                    }
                }
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    log.debug("Selected base directory: " + file.getName() + ".");
                    startPoint = file;
                } else {
                    //TODO: handle error condition
                    log.error("Directory selection cancelled by user.");
                }
            }

            // Check that startPoint is or is within imagebase.
            if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
                String base = Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                log.error("Tried to scan directory (" + startPoint.getPath()
                        + ") outside of base image directory (" + base + ")");
                String message = "Can't scan and database files outside of base image directory (" + base + ")";
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                        "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
            } else {
                if (!startPoint.canRead()) {
                    JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                            "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                            "Can't Scan.", JOptionPane.YES_NO_OPTION);
                } else {
                    pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);

                    // retrieve a list of image records in the selected directory
                    ICImageLifeCycle ils = new ICImageLifeCycle();
                    ICImage pattern = new ICImage();
                    pattern.setPath(pathToCheck);
                    pattern.setTemplateId(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS);
                    files = ils.findByExample(pattern);
                    if (files != null) {
                        log.debug(files.size());
                    }
                }
            }
        }
    } else {
        try {
            // retrieve a list of all image records with no template
            ICImageLifeCycle ils = new ICImageLifeCycle();
            files = ils.findNotDrawerNoTemplateImages();
            if (files != null) {
                log.debug(files.size());
            }
        } catch (HibernateException e) {
            log.error(e.getMessage());
            runStatus = RunStatus.STATUS_FAILED;
            String message = "Error loading the list of images with no templates. " + e.getMessage();
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                    "Error loading image records.", JOptionPane.YES_NO_OPTION);
        }
    }

    log.debug("Found " + files.size() + " Image files without templates in directory to check.");

    return files;
}

From source file:pcd3.View.java

private void pilihGambarSharpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarSharpMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;//from w ww . j  a  va 2  s .  c  o  m
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraTelu.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormTelu.setImage(bimg);
                    imageFormTelu.imageToGray(1);
                    citraSharpheningAwal.setText("");
                    citraSharpheningGray.setText("");
                    citraSharpheningHasil.setText("");
                    citraSharpheningAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSharpheningGray.setIcon(
                            new ImageIcon(imageFormTelu.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraTelu.setText("Ukuran Citra : " + imageFormTelu.getTinggi() + " x "
                            + imageFormTelu.getLebar() + "");
                    imageFormTelu.setSharpeningImage();
                    citraSharpheningHasil.setIcon(
                            new ImageIcon(imageFormTelu.getSharpeningImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:pcd3.View.java

private void pilihGambarLoroMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pilihGambarLoroMouseClicked
    final String path = "./Citra Images/form.1";

    javax.swing.JFileChooser chooser = new javax.swing.JFileChooser();
    chooser.setCurrentDirectory(new File(path));

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public final static String jpeg = "jpeg";
        public final String jpg = "jpg";
        public final String gif = "gif";
        public final String tiff = "tiff";
        public final String tif = "tif";
        public final String png = "png";

        /*Get the extension of a file.*/
        public String getExtension(java.io.File f) {
            String ext = null;//from w  ww .jav a2  s.  c  o  m
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }
            return ext;
        }

        @Override
        public String getDescription() {
            return "All Images extensions (jpg, gif, tiff, tif, png)";
        }

        @Override
        public boolean accept(java.io.File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                return extension.equals(tiff) || extension.equals(tif) || extension.equals(gif)
                        || extension.equals(jpeg) || extension.equals(jpg) || extension.equals(png);
            }

            return false;
        }
    });

    if (chooser.showDialog(this, "  Open  ") == javax.swing.JFileChooser.APPROVE_OPTION) {
        java.io.File file = chooser.getSelectedFile();
        String filePath = file.toString();
        try {
            final BufferedImage bimg = ImageIO.read(new File(filePath));
            namaCitraLoro.setText("Nama Citra : " + file.getName());
            Thread t = new Thread() {
                @Override
                public void run() {
                    imageFormLoro.setImage(bimg);
                    imageFormLoro.imageToGray(1);
                    citraSmoothingAwal.setText("");
                    citraSmoothingGray.setText("");
                    citraSmoothingHasil.setText("");
                    citraSmoothingAwal.setIcon(new ImageIcon(bimg.getScaledInstance(300, 300, 0)));
                    citraSmoothingGray.setIcon(
                            new ImageIcon(imageFormLoro.getGrayImage().getScaledInstance(300, 300, 0)));
                    ukuranCitraLoro.setText("Ukuran Citra : " + imageFormLoro.getTinggi() + " x "
                            + imageFormLoro.getLebar() + "");
                    imageFormLoro.setSmoothingImage();
                    citraSmoothingHasil.setIcon(
                            new ImageIcon(imageFormLoro.getSmoothingImage().getScaledInstance(300, 300, 0)));
                }
            };
            t.start();

        } catch (IOException e) {
            javax.swing.JOptionPane.showMessageDialog(this, "File Tidak Ditemukan " + e);
        }
    }
}

From source file:androhashcheck.MainFrame.java

/**
 * Opens file expolorer to choose file to be uploaded.
 *
 * @param evt//from  w w w.  j a va  2s  .c o m
 */
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        this.textField1.setText(selectedFile.getAbsolutePath());
    }
}

From source file:Forms.FrmPrincipal.java

private void btnFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFileActionPerformed
    // TODO add your handling code here:
    File sArchivo;//w  w  w.j a  va  2  s .c om
    JFileChooser archivo = new JFileChooser();
    BufferedReader br = null;
    int lin = 0;
    patrones = new ArrayList<String[]>();

    try {
        archivo.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = archivo.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            sArchivo = archivo.getSelectedFile();
            txtArchivo.setText(sArchivo.getAbsolutePath());

            br = new BufferedReader(new FileReader(sArchivo.getAbsolutePath()));
            String linea = br.readLine();
            while (null != linea) {
                String[] campos = linea.split(SEPARADOR);
                numEntradas = campos.length;
                patrones.add(campos);
                linea = br.readLine();
                lin++;
            }
        }

        llenaMatriz();

    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage());
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage());
        Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (null != br)
            try {
                br.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
                Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
}

From source file:cn.labthink.ReadAccess060.java

private void jButton_OpenfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OpenfileActionPerformed

    //filter//from   ww w  . java 2 s .c om
    ExtensionFileFilter filter = new ExtensionFileFilter("mdb", false, true);
    filter.setDescription("Open DataBase File");
    //?

    JFileChooser jfc = new JFileChooser();

    FileSystemView fsv = FileSystemView.getFileSystemView();
    //?
    jfc.setCurrentDirectory(fsv.getHomeDirectory());

    jfc.setDialogTitle("Choose the mdb file");
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.OPEN_DIALOG);
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setFileFilter(filter);
    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        String filesrc = jfc.getSelectedFile().getAbsolutePath();
        inputfile = jfc.getSelectedFile();
        jLabel_dbpath.setText("DB File Path:" + filesrc);
        maxid = Integer.MIN_VALUE;
        minid = Integer.MAX_VALUE;
    } else {
        return;
    }
    //

    Infodata = new Vector();
    Infocolumns = new Vector();

    try {

        //            String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D://b.MDB";
        if (inputfile == null) {
            return;
        }
        initDB();

        sql = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = sql.executeQuery("SELECT * FROM test order by testid desc");

        Infocolumns.add("TestID");
        Infocolumns.add("TestType");
        Infocolumns.add("DeviceID");
        Infocolumns.add("CellID");
        Infocolumns.add("Operator");
        Infocolumns.add("StartTime");
        Infocolumns.add("EndTime");
        Infocolumns.add("Comments");
        Infocolumns.add("SetTemp.");
        int columnCount = Infocolumns.size();
        Vector row;
        while (rs.next()) {
            row = new Vector(columnCount);
            int temp = 0;
            int ivalue = rs.getInt("TESTID");
            maxid = maxid < ivalue ? ivalue : maxid;
            minid = minid > ivalue ? ivalue : minid;
            row.add(ivalue);
            temp = rs.getInt("TESTTYPE");
            if (temp == 1) {
                row.add("OTR");
            } else if (temp == 2) {
                row.add("WVTR");
            } else {
                row.add(temp);
            }
            row.add(rs.getInt("DEVICEID"));
            row.add(rs.getString("CELLID"));
            row.add(rs.getString("OPERATOR"));
            row.add(rs.getDate("STARTTIME"));
            row.add(rs.getDate("ENDTIME"));
            row.add(rs.getString("COMMENTS"));
            row.add(rs.getDouble("SETTEMP"));
            //                row.add(rs.getString(11));
            //                row.add(rs.getInt(10));
            Infodata.add(row);
        }

        DefaultTableModel tableModel = new DefaultTableModel(Infodata, Infocolumns);
        jTable1.setModel(tableModel);
        //?  
        // jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
        jTable1.setSelectionBackground(Color.orange);
        //?
        TableRowSorter<TableModel> tableRowSorter = new TableRowSorter<TableModel>(tableModel);
        jTable1.setRowSorter(tableRowSorter);
        //            jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// table
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// ??
        jTable1.setDefaultRenderer(Object.class, tcr);

        //
        ((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer())
                .setHorizontalAlignment(SwingConstants.CENTER);
        //            DefaultTableCellRenderer  rh = new DefaultTableCellRenderer();
        //            rh.setHorizontalAlignment(SwingConstants.CENTER);
        //            jTable1.getTableHeader().setDefaultRenderer(rh);

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(28);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(7).setPreferredWidth(100);

    } catch (SQLException ee) {
        System.out.println(ee);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ReadAccess060.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            sql.close();
        } catch (Exception e) {
        }
        try {
            rs.close();
        } catch (Exception e) {
        }
    }

    //        validate();

}

From source file:cn.labthink.ReadAccess330.java

private void jButton_OpenfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OpenfileActionPerformed

    //filter/*from  www  . ja  v  a 2s  .  co m*/
    ExtensionFileFilter filter = new ExtensionFileFilter("mdb", false, true);
    filter.setDescription("Open DataBase File");
    //?

    JFileChooser jfc = new JFileChooser();

    FileSystemView fsv = FileSystemView.getFileSystemView();
    //?
    jfc.setCurrentDirectory(fsv.getHomeDirectory());

    jfc.setDialogTitle("Choose the mdb file");
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.OPEN_DIALOG);
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setFileFilter(filter);
    int result = jfc.showOpenDialog(this); // ""?
    if (result == JFileChooser.APPROVE_OPTION) {
        String filesrc = jfc.getSelectedFile().getAbsolutePath();
        inputfile = jfc.getSelectedFile();
        jLabel_dbpath.setText("DB File Path:" + filesrc);
        maxid = Integer.MIN_VALUE;
        minid = Integer.MAX_VALUE;
    } else {
        return;
    }
    //

    Infodata = new Vector();
    Infocolumns = new Vector();

    try {

        //            String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D://b.MDB";
        if (inputfile == null) {
            return;
        }
        initDB();

        sql = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = sql.executeQuery("SELECT * FROM test order by testid desc");

        Infocolumns.add("TestID");
        Infocolumns.add("TestType");
        Infocolumns.add("DeviceID");
        Infocolumns.add("CellID");
        Infocolumns.add("Operator");
        Infocolumns.add("StartTime");
        Infocolumns.add("EndTime");
        Infocolumns.add("Comments");
        Infocolumns.add("SetTemp.");
        int columnCount = Infocolumns.size();
        Vector row;
        while (rs.next()) {
            row = new Vector(columnCount);
            int temp = 0;
            int ivalue = rs.getInt("TESTID");
            maxid = maxid < ivalue ? ivalue : maxid;
            minid = minid > ivalue ? ivalue : minid;
            row.add(ivalue);
            temp = rs.getInt("TESTTYPE");
            if (temp == 1) {
                row.add("OTR");
            } else if (temp == 2) {
                row.add("WVTR");
            } else {
                row.add(temp);
            }
            row.add(rs.getInt("DEVICEID"));
            row.add(rs.getString("CELLID"));
            row.add(rs.getString("OPERATOR"));
            row.add(rs.getDate("STARTTIME"));
            row.add(rs.getDate("ENDTIME"));
            row.add(rs.getString("COMMENTS"));
            row.add(rs.getDouble("SETTEMP"));
            //                row.add(rs.getString(11));
            //                row.add(rs.getInt(10));
            Infodata.add(row);
        }

        DefaultTableModel tableModel = new DefaultTableModel(Infodata, Infocolumns);
        jTable1.setModel(tableModel);
        //?  
        // jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
        jTable1.setSelectionBackground(Color.orange);
        //?
        TableRowSorter<TableModel> tableRowSorter = new TableRowSorter<TableModel>(tableModel);
        jTable1.setRowSorter(tableRowSorter);
        //            jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// table
        tcr.setHorizontalAlignment(SwingConstants.CENTER);// ??
        jTable1.setDefaultRenderer(Object.class, tcr);

        //
        ((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer())
                .setHorizontalAlignment(SwingConstants.CENTER);
        //            DefaultTableCellRenderer  rh = new DefaultTableCellRenderer();
        //            rh.setHorizontalAlignment(SwingConstants.CENTER);
        //            jTable1.getTableHeader().setDefaultRenderer(rh);

        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(28);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(40);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(6).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(7).setPreferredWidth(100);

    } catch (SQLException ee) {
        System.out.println(ee);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ReadAccess330.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            sql.close();
        } catch (Exception e) {
        }
        try {
            rs.close();
        } catch (Exception e) {
        }
    }

    //        validate();

}