1

下面的问题

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

我的问题是:

  1. 我不知道他在问什么。我有一个粗略的想法,并认为只是为 setTitle 做一个返回声明。
  2. 我不知道我是否必须在我正在制作的类中实现 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);
    }
}
4

0 回答 0