我希望用户只能从现有的文件中选择文件,而不允许他输入文件名。
那么我们如何在JFileChooser中禁用文件输入字段?
谢谢。
import java.awt.Frame;
import java.lang.reflect.Field;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.plaf.metal.MetalFileChooserUI;
public class FileChooser {
public static void main(String[] args) throws Exception{
Frame f = new JFrame();
JFileChooser jFileChooser = new JFileChooser();
MetalFileChooserUI ui = (MetalFileChooserUI)jFileChooser.getUI();
Field field = MetalFileChooserUI.class.getDeclaredField("fileNameTextField");
field.setAccessible(true);
JTextField tf = (JTextField) field.get(ui);
tf.setEditable(false);
tf.setEnabled(false);
jFileChooser.showDialog(f, "Select");
f.dispose();
}
}
你可以遍历子组件层次结构(就像Yuriy提到的那样)。 以下是在组件层次结构中查找JTextField的函数。 它会找到第一个JTextField(希望需要的文本字段是FileChooser中唯一的一个)。
{
JFileChooser fc = new JFileChooser();
disableTF(fc);
}
public boolean disableTF(Container c) {
Component[] cmps = c.getComponents();
for (Component cmp : cmps) {
if (cmp instanceof JTextField) {
((JTextField)cmp).setEnabled(false);
return true;
}
if (cmp instanceof Container) {
if(disableTF((Container) cmp)) return true;
}
}
return false;
}
这是对http://www.mikepot.com/1493.html中解决方案的扩展。
不同之处在于单击被转换为双击。这在Ubuntu下似乎效果更好,因为双击会被转换成单击。
package com.troyware.inventoryItemManager;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JList;
/**
* This file chooser prevents users from changing file names and thus should facilitate navigating to the correct file
* by precluding the user from getting stuck when single clicking a folder name
*
* @author http://www.mikepot.com/1493.html
* slightly modified by Phil Troy, www.PhilTroy.com, to convert single click into double click
*/
public class MyFileChooser extends JFileChooser
{
public MyFileChooser()
{ JList list = findFileList(this);
for (MouseListener l : list.getMouseListeners())
{ if (l.getClass().getName().indexOf("FilePane") >= 0)
{ list.removeMouseListener(l);
list.addMouseListener(new MyMouseListener(l));
}
}
}
private JList findFileList(Component comp)
{ if (comp instanceof JList) return (JList)comp;
if (comp instanceof Container)
{ for (Component child : ((Container)comp).getComponents())
{ JList list = findFileList(child);
if (list != null) return list;
}
}
return null;
}
private class MyMouseListener extends MouseAdapter
{
MyMouseListener(MouseListener listenerChain)
{ m_listenerChain = listenerChain;
}
public void mouseClicked(MouseEvent event)
{ if (event.getClickCount() > 0)
{ m_listenerChain.mouseClicked(new MouseEvent(event.getComponent(), event.getID(), event.getWhen(), event.getModifiers(), event.getX(), event.getY(), 2, false));
}
}
private MouseListener m_listenerChain;
}
private static final long serialVersionUID = 1L;
}