将JTextField放入一个单独的类中

时间:2012-08-25 05:56:58

标签: java swing actionlistener jtextfield

下面的问题

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做一个return语句。
  2. 我不知道是否必须将ActionListener实现到我正在制作的类中。
  3. 这是我到目前为止所拥有的

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

0 个答案:

没有答案