2010-04-19 10 views

답변

0

FileChooser가 사용되는 방법에 대해 FileChooserDemo 및 FileChooserDemo2 here을 살펴보십시오.

public void actionPerformed(ActionEvent e) { 
    //Set up the file chooser. 
    if (fc == null) { 
     fc = new JFileChooser(); 

    //Add a custom file filter and disable the default 
    //(Accept All) file filter. 
     fc.addChoosableFileFilter(new ImageFilter()); 
     fc.setAcceptAllFileFilterUsed(false); 

    //Add custom icons for file types. 
     fc.setFileView(new ImageFileView()); 

    //Add the preview pane. 
     fc.setAccessory(new ImagePreview(fc)); 
    } 

    //Show it. 
    int returnVal = fc.showDialog(FileChooserDemo2.this, 
            "Attach"); 

    //Process the results. 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     File file = fc.getSelectedFile(); 
     log.append("Attaching file: " + file.getName() 
        + "." + newline); 
    } else { 
     log.append("Attachment cancelled by user." + newline); 
    } 
    log.setCaretPosition(log.getDocument().getLength()); 

    //Reset the file chooser for the next time it's shown. 
    fc.setSelectedFile(null); 
} 
0

가정 클래스 "A"이 파일 츄와 클래스 "B", 다음은 당신이 필요로 할 것입니다 값을 필요로를 표시하는 코드가 포함되어 있습니다 : 여기

코드의 관련 발췌 한 것입니다. 일부 이벤트 (버튼이 예를 들어 클릭 된) 및이가 직접 호출하지 말아야 할 때

class A { 
    private PropertyChangerSupport changer = new PropertyChangerSupport(this); 
    private File selectedFile = null; 

    public void addPropertyChangeListener(String property, PropertyChangeListener listener) { 
     changer.addPropertyChangeListener(property, listener); 
    } 

    public void removePropertyChangeListener(String property, PropertyChangeListener listener) { 
     changer.removePropertyChangeListener(property, listener); 
    } 

    public void actionPerformed(ActionEvent evt) { 
     // Prompt the user for the file 
     selectedFile = fc.getSelectedFile(); 
     changer.firePropertyChange(SELECTED_FILE_PROP, null, selectedFile); 
    } 
} 

class B { 
    public B(...) { 
     // ... 
     A a = ... 
     a.addPropertyChangeListener(new PropertyChangeListener() { 
      public void propertyChanged(PropertyChangeEvent evt) { 
       if (evt.getPropertyName().equals(A.SELECTED_FILE_PROP)) { 
        File selectedFile = (File)evt.getNewValue(); 
        // Do something with selectedFile 
       } 
      }}); 
    } 
} 
3

의 actionPerformed는 이벤트 발송 쓰레드에 의해 호출됩니다. FileChooser를 표시하고 선택한 파일을 반환하는 메서드가 필요한 경우 다른 곳에서뿐만 아니라 eventHandler가 호출 할 수있는 다른 메서드를 선언하십시오.

public void actionPerformed(ActionEvent e) { 
    File myFile = selectFile(); 
    doSomethingWith(myFile); 
} 

public File selectFile() { 
    int returnVal = fc.showDialog(FileChooserDemo2.this, 
            "Attach"); 
    //Process the results. 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     return fc.getSelectedFile(); 
    } else { 
     return null; 
    } 
} 
관련 문제