mas*_*don 3 java swing actionlistener jtextarea
我有一个程序在一个JTextArea中获取带有文件路径的输入字符串,然后将其内容加载到第二个JTextArea.问题是当使用JTextArea时,我无法添加一个actionListener,它将在离开此字段时在第二个JTextArea中加载内容.如何解决这个问题?
protected JTextArea inputField, outputField;
public Main(){
super(new BorderLayout());
inputField = new JTextArea(5, 20);
outputField = new JTextArea(2, 20);
//inputField.addActionListener(this);
inputField.setEditable(false);
JScrollPane scroller2 = new JScrollPane(inputField);
JScrollPane scroller1 = new JScrollPane(outputField);
this.add(scroller1, BorderLayout.WEST);
this.add(scroller2, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent evt) {
String text = inputField.getText();
(loading contents of file)
}
Run Code Online (Sandbox Code Playgroud)
你不想要一个actionListener,你想要一个FocusListener.
JTextArea text = ...;
text.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
// Load your content.
}
});
Run Code Online (Sandbox Code Playgroud)