JtextareaにActionListenerを追加するための回避策
-
29-09-2019 - |
質問
1つのjtextareaにファイルパスを備えた入力文字列を取得し、そのコンテンツを2番目のjtextareaにロードするプログラムがあります。問題は、JTextareaを使用する場合、このフィールドを離れるときに2番目のjTextareaにコンテンツをロードするActionListenerを追加できないことです。この問題を回避する方法は?
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)
}
解決
あなたはactionlistenerを望んでいません、あなたは FocusListener.
JTextArea text = ...;
text.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
// Load your content.
}
});
他のヒント
または、私の最初のコメントを具体化するために、JButton(&A JeditorPaneにコンテンツに)を使用するこのsscceを試してください。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.File;
class LoadDocument {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame();
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel contentPane = new JPanel( new BorderLayout(3,3) );
contentPane.setBorder( new EmptyBorder(5,5,5,5) );
// has convenience methods to load documents..
final JEditorPane content = new JEditorPane();
JScrollPane sp = new JScrollPane(content);
sp.setPreferredSize( new Dimension(400,400) );
contentPane.add( sp, BorderLayout.CENTER );
final JFileChooser jfc = new JFileChooser();
JButton open = new JButton("Open File");
open.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = jfc.showOpenDialog(f);
if (result==JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
try {
content.setPage( file.toURI().toURL() );
} catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
f,
"File load error!",
e.getMessage(),
JOptionPane.ERROR_MESSAGE
);
}
}
}
} );
JToolBar tb = new JToolBar();
tb.add(open);
contentPane.add( tb, BorderLayout.NORTH );
f.setContentPane( contentPane );
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
ActionListenerのみが必要な場合は、この例を確認してください。
textArea.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
actionListener.actionPerformed(new ActionEvent(e.getSource(), e.getID(), "focusLost"));
}
});
その平等:
textArea.addActionListener(actionListener);
PS ActionListenerは、そのように使用するための最終またはクラスのフィールドでなければなりません。
所属していません StackOverflow