2013-05-03 6 views
3

나는 버튼이있어서 JFileChooser가 팝업되게하고 싶습니다. 나는 그것이 전체 파일 경로를 반환하려면,이버튼을 클릭 한 JFileChooser 클릭

JButton browse= new JButton("Browse"); 
add(browse); 
browse.addActionListener(new ClassBrowse()); 

public class ClassBrowse implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 
    int returnVal = fileChooser.showOpenDialog(this); 
     if (returnVal == JFileChooser.APPROVE_OPTION) { 
      File file = fileChooser.getSelectedFile(); 
      try { 
       // return the file path 
      } catch (Exception ex) { 
       System.out.println("problem accessing file"+file.getAbsolutePath()); 
      } 
     } 
     else { 
      System.out.println("File access cancelled by user."); 
     }  
    } 
} 

BHE 위 또한 오류를 The method showOpenDialog(Component) in the type JFileChooser is not applicable for the arguments (ClassName.ClassBrowse)

을 제공 노력했다. 어떻게해야합니까?

+0

JFrame을 어딘가에 설치했다고 가정하고''int returnVal = fileChooser.showOpenDialog (this);''를''int returnVal = fileChooser.showOpenDialog (frame);''로 대체하십시오. 당신의 코드. – santafebound

답변

1
  1. ActionListener를 사용하면 파일 선택에 this를 전달할 수 없습니다하는 Component 없습니다.
  2. 파일의 전체 경로를 얻으려면 File#getCanonicalPath을 볼 수 있지만 actionPerformed은 반환 유형이 void (또는 반환되지 않음) 만 반환하기 때문에 return 수 없습니다. 당신은, 그러나 ... 다른 방법을 전화 또는 예를 들어 ... JLabel 또는 JTextField의 텍스트를 설정, 다른 변수를 설정할 수 있습니다
0

당신은 파일 이름 문자열을 보유하고 인스턴스 변수를 설정할 수 있습니다 의 actionPerformed 같은

private String fileName; 
....... 
your code 
....... 
public void actionPerformed(ActionEvent e) { 
int returnVal = fileChooser.showOpenDialog((Component)e.getSource()); 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     File file = fileChooser.getSelectedFile(); 
     try { 
      fileName = file.toString(); 
     } catch (Exception ex) { 
      System.out.println("problem accessing file"+file.getAbsolutePath()); 
     } 
    } 
    else { 
     System.out.println("File access cancelled by user."); 
    }  
} 
+0

'File'을'String'으로 돌려주지 않으면, 그것은 무의미합니다. –

+0

사용자가 완전한 경로를 원한다고 지정했습니다. – prasanth

+0

이것은'File' 객체에서 쉽게 얻을 수 있습니다. 따라서 File 객체를 저장하십시오. 게다가, 때로는 OP가 가장 논리적 인 것을 요구하지 않고, 발에서 스스로를 쏘는 방법을 묻는다면 방향을 알려주겠습니까? –

1

당신은 용기를 전달할 수 있습니다 (이 수도 JFrame의, JDialog를, JApplet에 또는 일) 당신의 JButton가

fileChooser.showOpenDialog()

0에있다

파일 선택기는 해당 컨테이너 위에 모달 대화 상자로 열립니다.

관련 문제