jtextfield转换成一个单独的类

zte4gxcn  于 2021-07-09  发布在  Java
关注(0)|答案(0)|浏览(392)

下面的问题
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);
    }
}

我的问题是:
我不知道他在问什么。我有一个粗略的想法,想做一个settitle的返回语句。
我不知道是否必须在我正在创建的类中实现actionlistener。
这是我目前掌握的情况

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);
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题