importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.io.*;
public classwork7_gai1extendsJFrame {
/**
*
*/
JFramejf;
JMenuBarmenubar;
JMenumenuFile;
JMenuItemclass1,class2,class3,class4;
JTextAreatxt;
private classclass1HandlerimplementsActionListener{
@Override
public voidactionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
txt.setText(readTxtFile("D:\\class1.txt"));
}
}
private classclass2HandlerimplementsActionListener{
@Override
public voidactionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
txt.setText(readTxtFile("D:\\class2.txt"));
}
}
private classclass3HandlerimplementsActionListener{
@Override
public voidactionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
txt.setText(readTxtFile("D:\\class3.txt"));
}
}
private classclass4HandlerimplementsActionListener{
@Override
public voidactionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
txt.setText(readTxtFile("D:\\class4.txt"));
}
}
publicwork7_gai1() {
jf=newJFrame();
jf.setLayout(newBorderLayout());
txt=newJTextArea(5,10);
txt.setTabSize(4);
txt.setSize(100,100);
txt.setLineWrap(true);// 激活自动换行功能
txt.setBackground(Color.white);
menubar =newJMenuBar();
menuFile =newJMenu("各班级成绩");
menubar.add(menuFile);
class1 =newJMenuItem("2004(1)班");
class1.addActionListener(newclass1Handler());
class2 =newJMenuItem("2004(2)班");
class2.addActionListener(newclass2Handler());
class3 =newJMenuItem("2004(3)班");
class3.addActionListener(newclass3Handler());
class4 =newJMenuItem("2004(4)班");
class4.addActionListener(newclass4Handler());
menuFile.add(class1);
menuFile.add(class2);
menuFile.add(class3);
menuFile.add(class4);
jf.add(menubar,BorderLayout.NORTH);
jf.add(txt, BorderLayout.CENTER);
jf.setSize(660,400);
jf.setLocation(400,200);
jf.setVisible(true);// 可视化
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭窗口时退出程序
}
String readTxtFile(String filePath) {
try{
StringBuffer sb =newStringBuffer();
String encoding ="GBK";
File file =newFile(filePath);
if(file.isFile() && file.exists()) {// 判断文件是否存在
InputStreamReader read =newInputStreamReader(
newFileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader =newBufferedReader(read);
String lineTxt =null;
while((lineTxt = bufferedReader.readLine()) !=null) {
sb.append(lineTxt);
}
read.close();
String str = sb.toString();
returnstr;
}else{
System.out.println("找不到指定的文件");
}
}catch(Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return null;
}
/**
* Launch the application.
*/
public static voidmain(String[] args) {
newwork7_gai1();
}
}
网友评论