JFileChooser + KeyListener

Hello. I am using the JFileChooser and have come across a problem. When the user tabs to the cancel button and then hits the "Enter" key on the keyboard, the JFileChooser sends back the APPROVE_OPTION rather than the CANCEL_OPTION. Is there any way around this?

1) for exercise and understand how keyboard and jfilechooser interactsWell, the key board and jfilechooser don't interact. JFileChooser is simply a panel consisting of other components added to the panel. So the keyboard interacts with the other components added to the panel.
So start with something simpler if you want to understand how KeyStrokes and Actions are used in Swing. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
Since the JFileChooser appears to be using a JList you would then need to understand how the key bindings are used on the list. You would then need to somehow access the list from the UI or simply iterate through all the components added to the JFileChooser until you find a JList. Once you find the JList you can then assign the "P" keystroke to the same action as is being used by the "down" keystroke.

Similar Messages

  • Jfilechooser and keylistener

    hi,
    I'm a noob in java. I have a simple application to open file with JFileChooser. When I press down key on keyboard the selection go down etc. For istance, if want to obtain the same thing pressing "p" key, what could I do??
    Is it possible?
    sorry for my bad english and for the dummy question
    regards

    1) for exercise and understand how keyboard and jfilechooser interactsWell, the key board and jfilechooser don't interact. JFileChooser is simply a panel consisting of other components added to the panel. So the keyboard interacts with the other components added to the panel.
    So start with something simpler if you want to understand how KeyStrokes and Actions are used in Swing. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
    Since the JFileChooser appears to be using a JList you would then need to understand how the key bindings are used on the list. You would then need to somehow access the list from the UI or simply iterate through all the components added to the JFileChooser until you find a JList. Once you find the JList you can then assign the "P" keystroke to the same action as is being used by the "down" keystroke.

  • How can I set a default file for JFileChooser

    Hi. I am developing a p2p chat application and I have to unrelated questions.
    1. How can I set a default file name for JFileChooser, to save a completly new file?
    2. I have a JTextArea that I append recieved messages. But when a message is appended, the whole desktop screen refreshes. How can I prevent that?
    Hope I was clear. Thanks in advance.

    Thank you for the first answer, it solved my problem. Here is the code for 2nd question, I've trimmed it a lot, hope I didn't cut off any critical code
    public class ConversationWindow extends JFrame implements KeyListener,MessageArrivedListener,ActionListener,IOnlineUsrComp{
         private TextArea incomingArea;
         private Conversation conversation;
         private JTextField outgoingField;
         private JScrollPane incomingTextScroller;
         private String userName;
         private JButton inviteButton;
         private JButton sendFileButton;
         private JFileChooser fileChooser;
         private FontMetrics fontMetrics;
         private HashMap<String, String> onlineUserMap;
         public void MessageArrived(MessageArrivedEvent e) {
              showMessage(e.getArrivedMessage());
         public ConversationWindow(Conversation conversation)
              this.conversation=conversation;
              userName=User.getInstance().getUserName();
              sendFileButton=new JButton("Dosya G�nder");
              sendFileButton.addActionListener(this);
              inviteButton=new JButton("Davet et");
              inviteButton.addActionListener(this);
              incomingArea=new TextArea();
              incomingArea.setEditable(false);
              incomingArea.setFont(new Font("Verdana",Font.PLAIN,12));
              fontMetrics =incomingArea.getFontMetrics(incomingArea.getFont());
              incomingArea.setPreferredSize(new Dimension(300,300));
              outgoingField=new JTextField();
              outgoingField.addKeyListener(this);
              incomingTextScroller=new JScrollPane(incomingArea);          
              JPanel panel=new JPanel();
              panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
              panel.add(inviteButton);
              panel.add(sendFileButton);
              panel.add(incomingTextScroller);
              panel.add(outgoingField);
              add(panel);
              pack();
              setTitle("Ki&#351;iler:");
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setLocationRelativeTo(null);
              addWindowListener(new CloseAdapter());
         //Sends the message to other end
         public void keyPressed(KeyEvent e) {
              if(e.getKeyCode()==KeyEvent.VK_ENTER && e.getSource()==outgoingField)
                   String message=outgoingField.getText();
                   if(message.equals("")) return;
                   showMessage(userName+": "+message);
                   conversation.sendMessages(userName+": "+message);
                   outgoingField.setText("");     
         //Displays the recieved message
         public void showMessage(String message)
              if(fontMetrics.stringWidth(message)>incomingArea.getWidth())
                   int mid=message.length()/2;
                   StringBuilder sbld=new StringBuilder(message);
                   for(;mid<message.length();mid++)
                        if(message.charAt(mid)==' ')
                             sbld.setCharAt(mid, '\n');
                             message=sbld.toString();
                             break;
              incomingArea.append("\n"+message);
    }

  • JFileChooser as a component?

    Hey,
    I need to have directory browsing capability but implementing a one from scratch is too much. Is there anyway to integrate JFileChooser into a component? Like to put it into my application in a panel rather than have it as a dialog???

    Hey
    Do you know how I could add keylistener and mouse listener to it?
    I want to make it so that when the user presses del on keyboard then the selected file is deleted. And I want to add some right click actions as well.
    Just adding listeners to JFileChooser doesn't seem to do the trick.
    I would guess that if I take individual components of it and add the listeners to them, then that would work.
    Any ideas?

  • Need help for JFileChooser

    Hi,
    I need help on this one. I have a filechooser class which extended from JFileChooser class. Every thing works fine except this: I want to by hiting the "Enter" key to save the files. The "Enter" key works only when the focus is in the file name text field now, I want it to work when the focus is in the directory area, the file list area and the file type area as well. I try to add the KeyListener but how can I get hold of the component of the three areas of file chooser? I tried to add the KeyListener as Accessory, it didn't work either. Some one please help me.

    Try this to let your components react to ActionEvents
    comp.addActionListener(new  WhatIWantToDo());
    // WhatIWantToDo is the inner class.
    // Let it do what you want to be the reaction
    class WhatIWantToDo implements ActionListener {
    public void actionPerformed(ActionEvent event) {
    //  code on what you want to do
    }Or working without an inner class try this
    comp.addActionListener(new ActionListener() {
    // the event handling
    public void actionPerformed(ActionEvent event) {
    // your code for behavior
    // e.g. System.out.println("There is a reaction");
    // or specify a special named component as c1
    Object source = event.getSource();
    if (source == c1) doSomething();
    else if (source == c2) doOtherThings();
    });Hope this is of help for what you want. Else let me know.

  • JFileChooser's approve button text changes when file

    I have a JFileChooser used for loading some XML file(s). We want the approve button's text to be "Load". When I bring up the dialog, the button text initially reads "Load", when I select a directory, it reads "Open", if I select a file again, it goes back to "Load". So far, so good.
    The problem comes when using it in a non-English language. When I bring up the dialog, the button text initially reads the appropriately translated "Load". However, when I select a directory, it changes to the English "Open". I do not see a method to use to adjust this text. Am I missing something, or is this a bug?
    Any help is greatly appreciated.
    Jamie

    Here's some code I'll put into the public domain:
    package com.graphbuilder.desktop;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Stack;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.io.File;
    <p>Attempt to improve the behaviour of the JFileChooser.  Anyone who has used the
    the JFileChooser will probably remember that it lacks several useful features.
    The following features have been added:
    <ul>
    <li>Double click to choose a file</li>
    <li>Enter key to choose a file after typing the filename</li>
    <li>Enter key to change to a different directory after typing the filename</li>
    <li>Automatic rescanning of directories</li>
    <li>A getSelectedFiles method that returns the correct selected files</li>
    <li>Escape key cancels the dialog</li>
    <li>Access to common GUI components, such as the OK and Cancel buttons</li>
    <li>Removal of the useless Update and Help buttons in Motif L&F</li>
    </ul>
    <p>There are a lot more features that could be added to make the JFileChooser more
    user friendly.  For example, a drop-down combo-box as the user is typing the name of
    the file, a list of currently visited directories, user specified file filtering, etc.
    <p>The look and feels supported are Metal, Window and Motif.  Each look and feel
    puts the OK and Cancel buttons in different locations and unfortunately the JFileChooser
    doesn't provide direct access to them.  Thus, for each look-and-feel the buttons must
    be found.
    <p>The following are known issues:  Rescanning doesn't work when in Motif L&F.  Some
    L&Fs have components that don't become available until the user clicks a button.  For
    example, the Metal L&F has a JTable but only when viewing in details mode.  The double
    click to choose a file does not work in details mode.  There are probably more unknown
    issues, but the changes made so far should make the JFileChooser easier to use.
    public class FileChooserFixer implements ActionListener, KeyListener, MouseListener, Runnable {
         Had to make new buttons because when the original buttons are clicked
         they revert back to the original label text.  I.e. some programmer decided
         it would be a good idea to set the button text during an actionPerformed
         method.
         private JFileChooser fileChooser = null;
         private JButton okButton = new JButton("OK");
         private JButton cancelButton = new JButton("Cancel");
         private JList fileList = null;
         private JTextField filenameTextField = null;
         private ActionListener actionListener = null;
         private long rescanTime = 20000;
         public FileChooserFixer(JFileChooser fc, ActionListener a) {
              fileChooser = fc;
              actionListener = a;
              fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              okButton.setMnemonic('O');
              cancelButton.setMnemonic('C');
              JButton oldOKButton = null;
              JButton oldCancelButton = null;
              JTextField[] textField = getTextFields(fc);
              JButton[] button = getButtons(fc);
              JList[] list = getLists(fc);
              String laf = javax.swing.UIManager.getLookAndFeel().getClass().getName();
              if (laf.equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.motif.MotifLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[2];
                   button[1].setVisible(false); // hides the do-nothing 'Update' button
                   button[3].setVisible(false); // hides the disabled 'Help' button
                   filenameTextField = textField[1];
                   fileList = list[0];
              fix(oldOKButton, okButton);
              fix(oldCancelButton, cancelButton);
              okButton.addActionListener(this);
              cancelButton.addActionListener(this);
              fileList.addMouseListener(this);
              addKeyListeners(fileChooser);
              new Thread(this).start(); // note: rescanning in Motif feel doesn't work
         public void run() {
              try {
                   while (true) {
                        Thread.sleep(rescanTime);
                        Window w = SwingUtilities.windowForComponent(fileChooser);
                        if (w != null && w.isVisible())
                             fileChooser.rescanCurrentDirectory();
              } catch (Throwable err) {}
         public long getRescanTime() {
              return rescanTime;
         public void setRescanTime(long t) {
              if (t < 200)
                   throw new IllegalArgumentException("Rescan time >= 200 required.");
              rescanTime = t;
         private void addKeyListeners(Container c) {
              for (int i = 0; i < c.getComponentCount(); i++) {
                   Component d = c.getComponent(i);
                   if (d instanceof Container)
                        addKeyListeners((Container) d);
                   d.addKeyListener(this);
         private static void fix(JButton oldButton, JButton newButton) {
              int index = getIndex(oldButton);
              Container c = oldButton.getParent();
              c.remove(index);
              c.add(newButton, index);
              newButton.setPreferredSize(oldButton.getPreferredSize());
              newButton.setMinimumSize(oldButton.getMinimumSize());
              newButton.setMaximumSize(oldButton.getMaximumSize());
         private static int getIndex(Component c) {
              Container p = c.getParent();
              for (int i = 0; i < p.getComponentCount(); i++) {
                   if (p.getComponent(i) == c)
                        return i;
              return -1;
         public JButton getOKButton() {
              return okButton;
         public JButton getCancelButton() {
              return cancelButton;
         public JList getFileList() {
              return fileList;
         public JTextField getFilenameTextField() {
              return     filenameTextField;
         public JFileChooser getFileChooser() {
              return fileChooser;
         protected JButton[] getButtons(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JButton)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JButton[] arr = new JButton[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JButton) v.get(i);
              return arr;
         protected JTextField[] getTextFields(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JTextField)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JTextField[] arr = new JTextField[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JTextField) v.get(i);
              return arr;
         protected JList[] getLists(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JList)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JList[] arr = new JList[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JList) v.get(i);
              return arr;
         public File[] getSelectedFiles() {
              File[] f = fileChooser.getSelectedFiles();
              if (f.length == 0) {
                   File file = fileChooser.getSelectedFile();
                   if (file != null)
                        f = new File[] { file };
              return f;
         public void mousePressed(MouseEvent evt) {
              Object src = evt.getSource();
              if (src == fileList) {
                   if (evt.getModifiers() != InputEvent.BUTTON1_MASK) return;
                   int index = fileList.locationToIndex(evt.getPoint());
                   if (index < 0) return;
                   fileList.setSelectedIndex(index);
                   File[] arr = getSelectedFiles();
                   if (evt.getClickCount() == 2 && arr.length == 1 && arr[0].isFile())
                        actionPerformed(new ActionEvent(okButton, 0, okButton.getActionCommand()));
         public void mouseReleased(MouseEvent evt) {}
         public void mouseClicked(MouseEvent evt) {}
         public void mouseEntered(MouseEvent evt) {}
         public void mouseExited(MouseEvent evt) {}
         public void keyPressed(KeyEvent evt) {
              Object src = evt.getSource();
              int code = evt.getKeyCode();
              if (code == KeyEvent.VK_ESCAPE)
                   actionPerformed(new ActionEvent(cancelButton, 0, cancelButton.getActionCommand()));
              if (src == filenameTextField) {
                   if (code != KeyEvent.VK_ENTER) return;
                   fileList.getSelectionModel().clearSelection();
                   actionPerformed(new ActionEvent(okButton, 0, "enter"));
         public void keyReleased(KeyEvent evt) {}
         public void keyTyped(KeyEvent evt) {}
         public void actionPerformed(ActionEvent evt) {
              Object src = evt.getSource();
              if (src == cancelButton) {
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);
              else if (src == okButton) {
                   File[] selectedFiles = getSelectedFiles();
                   Object obj = fileList.getSelectedValue(); // is null when no file is selected in the JList
                   String text = filenameTextField.getText().trim();
                   if (text.length() > 0 && (obj == null || selectedFiles.length == 0)) {
                        File d = fileChooser.getCurrentDirectory();
                        Vector vec = new Vector();
                        StringTokenizer st = new StringTokenizer(text, "\"");
                        while (st.hasMoreTokens()) {
                             String s = st.nextToken().trim();
                             if (s.length() == 0) continue;
                             File a = new File(s);
                             if (a.isAbsolute())
                                  vec.add(a);
                             else
                                  vec.add(new File(d, s));
                        File[] arr = new File[vec.size()];
                        for (int i = 0; i < arr.length; i++)
                             arr[i] = (File) vec.get(i);
                        selectedFiles = arr;
                   if (selectedFiles.length == 0) {
                        Toolkit.getDefaultToolkit().beep();
                        return;
                   if (selectedFiles.length == 1) {
                        File f = selectedFiles[0];
                        if (f.exists() && f.isDirectory() && text.length() > 0 && evt.getActionCommand().equals("enter")) {
                             fileChooser.setCurrentDirectory(f);
                             filenameTextField.setText("");
                             filenameTextField.requestFocus();
                             return;
                   boolean filesOnly = (fileChooser.getFileSelectionMode() == JFileChooser.FILES_ONLY);
                   boolean dirsOnly = (fileChooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY);
                   if (filesOnly || dirsOnly) {
                        for (int i = 0; i < selectedFiles.length; i++) {
                             File f = selectedFiles;
                             if (filesOnly && f.isDirectory() || dirsOnly && f.isFile()) {
                                  Toolkit.getDefaultToolkit().beep();
                                  return;
                   fileChooser.setSelectedFiles(selectedFiles);
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);

  • Output stream with a keylistener

    Hello,
    I have a program that basically runs .class and .jar console based programs, using JFileChooser to open them and such. I have managed to capture the System.out and System.err streams from running processes and using p.getInputStream() and p.getErrorStream(), just appending a JTextArea with each character in the stream. Now I'm trying to get the System.in stream connected.
    I have a keylistener attached to my JFrame, like this
    String line;
    frame.addKeyListener(new KeyListener() {
         @Override
         public void keyPressed(KeyEvent e) {}
         @Override
         public void keyReleased(KeyEvent e) {
              Character key = e.getKeyChar();
              //Delete the last character in both the JTextArea and the current line
              if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                   if (output.getText().charAt(output.getText().length()-1) != '\n') {
                        String text = output.getText().substring(0, output.getText().length()-1);
                        output.setText(text);
                        line = line.substring(0, line.length()-1);
                   //Write line to OutputStream and put a new line in the JTextArea                              
              } else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                       //writeToOutput("\n-------\nLine reads: " + line + "\n--------\n");
                   writeToOutput("\n");
                   line = "";
              //Add any other characters to the line and show them in the JTextArea
              } else if (e.getKeyCode() != KeyEvent.VK_SHIFT) {
                   writeToOutput(key + "");
                   line = line + key;
         @Override
         public void keyTyped(KeyEvent e) {}                         
    });What happens is that the user types a line of characters, then presses enter. What I want is for when enter is pressed that the line is written to some sort of OutputStream in such a way that I can use it to provide input to a process with p.getOutputStream(OutputStream);
    Which OutputStream do I have to use and how? It's all a bit confusing :S
    Thanks,
    Jack
    Edited by: jackCharlez on Nov 23, 2009 1:25 PM
    Edited by: jackCharlez on Nov 23, 2009 1:33 PM

    Solved, using
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    Out.write in my keylistener and out.newline(); out.flush(); when the user presses enter.
    ^ For anyone googling this problem :P

  • No Disk Error when opening JFileChooser

    Hi all
    After launching my app via JWS and opening my apps FileChooser I get a 'javaw.exe - No Disk' error message:
    'There is no disk in the drive. Please insert a disk into drive A:.'
    This doesn't happen if I start the app without JWS. Although it happens only the first time after opening the FileChooser it's rather annoying for the user. I can't expect the user always having a disk in their drive.
    Is there a way of switching the scan for drive A off?
    Thanks for your help.
    Stephan

    See Top 25 Bugparade: # 4264750
    This is a SecurityManager - Problem and the java.io.File.
    eg.:
    System.setSecurityManager(new RMISecurityManager());
    File[] roots = File.listRoots();
    Then you will see the problem...
    I tried the following workaround:
    before you access disk. (or JFileChooser)
    SecurityManager sm = System.getSecurityManger();
    System.setSecurityManager(null);
    // disable the SecurityManger
    // this special disk access needs no SecurityManager..
    ... popup JFileChosser or make FileAccess..
    System.setSecurityManager(sm);
    // restore the old SecurityManger
    It's not the best solution but it works..
    hope this will help,
    Wolfgang
    EDI Organisation

  • Can not sort the files in JFileChooser if the files are from remote machine

    Hi All,
    Let me set the context of the question.
    I have extended the JFileChooser to support the listing/view of files.dirs etc of remote location through CORBA.To achieve that i have customized
    my FileSystemView to support it. In general ,the current JFileChooser sorts the file when we have details view .My question is related to this.The default
    JFileChooser has the support for sorting but when i customized the FileSystemView,the sorting functionality is no more exist.I tried with TableRowSorter as well but
    the sorting can be achieved in View only,the model still remains same as initial.
    Any pointer towards this will be highly appreciated.
    Thanks
    Praveen

    Can anyone help me out to solve this problem or any suggestion regarding this ?
    Regards
    Praveen

  • JFileChooser (again!) slow in JRE 1.6.14 on some machines, not others

    I am running ImageJ (from the NIH) on several of our machines and on some machines JFileChooser is lightning fast, while others exhibit the same slowness spoken of in another JFileChooser thread that is now in a locked state. We open large image files (tif, png) located on our SAN and from the network traffic I see in Windows Task Manager while opening a folder containing the images I would guess that JFileChooser is actually opening the files (intentionally or not), not just obtaining a folder listing. It's similar to the same issue of opening a large folder of images with the view set to thumbnails - it takes about the same amount of time. I have tried the suggestions in that thread to no avail - the environment the machines are running is:
    Windows XP SP3
    Java JRE 1.6.0_14
    Can anyone comment on what JFileChooser is doing and how I can get it to stop this? Is it a Windows environment setting so that the native API calls made by JFileChooser will behave differently? Thoughts?
    Thanks,
    Tom

    I can't be absolutely sure, but we have several seemingly identical machines used for the purpose of reading medical images and several of them appear to work correctly (very fast loading and population of the folder's contents) and others don't. I have been using eclipse to enhance the software tool we're using (ImageJ) and using the debugger I can see that when the JFileChooser object is being instantiated and populated with entries a tremendous amount of network traffic occurs. This network traffic is equivalent to the amount I see when the same folder is opened in My Computer using a thumbnails view of the folder contents. Apparently, the network is delivering approximately 300-400 MB of images. As far as configuration of the Windows machines is concerned I haven't found a significant difference yet, though I admit I am not a Windows desktop admin and may not know of some configuration item that could be responsible. I assume (though could be mistaken) that both My Computer and JFileChooser are ultimately using similar API calls to get the folder content entries?

  • Problem with JFileChooser and ImageIcon

    I'm trying to create an ImageIcon object from file selected in JFileChooser. The problem is that jfc.getSelectedFile().getAbsolutePath() returns a string with backslashes and the constructor of ImageIcon requires the string to have slashes. I`ve tried to create it via URL but it doesn't work as well...
    String lastUsedPath;
    URL imageURL;
    JFileChooser fc = new JFileChooser();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    int returnVal = fc.showDialog(frame,title);
    if(returnVal==JFileChooser.APPROVE_OPTION){                    
         lastUsedPath = fc.getSelectedFile().getAbsolutePath();
         imageURL = getClass().getResource(lastUsedPath);     //don't really get this but I copied it from Java Swing Tutorial          
    }else{
         return null;
    int curH, curW;            
    ImageIcon srcIcon = new ImageIcon(imageURL);                              
    curW = srcIcon.getIconWidth();
    curH = srcIcon.getIconHeight();If I use it this way imageURL is set to null.
    If I set the imageURL as 'fc.getSelectedFile().toURL()' the string is eg.: "file:/E:/file.jpg" instead of "E:/file.jpg". After that the ImageIcon is created but width and height return -1.
    If I try to create ImageIcon by 'new ImageIcon(lastUsedPath)' I get a not null object but the width & height of the ImageIcon is -1 as well.
    What do I have to do to be able to create an ImageIcon from file selected in JFileChooser? Why is this so hard and mind blowing?

    It still returns the ImageIcon object with width & height set to -1.
    EDIT:
    Got it finally:
    lastUsedPathForStupidImageIcon = fc.getSelectedFile().getPath();     
    img = ImageIO.read(new File(lastUsedPathForStupidImageIcon));
    curH = img.getHeight(this);
    curW = img.getWidth(this);The key was to use another String variable and hold the path instead of the absolute path
    Edited by: Beholder on Jan 17, 2010 1:35 PM

  • Problem using KeyListener in a JFrame

    Let's see if anyone can help me:
    I'm programming a Maze game, so I use a JFrame called Window, who extends JFrame and implements ActionListener, KeyListener. Thw thing is that the clase Maze is a JPanel, so I add it to my Frame and add the KeyListener to both, the Maze and the Window, but still nothing seems to happen.
    I've tried to remove the KeyListener from both separately, but still doesn't work...
    Any suggestions???

    This is the code for my Window.java file. May be someone can see the error...
    package maze;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Window extends JFrame implements ActionListener, KeyListener {
      private Maze maze;
      private JButton crear = new JButton("New");
      public Window(int size, String s) {
        super("3D Maze");
        boolean b = true;
        if (s.equalsIgnoreCase("-n"))
          b = false;
        else if (s.equalsIgnoreCase("-v"))
          b = true;
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        maze = new Maze(size,size,b);
        crear.addActionListener(this);
        addKeyListener(this);
        maze.addKeyListener(this);
        c.add(crear,BorderLayout.NORTH);
        c.add(maze,BorderLayout.CENTER);
        setSize(600,650);
        show();
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_UP || e.getKeyCode() == e.VK_W)
          maze.walk();
        else if (e.getKeyCode() == e.VK_DOWN || e.getKeyCode() == e.VK_S)
          maze.back();
        else if (e.getKeyCode() == e.VK_LEFT || e.getKeyCode() == e.VK_A)
          maze.turnLeft();
        else if (e.getKeyCode() == e.VK_RIGHT || e.getKeyCode() == e.VK_D)
          maze.turnRight();
        else if (e.getKeyCode() == e.VK_V)
          maze.alternaMostrarCreacion();
        else if (e.getKeyCode() == e.VK_M)
          maze.switchMap();
      public void keyTyped(KeyEvent e) {}
      public void keyReleased(KeyEvent e) {
      public void actionPerformed(ActionEvent e) {
        maze.constructMaze();
      public static void main(String[] args) {
        int i = 30;
        String s = "-v";
        if (args.length != 0) {
          try {
            i = Integer.parseInt(args[0]);
            if (!(i >= 15 && i <= 50))
              i = 30;
            s = args[1];
          catch(Exception e) {}
        Window w = new Window(i,s);
        w.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              ImageIcon im = new ImageIcon("./Logo.gif");
              String s = "";
              s += "3D MAZE\n\n";
              s += "Creator: Allan Marin\n";
              s += "http://metallan.topcities.com\n\n";
              s += ""+((char)(169))+" 2002";
              JOptionPane.showMessageDialog(null,s,"About...",JOptionPane.PLAIN_MESSAGE,im);
              System.exit(0);
    }

  • Trouble with focus, swing & keyListener

    can anybody out there help me with this problem, I got stuck with:
    I create a JDialog in a JFrame & would like to add Keylistener to the JDialog as soon as it opens..........but the it doesn't seem to be working....

    Oops! As bbhangale pointed out, my previous post is incorrect. It should read as follows:
    dialog.getRootPane().getInputMap...
    dialog.getRootPane().getActionMap...Actually, I've created MyDialog, an abstract sub-class of JDialog. In it, I over-ride the createRootPane() method and delcare the abstract onDialogClose() method. Here's what that looks like:
    public abstract class MyDialog extends JDialog
       // Implement MyDialog wrappers for all the JDialog constructors
       public MyDialog()
          super();
        * Overriding this method to register an action so the 'Esc' key will dismiss
        * the dialog.
        * @return a <code>JRootPane</code> with the appropiate action registered
       protected JRootPane createRootPane()
          JRootPane rootPane = new JRootPane();
          rootPane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW ).
             put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), "escPressed" );
          rootPane.getActionMap().
             put( "escPressed", new AbstractAction( "escPressed" )
             public void actionPerformed( ActionEvent actionEvent )
                onDialogClose();
          return rootPane;
        * This method gets called when the user attemps to close the JDialog via the
        * 'Esc' key.  It is up to the sub-class to implement this method and handle
        * the situation appropriately.
       protected abstract void onDialogClose();
    }Then, anytime I need a dialog, I sub-class MyDialog and implement onDialogClose() to do whatever I want it to do when the user presses 'Esc'.
    I swear I've been using it for quite some time now and it works beautifully!
    Jamie

  • JFileChooser animated gif preview

    I'm using an Accesory with an ImageIcon to preview images on a JFileChooser.
    It works ok, but I would like to know how do I get those animated gif to restart their animation whenever I click some other file (so the image preview goes to null) and click back on them.
    There are non-looped gifs and looped ones, it is specially for the non-looped gifs as to give a way to get to see the animation again. After clicking the file once the animation never plays again, even if a load another preview by clicking another file and then go back...
    Since there's no obvious method on ImageIcon or Image I tried flush since it says it clears the data but the only thing I got was the gif animating improperly (it would get trash/noise).
    * JFileChooserImagePreview.java
    * Created on 16 de junio de 2005, 12:58 AM
    package ptcg.win.util;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import java.io.File;
    /* from FileChooserDemo2.java. */
    public class JFileChooserImagePreview extends javax.swing.JComponent implements PropertyChangeListener {
         public JFileChooserImagePreview(JFileChooser fc) {
              setHeight = -1;
              setWidth = -1;
              setPreferredSize(new Dimension(100, 50));
              fc.addPropertyChangeListener(this);
         public JFileChooserImagePreview(JFileChooser fc, int setHeight, int setWidth) {
              this.setHeight = setHeight;
              this.setWidth = setWidth;
              setPreferredSize(new Dimension(setHeight, setWidth));
              fc.addPropertyChangeListener(this);
         public void propertyChange(PropertyChangeEvent e) {
              boolean update = false;
              String prop = e.getPropertyName();
              //If the directory changed, don't show an image.
              if(JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   file = null;
                   update = true;
              } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                   file = (File) e.getNewValue();
                   update = true;
              //Update the preview accordingly.
              if (update) {
                   thumbnail = null;
                   if(isShowing()) {
                        loadImage();
                        repaint();
         public void loadImage() {
              if (file == null) {
                   thumbnail = null;
                   return;
              ImageIcon tmpIcon = new ImageIcon(file.getPath());
              if (tmpIcon != null) {
                   Image i = tmpIcon.getImage();
                   //i.flush(); //screws the animation
                   thumbnail = new ImageIcon(i.getScaledInstance(setHeight, setWidth, Image.SCALE_SMOOTH));
         protected void paintComponent(Graphics g) {
              if (thumbnail == null) {
                   loadImage();
              if (thumbnail != null) {
                   int x = getWidth()/2 - thumbnail.getIconWidth()/2;
                   int y = getHeight()/2 - thumbnail.getIconHeight()/2;
                   if (y < 0) {
                        y = 0;
                   if (x < 5) {
                        x = 5;
                   thumbnail.paintIcon(this, g, x, y);
         ImageIcon thumbnail = null;
         File file = null;
         int setHeight, setWidth;
    }Thanks in advance

    Never-mind. I have it working properly now.

  • KeyListener..for beginners..please help me

    hi, im new to java..i think that this thing is simple to you guys..im trying to make a program where there is a ball bouncing around the screen..theres 3 walls one on the left one on the right and the other on top..there should be a moving catcher at the bottom..which should be controlled by the keyboard..
    i already made the catcher..my only problem is..i dont know how to make it move..
    by the way..i'm using threading..
    it would be nice if you can post even a simple example of threading with keylistener even just left and right so i would know how to apply it..
    i hope that someone there would help beginners like me, it would really be a big help..
    thank you very much!
    -dennis

    Hi Madhuama, I'll try to give you a hand with this. First off, what OS is running on your notebook, what game are you attempting to play, and how is it not working? Is it not installing?
    Thanks,
    Fenian Frank
    I work on behalf of HP

Maybe you are looking for

  • Installation fails on new Macbook Pro

    I am trying to install CS3 on a new Macbook Pro Retina 13" with Mavericks. All of the CS3 apps except Photoshop installed correctly. Photoshop fails and when I try to launch it returns a message that it cannot be initialized because the disk is not a

  • Final Cut Pro Monitor/TV/Camera hookup

    How do I hook up my G5 dual core Mac to JVC monitor(Model # TM-R9U) through Sony DSR 200 DV Cam camera(used for my deck) and then to my Toshiba television with RCA and S-video Line 2 outlets. tv? I want to watch and monitor my Final Cut Pro timeline

  • Why does airplay skip

    why does airtunes skip over airplay with my apple tv 2?

  • How to use functional global with a large amount of variables?

    Hi all, I'm currently developping a LV program which control and acquired data from a device. Up to now I used global variables ( very conveniente to use for experimental parameters). But now my program is become to be too large and I have too much "

  • Newb question about LCD resolution..

    This may seem like an odd question but I just bought a widescreen LCD and wanted to know what the proper ratio I should be working in is. 1920 x 1200 (1.6) or 1920 x 1440? (1.3) Thanks...