下面的问题
JtextField,事件处理在其类中完成。修改一个新类Question2,以便不更改按钮侦听器,但文本事件由名为Q2textHandler的单独TextHandler类处理。您可以使用PowerPoint中的ButtonHandler类作为指南,但您应该创建自己的TextHandler类并将其与JTextField关联。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Question4 extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private JButton cancelButton;
private JButton okButton;
public Question4() {
setTitle("My Button and Frame Handler");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation( EXIT_ON_CLOSE );
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout() );
cancelButton = new JButton("CANCEL");
okButton = new JButton("OK");
JTextField inputLine = new JTextField();
inputLine.setColumns(22);
contentPane.add(inputLine);
inputLine.addActionListener(this);
contentPane.add(okButton);
contentPane.add(cancelButton);
okButton.addActionListener(this);
cancelButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton)
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
setTitle("You clicked " + buttonText);
}
else
{
JTextField textField = (JTextField) event.getSource();
setTitle("You entered ' " + textField.getText() + "'");
}
}
public static void main(String[] args){
Question4 window = new Question4();
window.setVisible(true);
}
}
我的问题是:
这是我到目前为止所拥有的
public class Q2textHandler extends JFrame implements ActionListener{
private String text;
public void actionPerformed(ActionEvent event) {
{
JTextField textField = (JTextField) event.getSource();
String text = textField.getText();
setTitle("You've entered" + text);
}
}