我正在构建一个图形用户界面,并使用FileChooser来获取用户选择的文件,所以一切正常,但现在我正在尝试获取所选文件的路径(通过 a 很容易地制作file.getAbsolutePath()
)。
但不知何故,我无法把它从课堂上拿出来......我想在课堂上有一个带有监听器的字符串路径,它看起来像这样:
private void browseButton(Canvas BasicSelection)
{
final Button btnBrowse = new Button(BasicSelection, SWT.NONE);
btnBrowse.setBounds(70, 29, 68, 23);
btnBrowse.setText("Browse");
btnBrowse.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
filechooser.createAndShowGUI(path);
sbtnBrowse = btnBrowse.getSelection();
}
});
launchEvent();
}
这是单击按钮时执行的操作:
public void actionPerformed(ActionEvent e)
{
//Set up the file chooser.
if (fc == null)
{
fc = new JFileChooser();
}
fc.addChoosableFileFilter(new Filter());
fc.setAcceptAllFileFilterUsed(false);
//Show it.
int returnVal = fc.showDialog(FileChooser.this,"Attach");
//Process the results.
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
setPath(file);
log.append("Attaching file: " + file.getName() + "." + newline);
// Here is where i would need to get the file... but how ?
}
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);
}
如何从类中获取文件名?
编辑:我已经尝试过使用 getter 和 setter,但奇怪的是,他在我实际写入内容之前尝试访问内容。
String path ;
/*
Rest of the code ...
*/
public void setPath(File input)
{
if (input != null)
{
this.path = input.getAbsolutePath();
System.out.println("path is now set correctly : ");
}
}
public String getPath()
{
return this.path;
}