如何将文件名写入标签

时间:2014-03-06 13:15:47

标签: file actionlistener jlabel jfilechooser

我希望JMileChooser从JMenuItem获取所选文件的名称,并在选中JCheckBoxMenuItem时在JLabel中显示它。我可以选择文件,但不能有它的名字。代码的重要部分如下所示,

private JFileChooser fc;
private JLabel currentDocPanel;
public JCheckBoxMenuItem viewOpt;

public String getFileName() {
    String str = fc.getSelectedFile().getName();
    return str;
}
private class ActionEventHandler implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

if (e.getSource() == viewOpt) {
            if (currentDocPanel.isVisible()) {
                currentDocPanel = new JLabel(getFileName());
                currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
                add(currentDocPanel, BorderLayout.SOUTH);
    }
  }
}

2 个答案:

答案 0 :(得分:1)

感谢您的回复。我尝试了您提供的代码,但未在标签上看到文件名。我稍微更改了我的代码,我能够在标签中看到文本,但问题是我只能在握住窗口并用鼠标展开它时看到它。当单击JCheckBoxMenuItem时,我在actionPerformed中调用此函数。这就是我所做的;

 public void getFileName() throws Exception {
    System.out.println("getFileName");
    try {
        File getfile = fc.getSelectedFile();
        boolean check = getfile.exists();
        if (check) {
            System.out.println("File Name: " + getfile.getName()); //to check
            String nameToLabel = "File Name: " + getfile.getName();
            currentDocPanel = new JLabel(nameToLabel);
            //currentDocPanel.setText(String.valueOf(fc.getSelectedFile()));
            currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
            add(currentDocPanel, BorderLayout.SOUTH);
        }
    } catch (Exception e) {
    }

}

答案 1 :(得分:0)

相当简单:

currentDocPanel.setText(String.valueOf(Your_JFileChooser.getSelectedFile()));

应该有效。在这里,我只获取JFC的selectedFile并将输出转换为String。