怎样用java做一个最简单的界面,比如就浏览打开一个文本之类的?求代码,求指点,我刚学

 我来答
帐号已注销
2013-11-09
知道答主
回答量:26
采纳率:0%
帮助的人:21.8万
展开全部
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class MyMenuTest
{

private Frame f;
private MenuBar bar;
private TextArea ta;
private Menu fileMenu;
private MenuItem openItem,saveItem,closeItem;

private FileDialog openDia,saveDia;

private File file;
MyMenuTest()
{
init();
}
public void init()
{
f = new Frame("my window");
f.setBounds(300,100,650,600);

bar = new MenuBar();

ta = new TextArea();

fileMenu = new Menu("文件");

openItem = new MenuItem("打开");
saveItem = new MenuItem("保存");
closeItem = new MenuItem("退出");

fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(closeItem);
bar.add(fileMenu);

f.setMenuBar(bar);

openDia = new FileDialog(f,"我要打开",FileDialog.LOAD);
saveDia = new FileDialog(f,"我要保存",FileDialog.SAVE);

f.add(ta);
myEvent();

f.setVisible(true);

}
private void myEvent()
{

saveItem.addActionListener(new ActionListener()
{

public void actionPerformed(ActionEvent e)
{
if(file==null)
{
saveDia.setVisible(true);

String dirPath = saveDia.getDirectory();
String fileName = saveDia.getFile();
if(dirPath==null || fileName==null)
return ;
file = new File(dirPath,fileName);
}

try
{
BufferedWriter bufw = new BufferedWriter(new FileWriter(file));

String text = ta.getText();

bufw.write(text);
//bufw.flush();
bufw.close();
}
catch (IOException ex)
{
throw new RuntimeException();
}

}
});

openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openDia.setVisible(true);
String dirPath = openDia.getDirectory();
String fileName = openDia.getFile();
// System.out.println(dirPath+"..."+fileName);
if(dirPath==null || fileName==null)
return ;

ta.setText("");
file = new File(dirPath,fileName);

try
{
BufferedReader bufr = new BufferedReader(new FileReader(file));

String line = null;

while((line=bufr.readLine())!=null)
{
ta.append(line+"\r\n");
}

bufr.close();
}
catch (IOException ex)
{
throw new RuntimeException("读取失败");
}

}
});

closeItem.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 MyMenuTest();
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式