欢迎来到天天文库
浏览记录
ID:39550037
大小:522.50 KB
页数:29页
时间:2019-07-06
《JavaSwing的复杂控件》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、9.1JTextArea(文本区)JTextArea是一个显示纯文本的多行区域,它具有换行功能,同时能也可以借助JScrollPane提供垂直和水平滚动的功能。9.1.1JTextArea的构造函数JTextArea()构造新的TextAreaJTextArea(Document doc)构造新的JTextArea,使其具有给定的文档模型,所有其他参数均默认为(null,0,0)JTextArea(int rows,int columns)构造具有指定行数和列数的新的空TextArea9.1.2JTextArea的常用方
2、法append(String str)将给定文本追加到文档结尾StringgetText()返回JTextArea中的内容intgetLineCount()返回JTextArea中当前文本所占的行数setLineWrap(boolean wrap)设置文本区的换行策略9.1.3文本区与文本域下面示例展示了文本区与文本域的文本显示特点,文本域只能输入和显示单行文本,且不能提供换行与滚动条功能,而文本区则既可以提供通过换行的多行显示,也能通过将文本区添加到一个JScrollPane(滚动窗格)中实现垂直和水平的滚动功能。示例
3、1packageedu.learn;importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;publicclassJTextAreaExampleextendsJFrameimplementsActionListener{JLabeluserLab=newJLabel("发信人:",JLabel.LEFT);JTextFielduserText=newJTextField(20);JLabelmailLab=newJLabel("所发信息:",JLabel.
4、LEFT);JTextFieldmailText=newJTextField(20);JLabelinfoLabe=newJLabel("信息记录:",JLabel.LEFT);JTextAreatxtArea=newJTextArea(5,20);publicJTextAreaExample(){init();setTitle("文本域练习");setBounds(200,200,250,270);setResizable(false);setVisible(true);setDefaultCloseOperation
5、(JFrame.EXIT_ON_CLOSE);}publicvoidinit(){setLayout(newFlowLayout(FlowLayout.LEFT));add(userLab);add(userText);add(mailLab);add(mailText);add(infoLabe);//JTextArea不能自己提供滚动条,它必须借助于滚动窗格JScrollPaneJScrollPanescroll=newJScrollPane(txtArea);txtArea.setEditable(false);a
6、dd(scroll);mailText.addActionListener(this);}publicvoidactionPerformed(ActionEvente){txtArea.append(userText.getText()+":"+mailText.getText()+"");mailText.setText("");}publicstaticvoidmain(String[]args){newJTextAreaExample();}}运行结果:9.1.4文本区上的DocumentEvent事件JTex
7、tArea经常触发的事件是DocumentEvent事件,DocumentEvent类放在javax.swing.envent包中。当文本区中的文本进行编辑操作,使文本区中的文本内容发生变化时,就会导致文本区中的文档模型中的数据发生变化,从而导致文本区触发DocumentEvent事件。DocumentEvent事件实现的接口以及接口中的抽象事件处理方法如下:事件类型对应监听器接口接口中的抽象事件方法DocumentEventDocumentListenerpublicvoidchangeUpdate(DocumentE
8、vente) ;publicvoidremoveUpdate(DocumentEvente) ;publicvoidinsertUpdate(DocumentEvente) ;以下示例展示了文本区的DocumentEvent(文档事件)的处理方法,该示例中有两个文本区,当用户朝一个文本区中输入文本时,就触发Docum
此文档下载收益归作者所有