ItemEvent事件

来源:互联网 发布:在线开放课程 网络课程 编辑:程序博客网 时间:2024/06/10 21:49

现在直接贴上代码

E7.java

package liqi;public class E7 {public static void main(String args[]) {WindowItemEvent win = new WindowItemEvent();win.setBounds(100, 100, 460, 360);win.setTitle("处理ItemEvent事件");}}

WindowItemEvent.java

package liqi;import java.awt.*;import javax.swing.*;import java.io.*;public class WindowItemEvent extends JFrame {/** *  */private static final long serialVersionUID = 1L;JComboBox choice;JTextArea textShow;PoliceListen listener;public WindowItemEvent() {init();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}void init() {setLayout(new FlowLayout());choice = new JComboBox();choice.addItem("请选择文件:");File dir = new File("C:\\Users\\Administrator\\workspace\\win\\src\\liqi");FileAccept fileAccept = new FileAccept();fileAccept.setExtendName("java");String[] fileName = dir.list(fileAccept);for (String name : fileName) {choice.addItem(name);}textShow = new JTextArea(10, 30);listener = new PoliceListen();listener.setJComboBox(choice);listener.setJTextArea(textShow);choice.addItemListener(listener); // choice是事件源,listener是监视器add(choice);add(new JScrollPane(textShow));}class FileAccept implements FilenameFilter { // 内部类private String extendName;public void setExtendName(String s) {extendName = "." + s;}public boolean accept(File dir, String name) {return name.endsWith(extendName);}}}

PoliceListen.java

package liqi;import java.awt.event.*;import java.io.*;import javax.swing.*;public class PoliceListen implements ItemListener {JComboBox choice;JTextArea textShow;public void setJComboBox(JComboBox box) {choice = box;}public void setJTextArea(JTextArea area) {textShow = area;}public void itemStateChanged(ItemEvent e) {textShow.setText(null);try {String fileName = choice.getSelectedItem().toString();fileName = "C:\\Users\\Administrator\\workspace\\win\\src\\liqi\\"+fileName;File file = new File(fileName);FileReader inOne = new FileReader(file);BufferedReader inTwo = new BufferedReader(inOne);String s = null;while ((s = inTwo.readLine()) != null) {textShow.append(s + "\n");}inOne.close();inTwo.close();} catch (Exception ee) {textShow.append(ee.toString());}}}

练习这个程序的时候,遇到几个问题

1.Item显示不了想要显示的当前文件,我只好用绝对地址

2.有了文件名,我发现打开文件失败,无奈,我又叫上绝对地址,实验,发现自己路径格式写错了

3.好不容易才解决格式问题,好了,终于可以显示文件的内容了,算是成功了

4.File dir = new File("src/liqi/");将上述路径可以改成这个,也是可以的,这应该叫相对路径,好了就这样结束了


这段程序里面,要积累的知识

1.java的io操作

2.java界面操作

基础就不用说了,我总结两种字符串连接方法,1.使用“+”符号,这个简单 2.使用concat()连接两个字符串

原创粉丝点击