Hi everyone,

In my simple GUI, I have a part where I use JFileChooser to let user browse for a file. The problem is that when browsing for that file, in order to open a sub folder, user has always to double click that the main folder to open the sub folder. What I want is that user can either double click the main folder or hit Enter (when that main folder is highlight) to open the sub folder.

Here is the code for the JFileChooser part:

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);


chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt") || f.isDirectory();

}

public String getDescription() {
return "TXT Files";
}});


int r = chooser.showDialog(new JFrame(),"Select .TXT File");
if (r == JFileChooser.APPROVE_OPTION) {
chooser.getSelectedFile().getName();
}
if(r == JFileChooser.CANCEL_OPTION) System.exit(0);

At this point, in order to open a sub folder, I need to double click the main folder. If I hit Enter (when that main folder is selected (highlight), it will give me an error. How can i get the Enter key to open the sub folder?

Thanks.

implement this interface java.awt.event.KeyListener and listen for KeyEvent.VK_ENTER

implement this interface java.awt.event.KeyListener and listen for KeyEvent.VK_ENTER

Thanks a lot for your hint but I am very new to java GUI so perhaps some sample code would be very helpful. :):)

Thanks a lot for your hint but I am very new to java GUI so perhaps some sample code would be very helpful. :):)

check this:http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html and here is another way using keybinders, which might serve your purpose better:http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html here is an example on keybinders:http://tips4java.wordpress.com/2008/10/10/key-bindings/

I don't see there any lack, no reason for KeyBindings nor for out_dated KeyListener

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.*;
//http://stackoverflow.com/questions/7769885/interrupted-exception-when-closing-file-open-dialogue
public class GUI extends JPanel implements ActionListener {

    static private final String newline = System.getProperty("line.separator");
    private static final long serialVersionUID = 1L;
    private JButton openButton, saveButton, runButton;
    private JTextArea log;
    private JFileChooser fc;

    public GUI() {
        super(new BorderLayout());
        log = new JTextArea(20, 40);
        log.setMargin(new Insets(5, 5, 5, 5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);
        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        openButton = new JButton("Open a File");
        openButton.addActionListener(this);
        saveButton = new JButton("Output Location");
        saveButton.addActionListener(this);
        runButton = new JButton("Run");
        runButton.addActionListener(this);
        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(runButton);
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
        showProp("java.vendor");
        showProp("java.version");
        showProp("java.runtime.version");
        showProp("sun.arch.data.model");
        showProp("os.name");
        showProp("os.version");
        showProp("os.arch");
    }

    private void showProp(String name) {
        output(name + " \t" + System.getProperty(name));
    }

    public void output(String msg) {
        log.append(msg + newline);
        log.setCaretPosition(log.getDocument().getLength());
        System.out.println(msg);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == openButton) { //Handle open button action.
            int returnVal = fc.showOpenDialog(GUI.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) { //This is where a real application would open the file.
                output("Input File Selected: " + fc.getSelectedFile().getName() + ".");
            } else {
                output("Input selection cancelled by user.");
            }
            log.setCaretPosition(log.getDocument().getLength());
        } else if (e.getSource() == saveButton) {//Handle output button action.
            int returnVal = fc.showSaveDialog(GUI.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {//This is where a real application will save the file.
                output("Output to be saved to: " + fc.getSelectedFile().getPath() + ".");
            } else {
                output("Output location selection cancelled.");
            }
            log.setCaretPosition(log.getDocument().getLength());
        } else if (e.getSource() == runButton) {
            output("Running...");
            try {
                output("Done.");//Do SOMETHING
            } catch (Exception e1) {
                e1.printStackTrace();
                System.exit(0);
            }
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("IDE Output Converter");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosed(WindowEvent e) {
                PrintStream nullStream = new PrintStream(new OutputStream() {

                    public void write(int b) throws IOException {
                    }

                    @Override
                    public void write(byte b[]) throws IOException {
                    }

                    @Override
                    public void write(byte b[], int off, int len) throws IOException {
                    }
                });
                System.setErr(nullStream);
                System.setOut(nullStream);
                System.exit(0);
            }
        });

        frame.add(new GUI());
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}
commented: always one up eh? ;) +9

:)

Thanks everyone for helping. I am new to java GUI so I am kind of learning now. I think I need to do a lot more reading and researching in order to get this done. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.