目前我有麻煩的事件驅動文件對話框傳遞給一個變量如何從java文件對話框中獲取值並將其傳遞給變量?
這檔節目應該如何工作,用戶按下一個文件路徑,那麼這將是在文件保存對象,準備進一步操作
下面的代碼
public class FileChooser {
private String filePath;
public FileChooser(){
prepareGUI();
}
private void prepareGUI(){
mainFrame = new Frame("Naufal File Chooser");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showFileDialogDemo(){
final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");
Button showFileDialogButton = new Button("Open File");
showFileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
statusLabel.setText("File Selected :"
+ fileDialog.getDirectory() + fileDialog.getFile());
//Here is where I should get the value, I tried set and get and as well as using return at the bottom both return null
// I'm trying to use setFilePath to store the file
setFilePath(fileDialog.getDirectory() + fileDialog.getFile());
}
});
controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
public void setFilePath(String file) {
this.filePath = file;
}
public String getFilePath() {
return filePath;
}
}
在main.java
public class FileMain {
public static void main(String[] args) throws IOException {
FileChooser fileChosen = new FileChooser();
fileChosen.showFileDialogDemo();
// Here it is always return null
String fileName = fileChosen.getFilePath();
System.out.println(fileName); // Always return null even before I click the file path.
File myFile = new File(fileName);
}
}
什麼是邏輯得到來自事件驅動對象的值?
Post FileDemo code。 – Amila
我的壞它應該是FileChoser –
而你的showFileDialogDemo()方法? – Amila