JFileChooser getSelectedFile

When I place a JFileChooser into its own JPanel, as part of a bigger JDialog, I have discovered that I am not able to get hold of the file name which I have entered into the associated textField.
I have used getSelectedFile(), but this only returns the Current Directory not the file name, I have even tried to extract the TextField by recursively calling getComponents() on all Containers within the JFileChooser but I was not able to get any reference to a TextField.
When the JFileChooser is used within its own Dialog everything works correctly.
Hope someone can help, Cheers

When/where are you calling getSelectedFile (perhaps post some code)? I believe the text entered in the textfield is not set as the selected file of the JFileChooser until after the OK button is pressed, e.g. in an override of approveSelection() or later.

Similar Messages

  • Override JFileChooser.getSelectedFiles() to return File[] in the order the files were selected.

    How would I accomplish this?

    Hi,
    I guess u can create a custom file chooser class. This should essentially include an event listener for selections done in the file chooser dialog and store in an array. you can pass this array back to the calling class/method.
    I could do it for u...but since u are already working on it...you might as well just go ahead and do it
    Let me know if this works,
    Cheers,
    Parth Shah

  • Is it a bug in JFileChooser?

    JDK & JRE:
    java version "1.4.2_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_02-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_02-b03, mixed mode)
    Operating System: Windows 2000 Advanced Server with sp4
    Description:
    Assume setting the JFileChooser's property as 'JFileChooser.FILES_AND_DIRECTORIES',
    double-clicking on a directory, enter the directory but no one file is selected,
    the text in the text-field that used for selected files is the name of this directory.
    For example, you've selected the directoy 'D:\jdk14', enter the directory and
    none is selected. Codes as below:
    File f = JFileChooser.getSelectedFile();
    String s = f.getAbsolutePath();
    The content of the variable named 's' is 'd:\jdk14\jdk14'

    Yes, it's a bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5075580

  • JFileChooser - how to filter

    jFileChooser.setAutoscrolls(true);
    jFileChooser.setDialogTitle("Program Analyzer");
    jFileChooser.setDialogType(1);
    jFileChooser.setBounds(new Rectangle(50, 23, 381, 216));
    void jLabelFile_mouseClicked(MouseEvent e) {
    jFileChooser.showDialog(this, "Select");
    file.FileSelection(jFileChooser.getSelectedFile());
    this is how i run the jFileChooser... how do i filter it to only display .java and .txt files
    jFileChooser.addChoosableFileFilter(); -- how do i use this method?? or is tehre another way???

    Hope this helps.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.filechooser.*;
    import java.io.File;
    public class Fr extends JFrame
    JButton jbutton = new JButton("Click here to select a file");
    public Fr()
    this.getContentPane().setLayout(new FlowLayout());
    this.getContentPane().add(jbutton);
    jbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae)
    JFileChooser jf= new JFileChooser();
    jf.setFileFilter( new MyFilter());
    int ret = jf.showOpenDialog(Fr.this);
    public static void main(String h[])
    Fr f = new Fr();
    f.setSize(200,200);
    f.setVisible(true);
    class MyFilter extends FileFilter
    public boolean accept(File f)
    if(!f.isFile())
    return true;
    String s = f.getName();
    if((s.endsWith(".java"))||(s.endsWith(".txt")))
    return true;
    else
    return false;
    public String getDescription()
    return "Java & text files";

  • JFileChooser leaks memory -  HELP

    Hi all,
    I am having difficulty with this. I am using Borland Optimizit. I can see two instances of my object and two instances of JFileChooser.
    See below method: If I browse there is no leak. If I enter the if block it leaks.
    public final void actionPerformed(ActionEvent evt)
    // get the event source
    Object source = evt.getSource();
    // if the event source is the browse button
    if(source == browseButton)
    // if the file chooser has not been instantiated
    if(fileChooser == null)
    fileChooser = new JFileChooser();
    // allow the user to browse the directories
    fileChooser.setCurrentDirectory(new File(Const.DEFAULT_DIRECTORY));
    int result = fileChooser.showOpenDialog(this);
    // if the user selected a file
    if(result == JFileChooser.APPROVE_OPTION)
         // The try block is necessary because the showOpenDialog method
         // returns APPROVE_OPTION if the user clicks open without
         // selecting a file. This will cause the
         // JFileChooser.getSelectedFile method to throw a
         // NullPointerException.
         try
         // set the text in the file name text field to the name of
    // the file selected
         String f = fileChooser.getSelectedFile().getAbsolutePath();
         fileTextField.setText(f);
         catch(NullPointerException e)
         // Do nothing. The file name text field will be left
         // unchanged.
    }// end actionPerformed()

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bjfilechooser+%2B%22memory+leak%22&col=javabugs&col=javaforums&x=24&y=13

  • JFileChooser problems

    Hi
    I've written a small GUI for a college project. I have 2 JFileChoosers one which gets a single file(this works fine), the second I have set to directories only and I want to retrieve a File []. This doesn't seem to work it just returns an empty File []. I've tried using the myJFileChooser.getSelectedFiles method and
    File a = JFileChooser.getSelectedFile();
    File [] b = a.listFiles();
    but neither have worked. Here's my code bellow. Thanks in advance for the help
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class Simple extends JFrame
         private JFileChooser jpegF;
         private JFileChooser gpx;
         private Toolkit toolkit;
         //private File gpxFile;
         //private File [] jpegFolder;
         private JTextField outputFile;
         private JLabel outText;
         public Simple()
              setSize(300,300);
              setTitle("Simple");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              toolkit = getToolkit();
              Dimension size = toolkit.getScreenSize();
              setLocation(size.width/2 - getWidth()/2, size.height/2 - getHeight()/2);
              JPanel panel = new JPanel();
              getContentPane().add(panel);
              outText = new JLabel("Enter Name for route:");
              panel.setLayout(null);
              outputFile = new JTextField();
              jpegF = new JFileChooser();
              jpegF.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              jpegF.setMultiSelectionEnabled(true);
              JButton jpegB = new JButton("Select JPEG Folder");
              JButton gpxB = new JButton("Select GPX File");
              jpegB.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){jpegF.showOpenDialog(null); }});
              gpx = new JFileChooser();
              gpxB.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){gpx.showOpenDialog(null); }});
              //gpxFile = gpx.getSelectedFile();
              //File curDir = jpegF.getSelectedFile();
              //jpegFolder = jpegF.getSelectedFiles();
              //jpegFolder = curDir.listFiles();
              System.out.println("Num of pics: "+ jpegFolder.length);
              JButton run = new JButton("Run");
              run.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){photoTrail.run(gpx.getSelectedFile(),jpegF.getSelectedFiles(), outputFile.getText());}});
              run.setBounds(75, 185, 150, 30);
              gpxB.setBounds(75,25,150,30);
              jpegB.setBounds(75,75,150,30);
              outputFile.setBounds(75,135,150,30);
              outText.setBounds(75,105,150,30);
              panel.add(gpxB);
              panel.add(run);
              panel.add(jpegB);
              panel.add(outputFile);
              panel.add(outText);
              }

    This works fine for me, and print the selected directories.
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setMultiSelectionEnabled(true);
    int retVal = chooser.showOpenDialog(frame);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        File[] files = chooser.getSelectedFiles();
        for (File f : files)
            System.out.println(f);
    }If you want further help post a Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the problem.

  • JFileChooser() out of order

    hi i tried to open & save file through JFileChooser()
    Both Dialogs opened but when i select to open/save file i got file name with path but no file open/save
    plz tell sth good as i have tried
    FileReader()
    FileWriter()
    thanx

    Hi,,
    JFileChooser just returns the path to a file. You can open a file as follows.
    try
    //assume JFileChooser has been inited
    File f = jFileChooser.getSelectedFile();
    FileInputStream fis = new FileInputStream(f.getAbsolutPath());
    byte buff = new byte[fis.available()];
    int readState = fis.read(byte,o,fis.available());
    String text = new String(buff);
    catch(Exception e) { // handle }
    Hope this helps.. Likewise, for Save, you have to write to a file using the path that is returned by the FileChooser

  • Not able to load objects

    I have written code to load in an object but this keeps giving me exceptions when i run the code to try and display the data from the object read in. My code is below:
    Thanks
    //--- cFaceRecGUIMain.java ---
    //--- Edmund Smith 23/08/04 ---
    //--- The GUI for the face recognition sofware contains buttons and ---
    //--- display area for an image of a face ---
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class cFaceRecGUIMain extends JFrame implements ActionListener {
    //Create menu bar items
    private JMenuItem jmiLoadPicture, jmiExit, jmiEdit;
    //Recognize Button
    private JButton jbtRecognize;
    //Labels with info about picture
    private String lblName, lblDOB, lblNI, lblStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    JFileChooser jFileChooser = new JFileChooser();
    //BitmapReader
    //cGetBytes getBytes = new cGetBytes();
    //Face database
    cFaceRecData faceDatabase = new cFaceRecData();
    //Set default window sizes
    final int xSize = 600;
    final int ySize = 400;
    //Array for holding pixels
    int pixels[];
    //Labels for menu items
    final String lbljmiLoadPicture = "Load Picture for recogniton";
    final String lbljmiExit = "Exit";
    final String lbljmiEdit = "Edit face database";
    //Create the frame to enter details about people
    cFaceRecGUIEDetails enterDetailsFrame = new cFaceRecGUIEDetails();
    //BitmapReader
    cGetBytes getImageBytes = new cGetBytes();
    //Main method
    public static void main(String[] args)
    cFaceRecGUIMain programFrame = new cFaceRecGUIMain();
    programFrame.pack();
    programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    programFrame.setTitle("Face Recognizer");
    programFrame.setSize(600, 400);
    programFrame.setVisible(true);
    //Constructor
    public cFaceRecGUIMain() {
    //Initialize menu bar
    JMenuBar jmb = new JMenuBar();
    setJMenuBar(jmb);
    //Add menus
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    jmb.add(fileMenu);
    JMenu faceMenu = new JMenu("Face");
    fileMenu.setMnemonic('A');
    jmb.add(faceMenu);
    JMenu helpMenu = new JMenu("Help");
    fileMenu.setMnemonic('H');
    jmb.add(helpMenu);
    //Add menu items
    fileMenu.add(jmiLoadPicture =
    new JMenuItem(lbljmiLoadPicture, 'L'));
    fileMenu.addSeparator();
    fileMenu.add(jmiExit = new JMenuItem(lbljmiExit, 'X'));
    faceMenu.add(jmiEdit = new JMenuItem(lbljmiEdit, 'E'));
    //Set keyboard accelerators
    jmiExit.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
    jmiLoadPicture.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
    //Set up new panel
    imagePanel.setBorder(new TitledBorder("Face"));
    //Lay components on panel
    imagePanel.setImageIcon(new ImageIcon("C:/Documents and Settings/" +
    "Edmund Smith/My Documents/aface.bmp"));
    imagePanel.add(jbtRecognize = new JButton("Recognize"),
    BorderLayout.SOUTH);
    setTitle("Face Recognizer");
    //Labels to hold info
    JPanel lblsAboutImagePanel = new JPanel();
    lblsAboutImagePanel.setBorder(new TitledBorder("Details"));
    lblsAboutImagePanel.setLayout(new GridLayout(4, 2));
    lblsAboutImagePanel.add(new JLabel("Name"));
    lblsAboutImagePanel.add(new JLabel(lblName));
    lblsAboutImagePanel.add(new JLabel("DOB"));
    lblsAboutImagePanel.add(new JLabel(lblDOB));
    lblsAboutImagePanel.add(new JLabel("National insurance number"));
    lblsAboutImagePanel.add(new JLabel(lblNI));
    lblsAboutImagePanel.add(new JLabel("Staff ID"));
    lblsAboutImagePanel.add(new JLabel(lblStaffID));
    //Add the different panels to the frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(imagePanel, BorderLayout.WEST);
    getContentPane().add(lblsAboutImagePanel, BorderLayout.CENTER);
    //Register listeners
    jmiExit.addActionListener(this);
    jmiLoadPicture.addActionListener(this);
    jmiEdit.addActionListener(this);
    //Create the frame where you can enter the details of a person
    enterDetailsFrame.pack();
    enterDetailsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    enterDetailsFrame.setTitle("Set up database");
    enterDetailsFrame.setSize(xSize, ySize);
    class edfClosingListener extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    //Check to see if the record has been changed
    if (enterDetailsFrame.isRecordModified)
    JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    if (enterDetailsFrame.newPeople.size() > 0)
    //create a temporary array to store the new people
    person[] newPersons = new
    person[enterDetailsFrame.newPeople.size()];
    //Copy the people in the vector to the array
    person tempPerson;
              for (int i = 0; i < newPersons.length; i++)
    tempPerson =
    (person)enterDetailsFrame.newPeople.elementAt(i);
    newPersons.path = tempPerson.path;
    newPersons[i].personsName = tempPerson.personsName;
    newPersons[i].personsDOB = tempPerson.personsDOB;
    newPersons[i].personsNI = tempPerson.personsNI;
    newPersons[i].personsStaffID = tempPerson.personsStaffID;
    //Create new database
    allPeople outPeople =
    new allPeople(enterDetailsFrame.peopleInfo, newPersons);
    //Save the database with the added records
    enterDetailsFrame.faceDatabase.saveDatabase(outPeople);
    else
    //Save the database with the same number of records
    enterDetailsFrame.faceDatabase.saveDatabase(
    enterDetailsFrame.peopleInfo);
    //Set the actions to happen when windows are closed
    enterDetailsFrame.addWindowListener(new edfClosingListener());
    closeWindow closeMainFrame = new closeWindow();
    addWindowListener(closeMainFrame);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem) {
    if (lbljmiExit.equals(actionCommand))
    System.exit(0);
    else if (lbljmiLoadPicture.equals(actionCommand))
    open();
    else if (lbljmiEdit.equals(actionCommand)) {
    enterDetailsFrame.setVisible(true);
    //No records have been modified
    enterDetailsFrame.isRecordModified = false;
    //Open a file
    private void open() {
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    try {
    //Get the file name
    String fileName = jFileChooser.getSelectedFile().getPath();
    //Display the image
    ImageIcon imagei = new ImageIcon(fileName);
    imagePanel.setImageIcon(imagei);
    //Set size of array for holiding bytes in the image
    pixels =
    new int[51 * 55];
    //Get the pixels
    // getBytes.getBMPImage(new FileInputStream(new File(fileName)), pixels);
    catch (Exception e) {
    System.out.print(e);
    class ImagePanel extends JPanel {
    //Label to hold the face
    private JLabel jlblFace = new JLabel();
    //Constructor
    public ImagePanel() {
    setLayout(new BorderLayout());
    add(jlblFace, BorderLayout.CENTER);
    //Set image and show it
    public void setImageIcon(ImageIcon icon) {
    jlblFace.setIcon(icon);
    Dimension dimension =
    new Dimension(icon.getIconWidth(), icon.getIconHeight());
    jlblFace.setPreferredSize(dimension);
    //--- cFaceRecGUIEDetails.java ---
    //--- Edmund Smith 06/10/04 ---
    //--- Allows the user to enter details about a person, view the ---
    //--- database and add people to the database ---
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    class cFaceRecGUIEDetails extends JFrame implements KeyListener, ActionListener
    //Buttons to navigate the database
    private JButton jbtPrevious, jbtNext;
    //Button to load a face
    private JButton jbtLoadFace;
    //Fields to display info about the person
    private JTextField jtfName, jtfDOB, jtfNI, jtfStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    private JFileChooser jFileChooser = new JFileChooser();
    //Variable to tell whether record has been modified
    boolean isRecordModified = false;
    //Tells which record current being veiwed/changed
    int currentRecord = 0;
    //Stores new people to be added to database
    Vector newPeople = new Vector();
    //Face database
    cFaceRecData faceDatabase;
    public allPeople peopleInfo;
    //Default Constructor
    public cFaceRecGUIEDetails()
    //Get the face database
    faceDatabase = new cFaceRecData();
    peopleInfo = faceDatabase.restoreDatabase();
    //Panel to hold two buttons to navigate the database
    JPanel jpButtons = new JPanel();
    //Add navigation buttons to panel
    jpButtons.setLayout(new FlowLayout());
    jpButtons.add(jbtPrevious = new JButton());
    jpButtons.add(jbtNext = new JButton());
    //Set button text
    jbtPrevious.setText("<");
    jbtNext.setText(">");
    //Panel to hold details about the person
    JPanel jpDetails = new JPanel();
    jpDetails.setBorder(new TitledBorder("Details"));
    jpDetails.setLayout(new GridLayout(4, 2));
    jpDetails.add(new JLabel("Name"));
    jpDetails.add(jtfName = new JTextField());
    jpDetails.add(new JLabel("DOB"));
    jpDetails.add(jtfDOB = new JTextField());
    jpDetails.add(new JLabel("National insurance number"));
    jpDetails.add(jtfNI = new JTextField());
    jpDetails.add(new JLabel("StaffID"));
    jpDetails.add(jtfStaffID = new JTextField());
    try
    jtfName.setText(peopleInfo.people[currentRecord].personsName);
    /* jtfDOB.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsDOB));
    jtfNI.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsNI));
    jtfStaffID.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsStaffID));*/
    catch (Exception e)
    System.out.print(e);
    imagePanel.setBorder(new TitledBorder("Face"));
    imagePanel.add(jbtLoadFace = new JButton("Load Face"));
    //Main body panel
    JPanel jpBody = new JPanel();
    jpBody.add(imagePanel, BorderLayout.WEST);
    jpBody.add(jpDetails, BorderLayout.CENTER);
    //Place panels on frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(jpBody, BorderLayout.CENTER);
    getContentPane().add(jpButtons, BorderLayout.SOUTH);
    //Register listeners
    jbtLoadFace.addActionListener(this);
    jbtPrevious.addActionListener(this);
    jbtNext.addActionListener(this);
    //jtfName.addKeyListener(this);
    jtfDOB.addKeyListener(this);
    jtfNI.addKeyListener(this);
    jtfStaffID.addKeyListener(this);
    public void actionPerformed(ActionEvent e)
    boolean goOn = false;
    if (e.getSource() == jbtLoadFace)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    if (e.getSource() == jbtPrevious || e.getSource() == jbtNext)
    if (isRecordModified == true)
    int result = JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    switch (result)
    case JOptionPane.YES_OPTION:
    saveRecordChanges();
    goOn = true;
    break;
    case JOptionPane.NO_OPTION:
    goOn = true;
    break;
    if (goOn == true)
    //If user has not cancelled move to another record
    if (e.getSource() == jbtPrevious)
    moveForwardToRecord(true);
    else
    moveForwardToRecord(false);
    public void saveRecordChanges()
    boolean alreadyInDatabase = false;
    //Put the values in the field into the database
    try
    if (currentRecord < peopleInfo.people.length)
    alreadyInDatabase = true;
    peopleInfo.people[currentRecord].personsName =
    jtfName.getText();
    peopleInfo.people[currentRecord].personsDOB =
    Integer.parseInt(jtfDOB.getText());
    peopleInfo.people[currentRecord].personsNI =
    Integer.parseInt(jtfNI.getText());
    peopleInfo.people[currentRecord].personsStaffID =
    Integer.parseInt(jtfStaffID.getText());
    catch (Exception e)
    System.out.print(e);
    if (alreadyInDatabase = false)
    newPeople.add(new person("", jtfName.getText(),
    Integer.parseInt(jtfDOB.getText()),
    Integer.parseInt(jtfNI.getText()),
    Integer.parseInt(jtfStaffID.getText())));
    public void moveForwardToRecord(boolean forward)
    isRecordModified = false;
    setTitle("Set up datbase");
    if (forward)
    else
    public void keyPressed(KeyEvent e)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    public void keyReleased(KeyEvent e) {
    public void keyTyped(KeyEvent e) {
    //Open a file
    private void open()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    String fileName = jFileChooser.getSelectedFile().getPath();
    imagePanel.setImageIcon(new ImageIcon(fileName));
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    //--- cFaceRecData.java ---
    //--- Edmund Smith 18/11/04 ---
    //--- Stores and retrives info about a person and their face ---
    import java.io.*;
    import java.util.*;
    class cFaceRecData
    //The location of the database
    final String dbPath = "C:/Documents and Settings/" +
    "Edmund Smith/My Documents/fdatabase.dat";
    //The data
    allPeople inPeople;
    //Saves the file
    void saveDatabase(allPeople outPeople)
    try
    //Object output stream
    ObjectOutputStream out =
    new ObjectOutputStream(new FileOutputStream(dbPath));
    //Write the object
    out.writeObject(outPeople);
    //Close the object output stream
    out.close();
    catch (IOException ex)
    System.out.println(ex);
    //Opens the file
    allPeople restoreDatabase()
    try
    //Object input steam
    ObjectInputStream in =
    new ObjectInputStream(new FileInputStream(dbPath));
    //Get the database
    inPeople = (allPeople)in.readObject();
    //Close the input stream
    in.close();
    catch (IOException ex)
    System.out.println(ex);
    catch (ClassNotFoundException ex)
    System.out.println(ex);
    //Return the database
    return inPeople;
    //Holds the info about a person
    class person
    //Stores the location of the image on disk
    String path;
    //Stores the name of a person
    String personsName;
    //Stores the dob of a person, their NI no, and employee ID
    int personsDOB, personsNI, personsStaffID;
    //Default constructor
    public person(String inPath, String inName, int inDOB, int inNI,
    int inStaffID)
    //Stores the values which passed in
    path = inPath;
    personsName = inName;
    personsDOB = inDOB;
    personsNI = inNI;
    personsStaffID = inStaffID;
    //The database
    class allPeople
    person[] people;
    int numPeople;
    //Default constructor
    public allPeople(person[] persons)
    //Create the array to hold the people
    people = new person[persons.length];
    for (int i = 0; i < persons.length; i++)
    people[i] = new person(persons[i].path,
    persons[i].personsName,
    persons[i].personsDOB,
    persons[i].personsStaffID,
    persons[i].personsNI);
    //Updates the database
    public allPeople(allPeople thePeople, person[] persons)
    //Create the array to hold the people
    int totalPeople = thePeople.people.length + persons.length;
    people = new person[totalPeople];
    for (int i = 0; i < totalPeople; i++)
    if (i < thePeople.people.length)
    people[i] = new person(thePeople.people[i].path,
    thePeople.people[i].personsName,
    thePeople.people[i].personsDOB,
    thePeople.people[i].personsStaffID,
    thePeople.people[i].personsNI);
    else
    people[i] = new person(persons[i].path,
    persons[i].personsName,
    persons[i].personsDOB,
    persons[i].personsStaffID,
    persons[i].personsNI);

    When posting code to the forum, please use the code button.
    Also, post the exception message and indicate the line that gives the error.

  • Outputting to a text file.

    Hey guys and gals,
    Im doing a program for work that is a form you type in, select save and it stores the data to a file. I have 2 problems. FIRST i need to know how to change the font. SECOND how do i put in tabs, returns using out.write(...);
    The goal is to output a form to a text file that can be saved, printed. Right now it all runs together in the .txt or .doc file that it makes.
    thanks bunches
    package hrform;
    // imports
    import java.awt.Font;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.event.*;
    import java.awt.Font;
    public class form extends JFrame implements ActionListener
    //declare text boxes, buttons, radiobuttons
    private JRadioButton jrbThree, jrbSix;
    //private ButtonGroup btg = new ButtonGroup();
    private JButton jbtSave;
    private JTextField jtfEmployee, jtfDateofhire;
    private JTextField jtfDatecompleted, jtfJobtitle;
    private JFileChooser jFileChooser = new JFileChooser();
    private JTextField jtfCurrentpay, jtfDateofincrease, jtfAmount;
    private JTextField jtfAcceptible, jtfExemplary, jtfImprovement, jtfDependability;
    private JTextField jtfPersonality, jtfGoals;
    /** Main Method*/
    public static void main(String [] args)
    form frame = new form();
    //frame.setDefault(closeOperation(JFrame.EXIT_ON_CLOSE));
    frame.setSize(800,580);
    frame.setVisible(true);
    /**Default Constructor*/
    public form()
    Color defaultColor = Color.red;
    setTitle("Employee Evaluation Form");
    JPanel p1 = new JPanel();
    p1.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
    setColor (Color.lightGray);
    p1.add(new JLabel("Employee Name:"));
    p1.add(jtfEmployee = new JTextField(11));
    p1.add(new JLabel("Date of Hire:"));
    p1.add(jtfDateofhire = new JTextField(10));
    p1.add(new JLabel("Date Completed by Employee"));
    p1.add(jtfDatecompleted = new JTextField(10));
    // panel p2 for radio buttons
    JPanel p2 = new JPanel();
    p2.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
    p2.add(new JLabel("Job Title: "));
    p2.add(jtfJobtitle = new JTextField(20));
    p2.add(new JLabel("Current Rate of Pay"));
    p2.add(jtfCurrentpay = new JTextField(10));
    p2.add(new JLabel("Date of Last Increase: "));
    p2.add(jtfDateofincrease = new JTextField(8));
    p2.add(new JLabel("Amount of Last Increase: "));
    p2.add(jtfAmount = new JTextField(70));
    p2.add(new JLabel("Has displayed an acceptable level of performance these areas: "));
    p2.add(jtfAcceptible = new JTextField(70));
    p2.add(new JLabel("Has shown EXEMPLARY performace in these areas: "));
    p2.add(jtfExemplary = new JTextField(70));
    p2.add(new JLabel("Areas for Improvement: "));
    p2.add(jtfImprovement = new JTextField(70));
    p2.add(new JLabel("Dependability(Focus on attendance, punctuality, and attentiveness): "));
    p2.add(jtfDependability = new JTextField(70));
    p2.add(new JLabel("Personality(Focus on ability to work for and with others): "));
    p2.add(jtfPersonality = new JTextField(70));
    p2.add(new JLabel("GOALS FOR NEXT QUARTER: "));
    p2.add(jtfGoals = new JTextField(70));
    p2.add(jbtSave = new JButton());
    jbtSave.setText("Save");
    //set default directory
    jFileChooser.setCurrentDirectory(new File("F:WPDOCS/Personne"));
    //Set flowlayout for the fram
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(p1, BorderLayout.NORTH);
    getContentPane().add(p2, BorderLayout.CENTER);
    // Register Listeners
    jbtSave.addActionListener(this);
    /** Handle event */
    public void actionPerformed(ActionEvent e)
    String actionCommand= e.getActionCommand();
    if (e.getSource() instanceof JButton)
    if ("Save".equals(actionCommand))
    Save();
    /** Save file*/
    private void Save()
    if(jFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
    Save(jFileChooser.getSelectedFile());
    private void Save(File file)
    try
    Font helv = new Font("Helvetica", Font.BOLD, 16);
    Font courier = new Font("Courier", Font.BOLD, 24);
    Color defaultColor = Color.cyan;
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    out.write(new JLabel(" ").getText().getBytes());
    //out.setFont("SansSerif",Font.BOLD,14);
    out.write(new JLabel("TMC Orthopedic - EMPLOYEE PERFORMANCE EVALUATION").getText().getBytes());
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Employee Name: ").getText().getBytes());
    byte[] b = (jtfEmployee.getText()).getBytes();
    out.write(b,0,b.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Date of Hire: ").getText().getBytes());
    out.write(new JLabel().getText().getBytes());
    byte[] c = (jtfDateofhire.getText()).getBytes();
    out.write(c,0,c.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Date Completed by Employee: ").getText().getBytes());
    //out.writeChars(\n);
    byte[] d = (jtfDatecompleted.getText().getBytes());
    out.write(d,0,d.length);
    byte[] e = (jtfJobtitle.getText().getBytes());
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Job Title: ").getText().getBytes());
    out.write(e,0,e.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Current Pay: ").getText().getBytes());
    byte[] f = (jtfCurrentpay.getText().getBytes());
    out.write(f,0,f.length);
    out.write(new JLabel(" ").getText().getBytes());
    byte[] g = (jtfDateofincrease.getText().getBytes());
    out.write(new JLabel("Date of Last Increase: ").getText().getBytes());
    out.write(g,0,g.length);
    out.write(new JLabel(" ").getText().getBytes());
    byte[] h = (jtfAmount.getText().getBytes());
    out.write(new JLabel("Amount Of Last Increase").getText().getBytes());
    out.write(h,0,h.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Has displayed an acceptable level of performance in these areas: ").getText().getBytes());
    byte[] i = jtfAcceptible.getText().getBytes();
    out.write(i,0,i.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Has displayed an exemplary level of performance in the following areas: ").getText().getBytes());
    byte[] j = jtfExemplary.getText().getBytes();
    out.write(j,0,j.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Areas for improvement").getText().getBytes());
    byte[] k = jtfImprovement.getText().getBytes();
    out.write(k,0,k.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Dependability(Focus on attendance, punctuality, and attentiveness): ").getText().getBytes());
    byte[] l = jtfDependability.getText().getBytes();
    out.write(l,0,l.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("Personality (Forcus on ability to work for and with others): ").getText().getBytes());
    byte[] m = jtfPersonality.getText().getBytes();
    out.write(m,0,m.length);
    out.write(new JLabel(" ").getText().getBytes());
    out.write(new JLabel("GOALS FOR NEXT QUARTER: ").getText().getBytes());
    byte[] n = jtfGoals.getText().getBytes();
    out.write(n,0,n.length);
    out.close();
    catch(IOException ex)

    I tried both of these and i get an error.
    "form.java": Error #: 300 : method write(java.lang.String) not found in class java.io.BufferedOutputStream at line 136, column 15
    Do i need to include something else???
    Thanks
    To insert a tab, use out.write("\t"). To insert a newline (crossplatform), use out.write(System.getProperty("line.separator")).
    HTH!
    :o)

  • How can i plot a histogram with using the results of Line Length

    PLS HELP.How can i prepare a histogram with using the results of line length code(It is somewhere in the middle).
    This is a final exam take-home question. I would appreciate if you can help?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.text.*;
    import java.io.File;
    public class WordAnalyser extends JFrame implements ActionListener
    private JMenuItem jmiAc, jmiSil, jmiCikis, jmiAnaliz, jmiHakkinda, jmiKullanim;
    private JTextArea jta1, jta2;
    private JFileChooser jFileChooser = new JFileChooser();
    File hafizada;
    File aktarilan = new File("Sonuc.txt");
    // Main method
    public static void main(String[] args)
    WordAnalyser frame = new WordAnalyser(); /* Ana ekran olusturulur */
    frame.setSize(400, 300); /* Degerleri belirlenir */
    frame.setVisible(true); /* Gorunebilirligi ayarlanir */
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public WordAnalyser()
    setTitle("Serkan Ozgen Dosya Inceleme Programina Hos Geldiniz");
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    JMenu fileMenu = new JMenu("Dosya");
    fileMenu.setMnemonic('F');
    mb.add(fileMenu);
    JMenu helpMenu = new JMenu("Degerlendirme");
    helpMenu.setMnemonic('H');
    mb.add(helpMenu);
    JMenu kullanimMenu = new JMenu("Kullanim Kilavuzu");
    mb.add(kullanimMenu);     
    fileMenu.add(jmiAc = new JMenuItem("Ac", 'A'));
    fileMenu.add(jmiSil = new JMenuItem("Sil", 'S'));
    fileMenu.add(jmiCikis = new JMenuItem("Cikis", 'C'));
    helpMenu.add(jmiAnaliz = new JMenuItem("Analiz", 'D'));
    helpMenu.add(jmiHakkinda = new JMenuItem("Hakkinda", 'H'));
    kullanimMenu.add(jmiKullanim = new JMenuItem("Kullanim"));     
    getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER);
    getContentPane().add(jta2 = new JTextArea(), BorderLayout.SOUTH);
    jmiAc.addActionListener(this);
    jmiSil.addActionListener(this);
    jmiCikis.addActionListener(this);
    jmiAnaliz.addActionListener(this);
    jmiHakkinda.addActionListener(this);
    jmiKullanim.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem)
    if ("Ac".equals(actionCommand))
    Ac();
    else if ("Sil".equals(actionCommand))
    Sil();
    else if ("Cikis".equals(actionCommand))
    System.exit(0);
    else if ("Analiz".equals(actionCommand))
    sayim();
    else if ("Hakkinda".equals(actionCommand))
    JOptionPane.showMessageDialog(this,
    "!!!! Bu program text analizi gerceklestirir. Her hakki saklidir SERKAN OZGEN!!!!",
    "Bu program hakkinda",
    JOptionPane.INFORMATION_MESSAGE);
    else if ("Kullanim".equals(actionCommand))
         JOptionPane.showMessageDialog(this,
         " Ilk once dosya menusunden Ac i tiklayarak analiz etmek istediginiz Dosyayi seciniz (Lutfen uzantisi *.txt \nveya *.log olsun). Daha sonra Degerlendirme menusunden analizi tiklarsaniz dosyanizda kac adet rakam, harf, \ncumle ve kelime oldugunu gorebilirsiniz. Simdiden kolay gelsin",
         "Programin kullanim detaylari",
         JOptionPane.INFORMATION_MESSAGE);
    private void Ac()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    hafizada = jFileChooser.getSelectedFile();
    Ac(hafizada);
    // Acilan Dosyayi ana ekranda gostermeye yariyan bir method
    private void Ac(File file)
    try
    // Acilan dosyayi okuma ve ana ekranda gosterme
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta1.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    // Temizle tusunun hangi ekranlara etki edecegini secme
    private void Sil()
    jta1.setText("");
    jta2.setText("");
    private void sayim()
    int buff;
    int sayac = 0;
    int Cumleler = 0;
    int Kelimeler = 0;
    int Karakterler = 0;
    int Satirlar = 0;
    int Rakamlar = 0;     
    boolean start = true;
    int linenum = 0;     
    try
    FileInputStream instream = new FileInputStream(hafizada);
    FileOutputStream outstream = new FileOutputStream(aktarilan);
         BufferedReader infile = new BufferedReader(new InputStreamReader(new FileInputStream(hafizada)));
    PrintStream out = new PrintStream(outstream);
         out.println("---Kelime Avcisinin Sonuclari---");
         String line = infile.readLine();
         while (line != null){
         int len = line.length();
         linenum++;
         line = infile.readLine();
         out.println("Line Length :"     + linenum + "\t" +len);
    while ((buff=instream.read()) != -1)
    switch((char)buff)
    case '?': case '.': case '!': /* Eger "?", "." veya "!" gorurse program cumleleri ve kelimeleri arttirir*/
    if (start == false)
    Cumleler++;
    Kelimeler++;
    start = true;
    break;
    case ' ': case '\t': case ',': case ';': case ':': case'\"': case'\'': /* Eger /t,;:\ ve \" bu isarteleri goruruse program kelimeleri arttirir */
    if (start == false)
    Kelimeler++;
    start = true;
    break;
              case 'n': case '\n': /* Eger \n gorurse satirlari arttirir */
              if (start == false)
                   Satirlar++;
                   Kelimeler++;
                   start = true;
              break;
    default:
    if (((char)buff >= 'a' && (char)buff<='z')|| /*a-z, A-Z veya - degerlerini gorurse karakterler arttirilir */
    ((char)buff >= 'A' && (char)buff<='Z')||
    ((char)buff == '-'))
    Karakterler++;
    if ((Kelimeler % 50) == 49)
    if (start == true)
                   out.println();     
    out.print((Kelimeler+1) + " ");
    out.print((char)buff);
    start = false;
              if ((char)buff >='0' && (char)buff <='9') {  /* 0-9 gorurse rakamlari arttiri */
                   Rakamlar++; }
    }// switch
         }//while
    instream.close();
    out.println();
    out.println();
    out.println("Karakter sayisi: " + Karakterler);
         out.println("Kelime sayisi: " + Kelimeler);
    out.println("Cumle sayisi: " + Cumleler);
         out.println("Satir sayisi: "+ Satirlar);
         out.println("Rakam sayisi: "+ Rakamlar);
    outstream.close();
    try
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(aktarilan));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta2.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    catch (Exception e)
    System.out.println(e);
    }

    Why is it that you're not interested in IOExceptions?
    catch (IOException ex)
    } Empty catch blocks is a hallmark of foolish Java code. At least print out the stack trace.
    %

  • How can i add the first to the following

    String line = infile.readLine();
    int linenum = 0;
    while (line != null) {
    int len = line.length();
    linenum++;
    System.out.println(linenum + "\t" + len);
    line = infile.readLine();
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.text.*;
    public class WordAnalyser extends JFrame implements ActionListener
    // Menu items Open, Clear, Exit, WordCount, About
    private JMenuItem jmiOpen, jmiClear, jmiExit, jmiWordCount, jmiAbout;
    // Text area for displaying and editing text files
    private JTextArea jta1, jta2;
    // Status label for displaying operation status
    private JLabel jlblStatus;
    // File dialog box
    private JFileChooser jFileChooser = new JFileChooser();
    File infile;
    File outfile = new File("OutFile.txt");
    DecimalFormat numForm1 = new DecimalFormat("000");
    DecimalFormat numForm2 = new DecimalFormat("0.00");
    // Main method
    public static void main(String[] args)
    WordAnalyser frame = new WordAnalyser();
    frame.setSize(500, 400);
    frame.center();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public WordAnalyser()
    setTitle("Word Analyser");
    // Create a menu bar mb and attach to the frame
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    // Add a "File" menu in mb
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    mb.add(fileMenu);
    // Add a "Help" menu in mb
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic('H');
    mb.add(helpMenu);
    // Create and add menu items to the menu
    fileMenu.add(jmiOpen = new JMenuItem("Open", 'O'));
    fileMenu.add(jmiClear = new JMenuItem("Clear", 'C'));
    fileMenu.addSeparator();
    fileMenu.add(jmiExit = new JMenuItem("Exit", 'E'));
    helpMenu.add(jmiWordCount = new JMenuItem("Word Count", 'W'));
    helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
    // Set default directory to the current directory
    jFileChooser.setCurrentDirectory(new File("."));
    // Set BorderLayout for the frame
    getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER);
    getContentPane().add(jta2 = new JTextArea(), BorderLayout.EAST);
    getContentPane().add(jlblStatus = new JLabel(), BorderLayout.SOUTH);
    // Register listeners
    jmiOpen.addActionListener(this);
    jmiClear.addActionListener(this);
    jmiExit.addActionListener(this);
    jmiWordCount.addActionListener(this);
    jmiAbout.addActionListener(this);
    public void center()
    // Get the screen dimension
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;
    // Get the frame dimension
    Dimension frameSize = this.getSize();
    int x = (screenWidth - frameSize.width)/2;
    int y = (screenHeight - frameSize.height)/2;
    // Determine the location of the left corner of the frame
    if (x < 0)
    x = 0;
    frameSize.width = screenWidth;
    if (y < 0)
    y = 0;
    frameSize.height = screenHeight;
    // Set the frame to the specified location
    this.setLocation(x, y);
    // Handle ActionEvent for menu items
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem)
    if ("Open".equals(actionCommand))
    open();
    else if ("Clear".equals(actionCommand))
    clear();
    else if ("Exit".equals(actionCommand))
    System.exit(0);
    else if ("Word Count".equals(actionCommand))
    word_count();
    else if ("About".equals(actionCommand))
    JOptionPane.showMessageDialog(this,
    "Program performs text analysis",
    "About This Program",
    JOptionPane.INFORMATION_MESSAGE);
    // Open file
    private void open()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    infile = jFileChooser.getSelectedFile();
    open(infile);
    // Open file with the specified File instance
    private void open(File file)
    try
    // Read from the specified file and store it in jta
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta1.append(new String(b, 0, b.length));
    in.close();
    // Display the status of the Open file operation in jlblStatus
    jlblStatus.setText(file.getName() + " Opened");
    catch (IOException ex)
    jlblStatus.setText("Error opening " + file.getName());
    // Clear all display areas
    private void clear()
    jta1.setText("");
    jta2.setText("");
    jlblStatus.setText("");
    // Perform word analysis with specified File instance
    private void word_count()
    int buff; // for reading 1 char at a time
    int count = 0;
    int sentences = 0;
    int words = 0;
    int chars = 0;
    boolean start = true;
    try
    FileInputStream instream = new FileInputStream(infile);
    FileOutputStream outstream = new FileOutputStream(outfile);
    // convert FileOutputSream object to PrintStream object for easier output
    PrintStream out = new PrintStream(outstream);
    out.println("---Word Analysis---");
    while ((buff=instream.read()) != -1)
    switch((char)buff)
    case '?': case '.': case '!':
    if (start == false)
    sentences++;
    words++;
    start = true;
    break;
    case ' ': case '\t': case '\n': case ',': case ';': case ':': case'\"': case'\'':
    if (start == false)
    words++;
    start = true;
    break;
    default:
    // 3-digit integer format
    if (((char)buff >= 'a' && (char)buff<='z')||
    ((char)buff >= 'A' && (char)buff<='Z')||
    ((char)buff >= '0' && (char)buff <= '9')||
    ((char)buff == '-'))
    chars++;
    if ((words % 50) == 49)
    if (start == true)
    out.println();
    out.print(numForm1.format(words+1) + " ");
    out.print((char)buff);
    start = false;
    }// switch
    }//while
    instream.close();
    out.println();
    out.println();
    out.println("Number of characters: " + chars);
    out.println("Number of words: " + words);
    out.println("Number of sentences: " + sentences);
    out.print("Number of words per sentence: ");
    // cast integers to float, then add 0.005 to round up to 2 decimal places
    out.println(numForm2.format((float)words/sentences));
    outstream.close();
    try
    //Read from the output file and display in jta
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(outfile));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta2.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    jlblStatus.setText("Error opening " + outfile.getName());
    catch (Exception e)
    System.out.println(e);
    }

    Do you want to add the code
    String line = infile.readLine();
    int linenum = 0;
    while (line != null) {
    int len = line.length();
    linenum++;
    System.out.println(linenum + "\t" + len);
    line = infile.readLine();
    }to your rest of the program?

  • Getting the entire file path using "Browse button"

    Hi All,
    I searched the forum for the solution, but did not find it there.
    I am using JFileChooser to browse and select a file.
    then i have to pass this file as and argument to another java program where it reads the file and sends it to the server.
    Now what i actually want is, when the file is selected i want to get the file nam along with the path i.e. C:/temp/temp.doc
    instead i am getting only temp.doc.
    I tried setting the JFileChooser mode as DIRECTORIES_ONLY. But that gives me only C:/temp and not the file name.
    If i set it as FILES_AND_DIRECTORIES it again gives me only the file name and not the path.
    pls. help me. its urgent.
    thanks

    What is wrong with JFileChooser.getSelectedFile()? From the returned File object you can get the canonical name which sounds to be what you want.

  • Plz help me out with class loader problem

    hai forum members,
    I have a code which loads class files from local disk.
    It works fine with some classes ,
    But i get this exception when i am selecting certain other class files
    I am using jdeveloper.
    Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: Filter (wrong name: project1/Filter)
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at com.jutframe.JavaUnitTester.selectClass_actionPerformed(JavaUnitTester.java:449)
         at com.jutframe.JavaUnitTester$7.actionPerformed(JavaUnitTester.java:338)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1766)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
                        JFileChooser jfilechooser=new JFileChooser();
                        Filterclass filter=new Filterclass();
                        //Set selection mode for file chooser
                        jfilechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        //set file filter
                        jfilechooser.setFileFilter(filter);
                        int returnVal = jfilechooser.showOpenDialog(this);
                        if(returnVal == JFileChooser.APPROVE_OPTION)
                            try
                                    String str = jfilechooser.getSelectedFile().getName();
                                    String parent=jfilechooser.getSelectedFile().getParent();
                                     // Create a File object on the root of the directory containing the class file
                                     File file = new File(parent);
                                     // Convert File to a URL
                                     URL url = file.toURL();         
                                     URL[] urls = new URL[]{url};
                                     // Create a new class loader with the directory
                                     ClassLoader cl = new URLClassLoader(urls);
                                     StringTokenizer st = new StringTokenizer(str,".");
                                     String s = st.nextToken ();
                                     Class c = cl.loadClass(s);  //ERROR IS SHOWN IN THIS PARTICULAR LINE
                                     Object instance=c.newInstance();
    --------------------------------------------please help me trace my mistake.
    thank you all.

    i think the problem that i have set a particular class path for my class files and my application loads files from that alone.
    So plz tell me if theres any way to access the class path of a particular file dynamically?
    regards

  • In Need Of Divine Intervention

    Need some help with this. I can't seem to get the "browse" button to browse my PC for images in the Upload frame. The "Cancel" button is closing the entire programme instead of just the Upload frame.
    Anyone know the problem? i just started java bout 3 months ago and still a noob at it =(
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.List;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.FileImageInputStream;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class PhotoAlbum extends JFrame
      implements ActionListener
      // Menu items Upload, Save, exit, and About
      private JMenuItem jmiUpload, jmiSave,jmiExit, jmiAbout, ttUpload;
      private JButton jbtnEditlabel , jbtnSavelabel,browse,cancel;
      // Text area for displaying and editing text files
         private JPanel jta,over;
         Image image;     
         SlidePanel slidePanel;     
         JComboBox slides;
         JFrame f;
         JFileChooser fileChooser;
      // Status label for displaying operation status
      private JLabel jlblStatus = new JLabel();
      // Scrolling
      private JScrollPane scrollPane = new JScrollPane();
      // File dialog box
      private JFileChooser jFileChooser = new JFileChooser();
      // Radio Buttons
      private JRadioButtonMenuItem jmiSlideshow , jmiThumbnail;
      //JPanels
      private JPanel head , body , low;
      /**Main method*/
      public static void main(String[] args)
           JFrame.setDefaultLookAndFeelDecorated(true);
        PhotoAlbum frame = new PhotoAlbum();
        frame.setSize(600, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
         frame.setLocationRelativeTo( null );
      public PhotoAlbum()
        setTitle("Photo Library");
        // Create a menu bar mb and attach to the frame
        JMenuBar mb = new JMenuBar();
        setJMenuBar(mb);
        // Add a "File","Help" and "View" menu in mb
        JMenu fileMenu = new JMenu("File");
        mb.add(fileMenu);
        JMenu viewMenu = new JMenu("View");
         mb.add(viewMenu);
         JMenu helpMenu = new JMenu("Help");
         mb.add(helpMenu);
              JPanel jta = new JPanel();
         //Setting a scrolling pane for jta
         jta.setOpaque( false );//making jta transparent
         jta.setPreferredSize( new Dimension(1200, 1200) );
        // Create and add menu items to the menu
        fileMenu.add(ttUpload = new JMenuItem("Upload"));
        fileMenu.add(jmiSave = new JMenuItem("Save"));
        fileMenu.addSeparator();
        fileMenu.add(jmiExit = new JMenuItem("Exit"));
        helpMenu.add(jmiAbout = new JMenuItem("About"));
    //    group.add(jmiThumbnail);group.add(jmiSlideshow);
        viewMenu.add(jmiThumbnail = new JRadioButtonMenuItem("Thumbnail"));
        viewMenu.add(jmiSlideshow = new JRadioButtonMenuItem("Slideshow"));
        getContentPane().add(scrollPane);
         //  "Low Panel"with a white background and placing "jbtnEditlabel" into it
         low = new JPanel();
         low.setBackground(Color.white);
         low.add(jbtnEditlabel = new JButton("Edit Labels"));
         //  "Low Panel     
         body = new JPanel();
         jta.setBackground(Color.white);
         // Creating edit label button
         getContentPane().add(low, BorderLayout.SOUTH);
        // Set default directory to the current directory
        jFileChooser.setCurrentDirectory(new File("."));
        // Set BorderLayout for the frame
        getContentPane().add(new JScrollPane(jta),BorderLayout.CENTER);
        getContentPane().add(jlblStatus, BorderLayout.NORTH);
        // Register listeners
        ttUpload.addActionListener(this);
        jmiSave.addActionListener(this);
        jmiAbout.addActionListener(this);
        jmiExit.addActionListener(this);
        jmiSlideshow.addActionListener(this);
        jmiThumbnail.addActionListener(this);
        jbtnEditlabel.addActionListener(this);
      /**Handle ActionEvent for menu items*/
      public void actionPerformed(ActionEvent e)
        String actionCommand = e.getActionCommand();
        if (e.getSource() instanceof JMenuItem)
          if ("Upload".equals(actionCommand))
            upload();
          else if ("Save".equals(actionCommand))
            save();
          else if ("About".equals(actionCommand))
            JOptionPane.showMessageDialog(this,"Insert Images using Upload or edit the labels of present images.",
            "About This Demo",JOptionPane.INFORMATION_MESSAGE);
          else if ("Exit".equals(actionCommand))
            System.exit(0);
          else if ("Slideshow".equals(actionCommand))
            jmiSlideshow();       
          else if ("Thumbnail".equals(actionCommand))
            jmiThumbnail();
      /**Save file*/
      private void save()
        if (jFileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
          save(jFileChooser.getSelectedFile());
      /**Save file with specified File instance*/
      private void save(File file)
        try
          // Write the text in jta to the specified file
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    //      byte[] b = (jta.getText()).getBytes();
    //      out.write(b, 0, b.length);
          out.close();
          // Display the status of the save file operation in jlblStatus
          jlblStatus.setText(file.getName()  + " Saved ");
        catch (IOException ex)
          jlblStatus.setText("Error saving " + file.getName());
         /**jmiSlideshow file*/
      private void jmiSlideshow()
      /**jmiThumbnail file*/
      private void jmiThumbnail()
            private void upload()
                   /* Set title of frame to Upload File*/
                   String frameTitle="Upload File";
                   final JFrame upload= new JFrame(frameTitle);
                   /* Creating "file" label / txtfield and uploadPanel */
                   JPanel uploadPanel=new JPanel();
                   JLabel xfile=new JLabel("File");
                   JTextField input=new JTextField(20);
                   /* Creating buttons and btm panel*/
                   JPanel  buttonPanel=new JPanel();
                   JButton jbtnCancel=new JButton("Cancel");
                   JButton jbtnOk=new JButton("OK");
                   JButton jbtnBrowse=new JButton("Browse");
                   /* Adding buttons and txtfields into uploadPanel*/
                   uploadPanel.add(xfile);
                   uploadPanel.add(input);
                   uploadPanel.add(jbtnBrowse);               
                   uploadPanel.add(jbtnCancel);
                   uploadPanel.add(jbtnOk);
                   /* Adding uploadPanel into upload*/
                   upload.getContentPane().add(uploadPanel);
                   /* Set size/visibilty/ and close operations*/
                   upload.setSize(550, 200);
                   upload.setVisible(true);
                   upload.setDefaultCloseOperation(EXIT_ON_CLOSE);
                   upload.addWindowListener(new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             upload.setVisible(false);
                   /* Adding listeners for the buttons in Upload()*/
                   jbtnCancel.addActionListener(new jbtnCancelListener());          
                   jbtnBrowse.addActionListener(new jbtnBrowseListener());
          /* Cancel button */
               class jbtnCancelListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   System.exit(0);
          /**Browse button*/
               class jbtnBrowseListener implements ActionListener
              public void actionPerformed(ActionEvent e)
              if(fileChooser.showOpenDialog(f) == JFileChooser.APPROVE_OPTION)
                File file = fileChooser.getSelectedFile();
                     if(hasValidExtension(file))
                    Slide slide = new Slide(file);
                    slides.addItem(slide);
                    slides.setSelectedItem(slide);
                    slidePanel.addImage(slide.getFile());
             public boolean hasValidExtension(File file)
                 String[] okayExtensions = { "gif", "jpg", "png" };
                 String path = file.getPath();
                 String ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
                 for(int j = 0; j < okayExtensions.length; j++)
                if(ext.equals(okayExtensions[j]))
                return true;
                 return false;
         class Slide
        File file;
        public Slide(File file)
            this.file = file;
        public File getFile()
            return file;
        public String toString()
            return file.getName();
    class SlidePanel extends JPanel
        List<BufferedImage> images;
        int count;
        boolean keepRunning;
        Thread animator;
        public SlidePanel()
            images = Collections.synchronizedList(new ArrayList<BufferedImage>());
            count = 0;
            keepRunning = false;
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            if(images.size() > 0)
                BufferedImage image = images.get(count);
                int imageWidth = image.getWidth();
                int imageHeight = image.getHeight();
                int x = (w - imageWidth)/2;
                int y = (h - imageHeight)/2;
                g.drawImage(image, x, y, this);
        private Runnable animate = new Runnable()
            public void run()
                while(keepRunning)
                    if(images.size() == 0)
                        stop();
                        break;
                    count = (count + 1) % images.size();
                    repaint();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("animate interrupt: " + ie.getMessage());
                repaint();
        public void start()
            if(!keepRunning)
                keepRunning = true;
                animator = new Thread(animate);
                animator.start();
        public void stop()
            if(keepRunning)
                keepRunning = false;
                animator = null;
        public void addImage(File file)
            try
                FileImageInputStream fiis = new FileImageInputStream(file);
                images.add(ImageIO.read(fiis));                             
            catch(FileNotFoundException fnfe)
                System.err.println("file: " + fnfe.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
        public void removeImage(int index)
            images.remove(index);
    }

    not got time to look much but replace the System.exit(0) with this.dispose() will close the frame instead of closing the whole application.
    http://www.magiksafe.com

  • How to determine which FileChooser ExtensionFilter has been selected

    Hi,
    I'm using a JavaFX fileChooser.showSaveDialog with two extension filters (*.csv and *.xml). How can I determine which filter was selected when the end-user clicks the save button?
    I am writing a program that allows the end-user to create an output file in CSV or XML format.
    If the end-user enters a file name with no extension, I need a way to determine if I should create a CSV or XML file. I would also like to add the proper extension to the file name if none is specified by the end-user. I want to do this based on which filter the end-user has selected. I wrote a Java program 5 years ago and I was able to do this with the following instruction:
    String extension = jFileChooser.getFileFilter().getDescription();
    I can't find a similar instruction for JavFX.
    My JavaFX Code:
    FileChooser fileChooser = new FileChooser();
    fileChooser.setInitialDirectory(new File(options.getOutputDirectory()));
    ExtensionFilter filter1 = new FileChooser.ExtensionFilter("Comma Delimited (*.csv)", "*.csv");
    fileChooser.getExtensionFilters().add(filter1);
    ExtensionFilter filter2 = new FileChooser.ExtensionFilter("XML Document (*.xml)", "*.xml");
    fileChooser.getExtensionFilters().add(filter2);
    File file = fileChooser.showSaveDialog(stage);
    String filename = file.getAbsolutePath();...How do I determine which extension filter has been selected?
    My Java Code:
    JFileChooser jFileChooser = new JFileChooser();
    jFileChooser.setCurrentDirectory(new File(outputDirectory));
    jFileChooser.setSelectedFile(new File(backupfile));
    FileFilter filter = new FileNameExtensionFilter("Comma Delimited (*.csv)", "csv");
    jFileChooser.addChoosableFileFilter(filter);
    jFileChooser.setFileFilter(filter);
    filter = new FileNameExtensionFilter("XML Document (*.xml)", "xml");
    jFileChooser.addChoosableFileFilter(filter);
    jFileChooser.setAcceptAllFileFilterUsed(false);
    jFileChooser.setDialogTitle("Export Alarms");
    jFileChooser.setBackground(colorFileChooser);
    int returnVal = jFileChooser.showDialog(jFrame, "Export");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = jFileChooser.getSelectedFile();
        String filename = file.getAbsolutePath();
        String extension = jFileChooser.getFileFilter().getDescription();
        if (extension.equals("XML Document (*.xml)")) {
            if (!filename.endsWith(".xml") && !filename.endsWith(".XML")) {
                filename = filename + ".xml";
            saveTableXML(filename);
        else if (extension.equals("Comma Delimited (*.csv)")) {
            if (!filename.endsWith(".csv") && !filename.endsWith(".CSV")) {
                filename = filename + ".csv";
            saveTableCSV(filename);
    }Thanks,
    Barry
    Edited by: 907965 on May 13, 2012 1:14 PM
    Edited by: 907965 on May 13, 2012 1:15 PM
    Edited by: 907965 on May 13, 2012 1:19 PM

    This problem is currently tracked as http://javafx-jira.kenai.com/browse/RT-18836.

Maybe you are looking for

  • Null Pointer exception in accessing EJB in 9.0.3

    Hi The application is working fine with 9.0.2, but when I deployed in 9.0.3 it is giving Null Pointer Exception, throwing the error message in Stack Trace. ========================================================== java.lang.NullPointerException     

  • Any tables for  each vendor/customer to check foreign currency balance?

    Hi all, Does SAP provide any tables to check foreign currency balance for each vendor/customer? I have searched some websites, have not found any good solutions yet? Regards Tony Moderator: Please, search SDN

  • How do I stop Error 42408 in Itunes 10.5??!! Can't sync or connect to store!

    Please help!  From the moment I installed Itunes 10.5 everything has gone wrong.  I can't sync my Iphone (it says "backing up" forever and I can't drag/drop songs to it), the Iphone has IOS 5.  And the Itunes 10.5 always starts up with "error 42408"

  • Help needed for Virtual Key Figure BADI

    I am trying to implement Virtual Key Figures via BADI. Here is what I have done Define Method method IF_EX_RSR_OLAP_BADI~DEFINE. DATA: l_s_chanm TYPE rrke_s_chanm, l_kyfnm TYPE rsd_kyfnm. FIELD-SYMBOLS: <l_s_chanm> TYPE rrke_s_chanm. Insert Code CASE

  • Notes sharing

    Hi there! Does anyone know how can I share a note with another icloud account? Not via email or iMessage. My wife and I would like to have access to the same note and make changes to it and then have it synced between our devices. We each have our ow