前段时间因为工作原因,需要对JFileChooser中选中或手动输入的文件名进行一下限制,也就是对其中的JTextField的输出进行一下限制,首先面临的问题就是怎么从JFileChooser这个控件中提出JTextField这个子空间,在网上搜索了一下,发现这个方法比较好用,代码如下:
这段代码大部分是在网上找到的,基本没作修改。
提出JTextField 的工作完成之后,就进入了下一步限制 JTextField 的过程,因为我要显示的文件名必须以CP_开头,所以代码修改如下:
最后又重写了一下approveSelection(),对文件名进行了一下格式检查,简单的完成了任务。
在查询的过程中学习是一件挺不错的事,加油!
- public static Component getLabelForInChooser(JFileChooser chooser,
- String key) {
- java.util.Locale l = chooser.getLocale();
- String s = UIManager.getString(key, l);
- javax.swing.plaf.FileChooserUI ui = chooser.getUI();
- int count = ui.getAccessibleChildrenCount(chooser);
- for (int i = 0; i < count; i++) {
- javax.accessibility.Accessible a = ui
- .getAccessibleChild(chooser, i);
- JLabel label = findLabel((JComponent) a, s);
- if (label != null) {
- return label.getLabelFor();
- }
- }
- return null;
- }
- private static JLabel findLabel(JComponent comp, String s) {
- JLabel label = null;
- if (comp instanceof JLabel) {
- if (((JLabel) comp).getText().equals(s)) {
- label = (JLabel) comp;
- }
- } else if (comp instanceof JComponent) {
- Component[] comps = comp.getComponents();
- for (int i = 0; i < comps.length; i++) {
- if (comps[i] instanceof JComponent) {
- label = findLabel((JComponent) comps[i], s);
- if (label != null) {
- break;
- }
- }
- }
- }
- return label;
- }
- public JTextField getJTextField(){
- Component comp = getLabelForInChooser(this,
- "FileChooser.fileNameLabelText");
- if (comp instanceof JTextField) {
- return ((JTextField) comp);
- }
- return null;
- }
提出JTextField 的工作完成之后,就进入了下一步限制 JTextField 的过程,因为我要显示的文件名必须以CP_开头,所以代码修改如下:
- protected void setJTextField(){
- JTextField field = getJTextField();
- field.setDocument(new specialDocment());
- field.setText("CP_");
- }
- protected class specialDocment extends PlainDocument {
- public void remove(int offs, int len) {
- try {
- if (offs >= strTop.length()) {
- super.remove(offs, len);
- }
- } catch (BadLocationException e) {
- e.printStackTrace();
- }
- }
- public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
- try {
- if(offs < strTop.length() && getLength() != 0) {
- if(offs == 0 && str.startsWith(strTop)){
- File file = getSelectedFile();
- if(null != file && file.exists()){
- super.remove(offs, getLength());
- super.insertString(offs, str, a);
- }
- }
- }
- else{
- super.insertString(offs, str, a);
- }
- } catch (BadLocationException e) {
- }
- }
- }
在查询的过程中学习是一件挺不错的事,加油!