問1の解答.
イベントが来たら,同一処理を行うようにしています.
「MirrorFieldFrame.java」
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MirrorFieldFrame extends JFrame
implements DocumentListener,ActionListener,KeyListener {
private JPanel routePanel;
private JTextField inputField;
private JTextField outputDocEvtField;
private JTextField outputActEvtField;
private JTextField outputKeyEvtField;
public MirrorFieldFrame() {
setLocation(50,25);
setSize(360,240);
setResizable(true);
setTitle("MirrorField");
getContentPane().setLayout(new BorderLayout());
setBackground(SystemColor.menu);
setForeground(SystemColor.menuText);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addKeyListener(this);
setRoutePanel();
getContentPane().add(routePanel,BorderLayout.CENTER);
}
private void setRoutePanel() {
routePanel=new JPanel(new GridLayout(9,1,4,4));
routePanel.add(new JLabel("Input Field."));
inputField=new JTextField();
inputField.getDocument().addDocumentListener(this);
inputField.addActionListener(this);
inputField.setHorizontalAlignment(JTextField.LEFT);
routePanel.add(inputField);
outputDocEvtField=new JTextField();
outputDocEvtField.setEditable(false);
outputDocEvtField.setHorizontalAlignment(JTextField.RIGHT);
routePanel.add(new JLabel("Output Field (for DocumentEvent)."));
routePanel.add(outputDocEvtField);
outputActEvtField=new JTextField();
outputActEvtField.setEditable(false);
outputActEvtField.setHorizontalAlignment(JTextField.RIGHT);
routePanel.add(new JLabel("Output Field (for ActionEvent)."));
routePanel.add(outputActEvtField);
outputKeyEvtField=new JTextField();
outputKeyEvtField.setEditable(false);
outputKeyEvtField.setHorizontalAlignment(JTextField.RIGHT);
routePanel.add(new JLabel("Output Field (for KeyEvent)."));
routePanel.add(outputKeyEvtField);
routePanel.add(Box.createVerticalStrut(8)); // 空欄
}
public void changeString(JTextField tf) {
char[] inCharArray;
String outString;
inCharArray=inputField.getText().toCharArray();
outString="";
for(int i=0;i<inCharArray.length;i++) {
outString=inCharArray[i]+outString;
}
tf.setText(outString);
}
public void insertUpdate(DocumentEvent de) {
changeString(outputDocEvtField);
}
public void removeUpdate(DocumentEvent de) {
changeString(outputDocEvtField);
}
public void changedUpdate(DocumentEvent de) {
// do nothing.
}
public void actionPerformed(ActionEvent ae){
changeString(outputActEvtField);
}
public void keyTyped(KeyEvent ke){
// do nothing.
}
public void keyPressed(KeyEvent ke) {
// do nothing.
}
public void keyReleased(KeyEvent ke) {
changeString(outputKeyEvtField);
}
public static void main(String[] args) {
MirrorFieldFrame mff;
mff=new MirrorFieldFrame();
mff.setVisible(true);
}
}
|