?? texteditor.java
字號:
// 簡單文本編輯器 @author Yangxiaoyan CS 0501
//實現功能:可以新建、打開、編輯和保存文本文件
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class TextEditor
{
public static void main(String[] args)
{
TextEditorFrame frame = new TextEditorFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
class TextEditorFrame extends JFrame implements ActionListener
{
JTextArea text; //將text作為公共變量,因為讀寫文件都會用到
JScrollPane sp;//
Container con=getContentPane();
public TextEditorFrame()
{
con.setLayout(new BorderLayout());
setSize(400,300);
setTitle("簡單文本編譯器");
JMenuBar menuBar = new JMenuBar(); //新建菜單欄
setJMenuBar(menuBar);//設定窗口的菜單欄
JMenu fileMenu = new JMenu("File");//新建菜單
menuBar.add(fileMenu); //加入菜單
JMenuItem newi = new JMenuItem("New"); //新建并加入菜單項目
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
fileMenu.add(newi);
fileMenu.add(open);
fileMenu.add(save);
fileMenu.addSeparator();
fileMenu.add(exit);
text=new JTextArea(" 長相思\n\n 山一程\n 水一程\n 身向榆關那畔行\n夜深千帳燈\n\n風一更\n雪一更\n聒碎鄉心夢不成\n故園無此聲",20,50); //新建文本域,默認
sp = new JScrollPane(text);//新建創建一個顯示指定組件ta內容的JScrolPane
add(sp,BorderLayout.CENTER);//將JScrollPane放入內容窗格
//四個菜單項注冊監聽器
newi.addActionListener(this);
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="New")
{
text.setText(""); //文本域設置為空
}
if(e.getActionCommand()=="Open")
{
text.setText(""); //如果不加這句,文件內容將在先前內容之后顯示
try {openfile();}
catch(IOException ex){ex.printStackTrace();}
}
if(e.getActionCommand()=="Save")
{
try{savefile();}//保存
catch(IOException ex){ex.printStackTrace(); }
}
}
public void savefile() throws IOException
{
FileDialog fd=new FileDialog(this,"Save",FileDialog.SAVE); //java.awt.FileDialog ,public static final int LOAD 和Save
fd.setVisible(true); //必須設為可見
FileWriter fw=new FileWriter( fd.getDirectory()+fd.getFile());//用于寫入字符流,要寫入原始字節流,使用 FileOutputStream
for(int i=0;i<text.getText().length();i++) //用于構造與fd 保存的文件相關聯的對象
{
fw.write(text.getText().charAt(i)); //寫入文件
}
fw.close();
}
public void openfile() throws IOException
{
FileDialog fd=new FileDialog(this,"Open",FileDialog.LOAD);
fd.setVisible(true);
FileReader fr=new FileReader( fd.getDirectory()+fd.getFile());
int n=0;
int num=100; //設定每行的字符數
while((n=fr.read())!=-1)
{
text.append(""+(char)n);
num--;
if(num==0)
{
text.append("\n");
num=100;
}
}
fr.close();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -