Java JTextField转换为一个单独的类
下面的问题 JtextField,事件处理在其类内完成。修改一个新的类Question2,这样按钮侦听器不会更改,但是文本事件由一个名为Q2textHandler的单独TextHandler类处理。您可以使用PowerPoint中的ButtonHandler类作为指南,但您应该创建自己的TextHandler类并将其与JTextField关联Java JTextField转换为一个单独的类,java,swing,actionlistener,jtextfield,Java,Swing,Actionlistener,Jtextfield,下面的问题 JtextField,事件处理在其类内完成。修改一个新的类Question2,这样按钮侦听器不会更改,但是文本事件由一个名为Q2textHandler的单独TextHandler类处理。您可以使用PowerPoint中的ButtonHandler类作为指南,但您应该创建自己的TextHandler类并将其与JTextField关联 import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.A
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);
}
}
您的
Q2TextHandler
类不需要扩展JFrame
——只有生成自己GUI的类需要扩展JFrame
。相反,您应该在文本处理程序的构造函数中接受一个JFrame
实例。把它存储起来,你可以在适当的时候调用它的setTitle
。。。。但总的来说,你正朝着正确的方向前进。最后,您将希望为Q2TextHandler
类指定一个新实例作为另一个类中JTextField
的操作侦听器。也许可以尝试更多的编辑,并用最新的代码更新您的问题?因此,我要删除else语句,因为我觉得这个练习要求我的是删除它。