File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Need your help with JcomboBox Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Need your help with JcomboBox" Watch "Need your help with JcomboBox" New topic

Need your help with JcomboBox

Slava Yuz

Joined: Mar 31, 2011
Posts: 1
Hello to all!
I need your help with JcomboBox, while setting files in it.
Examine following code:

File[] file_list = getFileList();
JComboBox box = new JComboBox(file_list);
JFrame frame = new JFrame();

Assume getFileList() is a function that returns an list of files residing in a specific directory and cannot be changed.

Above code displays a frame with a combo box where I can choose between all the files.
My problem is the files are shown with their full path (for example c:\documents and settings\administrator\.....) which could be very long and pointless since they're all in the same directory.
I want to see only the file name.

Said that there are 2 ways to fix the above code.

Values in combobox should still be files, meaning I will be able to do:
File f = (File)box.getSelectedValue();

I have searched many forums, books but still not find any solution.
Will very much appreciate your help!
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Hi Slava, and welcome to the Ranch! Please BeForthrightWhenCrossPostingToOtherSites.

You could use a custom renderer that shows only the file name. Read the API for JComboBox and follow the link to the Swing tutorial on "How to Use Combo boxes" where you can find out more about custom renderers.

luck, db
There are no new questions, but there may be new answers.
I agree. Here's the link:
subject: Need your help with JcomboBox
It's not a secret anymore!