在 JFileChooser 中选择一个文件后,我希望 JTextField 附加到它的路径。我写了下面的代码:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
public class Program extends JFrame{
public static void main(String[] args){
new Program();
}
public Program(){
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setTitle("Projekt Java");
JPanel thePanel = new JPanel();
thePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JButton button1 = new JButton("Wybierz plik:");
JButton button2 = new JButton("Dodaj");
JTextField text = new JTextField(23);
JTextArea textArea1 = new JTextArea(10,30);
thePanel.add(button1);
thePanel.add(text);
thePanel.add(button2);
thePanel.add(textArea1);
this.add(thePanel);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
String directory = fileChooser.getCurrentDirectory().toString();
text.append(directory); // doesn't work
}
}
});
this.setVisible(true);
}
private static void createFileChooser(final JFrame frame) {
String filename = File.separator+"tmp";
JFileChooser fileChooser = new JFileChooser(new File(filename));
// pop up an "Open File" file chooser dialog
fileChooser.showOpenDialog(frame);
System.out.println("File to open: " + fileChooser.getSelectedFile());
// pop up an "Save File" file chooser dialog
fileChooser.showSaveDialog(frame);
System.out.println("File to save: " + fileChooser.getSelectedFile());
}
}
但是,追加功能在这里不起作用。有人可以解释为什么会这样吗?除非它不在 Action 监听器中,否则它会起作用。我的错误是:
不能在不同方法中定义的内部类中引用非最终变量文本 JTextField 类型的方法 append(String) 未定义
我改为text.append(directory); text.setText(目录);并将 JTextfield 修改为最终的并且它有效。
最佳答案
使用 text.setText(directory)
而不是 text.append(directory)
。
append()
方法用于JTextArea
,JTextField
没有。
并且您必须将 JTextField 文本
声明为 final JTextField 文本
。
关于java - 为什么 append 函数在 ActionListener 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487818/