编程包含一个文本框和一个文本区域,在文本框中按回车键时,把文本框的内容写入文本区域

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class Main{

    public static void main(String[] args) {
        new NewFrame();
    }

}

class NewFrame extends JFrame {

    JFrame frame;
    JTextField field;
    JTextArea area;
    Police police;

    public NewFrame() {

        frame = new JFrame("NewWindow");
        field = new JTextField();
        area = new JTextArea("textarea");
        police = new Police();

        frame.setBounds(500, 400, 500, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        field.setEnabled(true);
        field.setEditable(true);
        field.addActionListener(police);
        field.setColumns(50);
        frame.add(field, BorderLayout.SOUTH);

        area.setEditable(false);
        area.setEnabled(true);
        area.setRows(10);
        area.setSize(500, 270);
        frame.add(area, BorderLayout.NORTH);
        area.setText("");
        area.setFont(new Font("楷体", Font.BOLD, 20));

        frame.validate();
        frame.setVisible(true);
    }

    class Police implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String string = field.getText();

            if (string.equals("cls"))
                area.setText("");
            else
                area.append("\n" + string);

            field.setText("");
        }
    }

}
0

Leave a Reply

Your email address will not be published.