GUI用户图形界面
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GUI用户图形界面相关的知识,希望对你有一定的参考价值。
/*记事本小练习 * GUI & IO综合运用 */ import java.awt.*; import java.awt.event.*; import java.io.*; public class Test33 { public static void main(String[] args) { MyTest mytest = new MyTest(); mytest.frameInit(); //运行窗口 } } class MyTest{ //定义成员变量,包括窗体,文本区域,对话框,File类,菜单等 private Frame myFrame; private TextArea ta; private FileDialog openDialog; private FileDialog saveDialog; private File f; private MenuBar mb ; private Menu m1; private MenuItem mi1,mi2,mi3; MyTest() { } public void frameInit() { //实现窗体 myFrame = new Frame("MyEditor"); myFrame.setBounds(100, 50, 700, 650); ta = new TextArea(); myFrame.add(ta); openDialog = new FileDialog(myFrame, "打开文件", FileDialog.LOAD); saveDialog = new FileDialog(myFrame,"保存",FileDialog.SAVE); menuInit(); //调用菜单实现方法 myEvent(); //调用事件 myFrame.setVisible(true); } public void menuInit() { //菜单实现 mb = new MenuBar() ; m1 = new Menu("文件"); mi1 = new MenuItem("打开"); mi2 = new MenuItem("保存"); mi3 = new MenuItem("关闭"); mb.add(m1); m1.add(mi1); m1.add(mi2); m1.add(mi3); myFrame.setMenuBar(mb); } public void myEvent() { //事件 myFrame.addWindowListener(new WindowAdapter() { //关闭窗口红叉事件 public void windowClosing(WindowEvent e) { System.exit(0); } }); mi1.addActionListener(new ActionListener() { //打开事件 @Override public void actionPerformed(ActionEvent e) { openDialog.setVisible(true); String dirPath = openDialog.getDirectory(); String name = openDialog.getFile(); if(dirPath == null||name ==null) return; ta.setText(""); //System.out.println(dirPath); f = new File(dirPath, name); String temp = null; try { BufferedReader bf = new BufferedReader(new FileReader(f)); while((temp = bf.readLine())!=null) ta.append(temp+"\r\n"); } catch (IOException e1) { e1.printStackTrace(); } } }); mi2.addActionListener(new ActionListener() { //保存事件 @Override public void actionPerformed(ActionEvent e) { saveDialog.setVisible(true); String dirPath = saveDialog.getDirectory(); String name = saveDialog.getFile(); if(dirPath == null||name ==null) return; f = new File(dirPath, name); String temp = null; try { BufferedWriter bw = new BufferedWriter(new FileWriter(f)); String text = ta.getText(); bw.write(text); bw.flush(); } catch (IOException e1) { e1.printStackTrace(); } } }); mi3.addActionListener(new ActionListener() { //关闭事件 public void actionPerformed(ActionEvent E) { System.exit(0); } } ); } }
以上是关于GUI用户图形界面的主要内容,如果未能解决你的问题,请参考以下文章