SwingのDocumentEventの追加について
内部クラスを使ってDocumentEvent
を使いたいのですが、addDocumentListener
の使い方がいまいちわかりません。どこを修正すべきでしょうか? よろしくお願いします。
import java.awt.*;
import java.awt.event.*;
import javax.lang.model.element.Element;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Caret;
import javax.swing.text.Document;
class CaesarFrame{
JFrame frame;
JTextField textField1, textField2;
JButton button;
JPanel panel1, panel2;
JComboBox<Object> comboBox1;
Object[] ob = {'A','B','C','D','E','F','G','H','I','J','K','L'
,'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
Container contentPane;
JLabel label;
// Constructor
CaesarFrame(){
frame = new JFrame("SwingLab");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 110);
frame.setLayout(new BorderLayout());
frame.setLocationRelativeTo(null);
contentPane = frame.getContentPane();
textField1 = new JTextField(20);
textField2 = new JTextField(28);
textField2.setEditable(false);
button = new JButton("Code!");
comboBox1 = new JComboBox<Object>(ob);
label = new JLabel("Output:");
panel1 = new JPanel();
panel2 = new JPanel();
panel1.add(comboBox1);
panel1.add(textField1);
panel1.add(button);
panel2.add(label);
panel2.add(textField2);
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2,BorderLayout.WEST);
frame.setVisible(true);
ActionListener buttonCode = new OkButtonActionListener();
button.addActionListener(buttonCode);
KeyAdapter key = new InputFieldKeyListener();
textField1.addKeyListener(key);
//この箇所がよくわかりません。
KeyAdapter key2 = new InputFieldKeyListener();
Document doc = ((DocumentEvent) key2).getDocument();
doc.addDocumentListener((DocumentListener) key);
}
class InputFieldKeyListener extends KeyAdapter implements DocumentListener{
public void keyTyped(KeyEvent e) {
char temp = e.getKeyChar();
String ch =String.valueOf(temp);
char offset = (char) comboBox1.getSelectedItem();
textField2.setText(Caesar.caesarCode(ch,offset));
}
@Override
public void changedUpdate(DocumentEvent e) {
System.out.println("Changed");
}
@Override
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
System.out.println("Inserted");
}
@Override
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
System.out.println("Removed");
}
}
private class OkButtonActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String message = textField1.getText();
char offset = (char) comboBox1.getSelectedItem();
textField2.setText(Caesar.caesarCode(message,offset));
}
}
}