JAVA-掌握DocumentEvent事件响应的处理方式。

本文介绍了一个Java应用程序,通过监听DocumentEvent事件,实现在文本框(textInput)中输入数值时,实时计算并显示其和与平均值在另一个文本区域(textShow)中。这种响应式设计能动态更新显示结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要求:
编写应用程序,有一个标题为“计算”的窗口,窗口中添加两个文本区textInput和textShow,当在textInput中输入若干个数时,textShow同时对textInput中的数进行求和运算,并求出平均值

在这里插入图片描述
代码如下:

package 实验6;

public class test {
	public static void main(String args[]){
		WindowDocument win=new WindowDocument();
		win.setBounds(100,100,590,500);
		win.setTitle("计算");
	}

}
package 实验6;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class WindowDocument extends JFrame {
	JTextArea textInput,textShow;
	TextListener textChangeListener;//textInput的监视器
	HandleListener handleListener;
	WindowDocument(){
		init();
		setLayout(new FlowLayout());
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	void init(){
		textInput=new JTextArea(15,20);
		textShow=new JTextArea(15,20);
		textShow.setLineWrap(true);
		textShow.setWrapStyleWord(true);
		add(textInput);
		add(textShow);
		textChangeListener=new TextListener();
		handleListener=new HandleListener();
		textChangeListener.settextInput(textInput);
		textChangeListener.settextShow(textShow);
		(textInput.getDocument()).addDocumentListener(textChangeListener);//向文档注册监视器
		
		
	}
	

}
package 实验6;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

public class TextListener implements DocumentListener{
	JTextArea textInput,textShow;
	public void settextInput(JTextArea s){
		 textInput=s;
	}
	public void settextShow(JTextArea s){
		textShow=s;
	}
	public void changedUpdate(DocumentEvent e) {
		String str=textInput.getText();
		String regex="\\D+";
		String digitWord[]=str.split(regex);
		double sum=0,mean;
		textShow.setText(null);
		textShow.append("求和的数组元素是:[");
		for(int i=0;i<digitWord.length;i++){
			int item = Integer.parseInt(digitWord[i]); 
			sum=sum+item;
			textShow.append(digitWord[i]+",");
		}
		mean=sum/digitWord.length;
		textShow.append("]"+"\n");
		textShow.append("和:"+sum+"\n");
		textShow.append("平均值:"+mean);
	}
	public void insertUpdate(DocumentEvent e) {
		changedUpdate(e);
		
	}
	public void removeUpdate(DocumentEvent e) {
		changedUpdate(e);
		
	}

}
package 实验6;
import java.awt.event.*;
import javax.swing.*;
public class HandleListener implements ActionListener {
	JTextArea textInput,textShow;
	public void settextInput(JTextArea s){
		 textInput=s;
	}
	public void settextShow(JTextArea s){
		textShow=s;
	}
	public void actionPerformed(ActionEvent e) {
		String str=e.getActionCommand();
		
		
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值