📄 simpleedit.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
public class SimpleEdit extends JFrame
{
JTextArea textArea=new JTextArea();
JScrollPane textAreaSC=new JScrollPane(textArea);
JFileChooser fileChooser=new JFileChooser();
public SimpleEdit ()
{
super("文本编辑器");
Action[] actions= //建立事件
{
new fileOpen(),
new fileSave(),
new exit()
};
setJMenuBar(createJMenuBar(actions));
Container con = getContentPane();
con.add(textAreaSC,BorderLayout.CENTER);
setSize(700,550);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JMenuBar createJMenuBar(Action[] actions)
{ //实现creatJMenuBar()功能
JMenuBar JMenuBar0=new JMenuBar();
JMenu JMenufile= new JMenu("文件");
JMenufile.add(new JMenuItem(actions[0]));
JMenufile.add(new JMenuItem(actions[1]));
JMenufile.addSeparator();
JMenufile.add(new JMenuItem(actions[2]));
JMenuBar0.add(JMenufile);
return JMenuBar0;
}
class fileOpen extends AbstractAction
{ //实现菜单项打开功能
public fileOpen()
{
super("打开");
}
public void actionPerformed(ActionEvent e)
{
int i=fileChooser.showOpenDialog(SimpleEdit.this);
if( i==fileChooser.APPROVE_OPTION )
{ //读取文件标识符为打开对话框选择的文件
File file=fileChooser.getSelectedFile();
if(!file.exists()) //打开文件不存在 警告
JOptionPane.showMessageDialog(null, "你要打开的文件不存在,请重新输入!");
else
{
try
{
//缓存读取字符流
BufferedReader br = new BufferedReader(new FileReader(file));
String str=null;
try
{
while((str=br.readLine())!=null)
textArea.append(str+'\n');
}catch(Exception ex)
{
ex.printStackTrace();
}
}catch(Exception ex1)
{
ex1.printStackTrace();
}
}
}
}
}
class fileSave extends AbstractAction
{ //实现菜单项保存功能
public fileSave()
{
super("保存");
}
public void actionPerformed(ActionEvent e)
{ //读取文件标识符为保存对话框选择的文件
int i=fileChooser.showSaveDialog(SimpleEdit.this);
if( i==fileChooser.APPROVE_OPTION )
{
File file=fileChooser.getSelectedFile();
try
{
FileOutputStream out=new FileOutputStream(file);
out.write(textArea.getText().getBytes());
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
class exit extends AbstractAction
{ //实现菜单项退出功能
public exit()
{
super("退出");
}
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args )
{
new SimpleEdit();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -