黑马程序员——java高新技术——GUI图形化用户界面

点击打开链接 点击打开链接 点击打开链接 点击打开链接 点击打开链接

 
//菜单栏、菜单的练习
ackage mymenu;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class  MyText
{
	private Frame f;
	private MenuBar mb;
	private Menu mu1,mu2;
	private MenuItem mi1,mi2,saveMI,openMI;

	private TextArea ta;
	private File fi;

	private FileDialog fd1,fd2;
	MyText()
	{
       init();
	}
	public void init()
	{
		f=new Frame();
		f.setBounds(200,300,650,600);

		mb=new MenuBar();
		mu1=new Menu("文件");
        mu2=new Menu("子菜单");
		mi1=new MenuItem("子条目");
		mi2=new MenuItem("退出");
		saveMI=new MenuItem("保存");
		openMI=new MenuItem("打开");

		fd1=new FileDialog(f,"保存",FileDialog.SAVE);
		fd2=new FileDialog(f,"打开",FileDialog.LOAD);

		mu2.add(mi1);
		mu1.add(mu2);
		mu1.add(mi2);
		mb.add(mu1);
		mu1.add(openMI);
		mu1.add(saveMI);
		f.setMenuBar(mb);

		ta=new TextArea();
		f.add(ta);
        
		myEvent();
		f.setVisible(true);

	}
	public void myEvent()
	{
		saveMI.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				if(fi==null){
			      fd1.setVisible(true);
                  String path=fd1.getDirectory();
			     	String name=fd1.getFile();
			    	if(path==null && name==null)
				    	return ;
				   fi=new File(path,name);
				}
				try
				{
                    fi.createNewFile();
					BufferedWriter br=new BufferedWriter(new FileWriter(fi));
			        br.write(ta.getText());
					br.close();
				}
				catch (IOException ee)
				{
					System.out.println("打开文件异常");
				}
				
			}
		});
		openMI.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				fd2.setVisible(true);
				String path=fd2.getDirectory();
				String name=fd2.getFile();
				if(path==null && name==null)
					return ;
				ta.setText("");
				File file=new File(path,name);
				try
				{
					BufferedReader br=new BufferedReader(new FileReader(file));
					for(String str=br.readLine();str!=null;str=br.readLine())
					{
						ta.append(str+"\r\n");
					}
					br.close();
				}
				catch (IOException ee)
				{
					System.out.println("打开文件异常");
				}
				
			}
		});
		mi2.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				System.exit(0);
			}
		});
		f.addWindowListener(new WindowAdapter()
		{
			public void WindowClosing(WindowEvent e)
			{
                System.exit(0);
			}
		});
	}
	public static void main(String[] args) 
	{
		new MyText();
	}
}


 

你可能感兴趣的:(黑马程序员——java高新技术——GUI图形化用户界面)