IO流、圖形化用戶界面、事件監(jiān)聽
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Jsb extends JFrame implements ActionListener
{
JMenuBar cd;
JMenu cd1,cd2;
JMenuItem cdx1,cdx2;
JTextArea wby;
JScrollPane gd;
public static void main(String[] args)
{
Jsb js=new Jsb();
}
Jsb()
{
cd=new JMenuBar();
cd1=new JMenu("文件(F)");
cd1.setMnemonic('F');
cd2=new JMenu("編輯(E)");
cd2.setMnemonic('E');
cdx1=new JMenuItem("打開",new ImageIcon("photo/dk.jpg"));
cdx1.addActionListener(this);
cdx1.setActionCommand("open");
cdx2=new JMenuItem("保存",new ImageIcon("photo/bc.jpg"));
cdx2.addActionListener(this);
cdx2.setActionCommand("save");
wby=new JTextArea();
gd=new JScrollPane(wby);
cd1.add(cdx1); cd1.add(cdx2);
cd.add(cd1); cd.add(cd2);
this.setJMenuBar(cd); this.add(gd);
ImageIcon tp1=new ImageIcon("photo/jsb.jpg");
this.setIconImage(tp1.getImage());
this.setTitle("記事本");
this.setSize(400,300);
this.setLocation(300,280);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("open")) //
{
JFileChooser wjxz=new JFileChooser();//文件選擇框
wjxz.setDialogTitle("文件打開"); //對(duì)話框標(biāo)題
wjxz.showOpenDialog(null);//顯示打開對(duì)話框的模式,null默認(rèn)
wjxz.setVisible(true);
String wjlj=wjxz.getSelectedFile().getAbsolutePath();//選擇文件的全路徑
FileReader wjl=null; BufferedReader hcl=null;
try
{
wjl=new FileReader(wjlj);
hcl=new BufferedReader(wjl);
String s="",zfc="";
while((s=hcl.readLine())!=null)
{
zfc+=(s+"\n");
}
wby.setText(zfc);
}
catch(Exception a){}
finally
{
try
{
wjl.close();
hcl.close();
}
catch(Exception a1){}
}
}
else if(e.getActionCommand().equals("save"))
{
JFileChooser wjxz1=new JFileChooser();
wjxz1.setDialogTitle("另存為");
wjxz1.showSaveDialog(null);
wjxz1.setVisible(true);
String wjlj1=wjxz1.getSelectedFile().getAbsolutePath();
try
{
PrintStream pl=new PrintStream(wjlj1);
System.setOut(pl);
System.out.println(this.wby.getText());
}
catch(Exception a2){}
finally
{
try
{
}
catch(Exception a2){}
}
}
}
}
本人初學(xué)者,旨在記錄學(xué)習(xí)java的過(guò)程,歡迎大家指正,如果有針對(duì)上述部分代碼更優(yōu)秀的代碼請(qǐng)寫在評(píng)論區(qū),我一定會(huì)回復(fù)感謝并更正。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。