AWT-JTest文本组件

package JText01;


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

//文本框输入文字,点击发送,文本域显示文本框输入的数据

//并判断文本框是否为空,为空的情况下做出响应

展示效果


public class JText01 extends JFrame {
//声明一个button
JButton sentBt;
//声明文本框
JTextField inputField;
//声明文本域
JTextArea chatContent;

public JText01() {

this.setLayout(new BorderLayout()); //设置布局BorderLayout

chatContent = new JTextArea(12,34); //创建一个文本域
JScrollPane showPanel = new JScrollPane(chatContent); //创建的ScrollPane滚动面板,将文本域作为显示的组件
JPanel inputPanel = new JPanel(); //创建一个Jpanel面板
chatContent.setEditable(false); //设置文本域不能编辑
inputField = new JTextField(20); //创建一个文本框
sentBt = new JButton("发送"); //创建一个按钮

//为“发送”按钮添加触发事件
sentBt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String content = inputField.getText(); //文本框中的数据复制与 content
if(content != null && !content.trim().equals("")) { //判断输入的信息是否为空
chatContent.append("本人:" +content+"\n"); //文本域显示的数据是从文本框中获取来的
}else {
chatContent.append("聊天信息不能为空\n");
}
inputField.setText(""); //将输入的文本框设置为空;
}
});

Label label = new Label("聊天内容");//添加一个标签,,用来描述输入框
//将组件添加到JPanel面板中
inputPanel.add(label);
inputPanel.add(sentBt);
inputPanel.add(inputField);

//将滚动面板、和Panel面板加到JFrame窗口中,文本域位于框架的中间位置
this.add(showPanel,BorderLayout.CENTER);
//设置InputPanel的位置在框架的下方,即南方
this.add(inputPanel, BorderLayout.SOUTH); ///一定要设置好布局,组件被覆盖,不能显示组件
//设置标题
this.setTitle("聊天窗口");
this.setSize(400, 300);
//点击关闭按钮,JFrame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setLocationRelativeTo(null);
}
 
public static void main(String [] args) {
new JText01();
}
}



















猜你喜欢

转载自blog.csdn.net/weixin_41585557/article/details/80671067