求JAVA编写的文本编辑器。
import java.awt.*;
成都创新互联是一家专注于成都做网站、网站制作与策划设计,定日网站建设哪家好?成都创新互联做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:定日等地区。定日做网站价格咨询:18982081108
import java.awt.event.*;
import java.io.*;
public class Notepad /*implements ActionListener , MouseListener , MouseMotionListener , WindowListener , ItemListener , KeyListener, TextListener */
{
//成员变量
private Frame mainFrame;//主框架
private MenuBar mb ; //菜单条
private Menu mFile , mEdit , mFormat , mHelp ; //菜单:文件,编辑,格式,帮助
private MenuItem miNew , miOpen , miSave , miSaveAs , miExit ;//文件菜单项:新建,打开,保存,另存为,退出
private MenuItem miCut , miCopy , miPaste , miDelete ;//编辑菜单项:剪切,复制,粘贴,删除
private MenuItem miFont , miLowtoCapital, miCapitaltoLow ,miEncrypt , miDisencrypt;//格式菜单项:字体
private MenuItem miAboutNotepad;//帮助菜单项:关于记事本
private TextArea ta;//文本区
private String tempString;//临时字符串,用于存储需要复制粘贴的字符串
private boolean textValueChanged = false;
private int id_font ;//字体
String fileName = "";//上次保存后的文件名和地址
//构造函数
public Notepad(){
//框架
mainFrame = new Frame ("Notepad v0.99 by Launching");
mb = new MenuBar ();
ta = new TextArea (30 ,60);
ta.setFont( new Font ( "Times New Rome" , Font.PLAIN , 15));
ta.setBackground(new Color(0 , 250 , 200));
//菜单条
mFile = new Menu ( "File");
mEdit = new Menu ( "Edit");
mFormat = new Menu ("Format");
mHelp = new Menu ("Help");
//"文件"
miNew = new MenuItem ("New");
miOpen = new MenuItem ("Open");
miSave = new MenuItem ("Save");
miSaveAs = new MenuItem ("Save as");
miExit = new MenuItem ("Exit");
//"编辑"
miCut = new MenuItem ("Cut");
miCopy = new MenuItem ("Copy");
miPaste = new MenuItem ("Paste");
miDelete = new MenuItem ("Delete");
//"格式"
miFont = new MenuItem ("Font");
miLowtoCapital = new MenuItem("Low to Capital");
miCapitaltoLow = new MenuItem("Capital to Low");
miEncrypt = new MenuItem("Encrypt");
miDisencrypt = new MenuItem("Disencrypt");
//"帮助"
miAboutNotepad = new MenuItem ("About Notepad");
//添加文件菜单项
mFile.add(miNew);
mFile.add(miOpen);
mFile.add(miSave);
mFile.add(miSaveAs);
mFile.add(miExit);
//添加编辑菜单项
mEdit.add(miCut);
mEdit.add(miCopy);
mEdit.add(miPaste);
mEdit.add(miDelete);
//添加格式菜单项
mFormat.add(miFont);
mFormat.add(miLowtoCapital);
mFormat.add(miCapitaltoLow);
mFormat.add(miEncrypt);
mFormat.add(miDisencrypt);
//添加帮助菜单项
mHelp.add(miAboutNotepad);
//菜单条添加菜单
mb.add(mFile);
mb.add(mEdit);
mb.add(mFormat);
mb.add(mHelp);
//框架添加菜单条
mainFrame.setMenuBar( mb );
//初始字符串赋为空
tempString = "";
//添加文本区
mainFrame.add(ta, BorderLayout.CENTER);
mainFrame.setSize(800 , 500);
mainFrame.setLocation( 100 ,100);// 起始位置
mainFrame.setResizable(true);//不可更改大小
mainFrame.setVisible(true);
//mainFrame.pack();
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////增加监视器////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//主框架
mainFrame.addWindowListener(new WindowAdapter (){ //关闭窗口
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//文本区
ta.addKeyListener( new KeyAdapter(){
public void KeyTyped(KeyEvent e){
textValueChanged = true ; //键盘按键按下即导致文本修改
}
});
////////////////"文件"菜单://////////////////////
//新建
miNew.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
ta.replaceRange("", 0 , ta.getText().length()) ;//清空文本区的内容
fileName = "";//文件名清空
}
});
//打开
miOpen.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
FileDialog d=new FileDialog(mainFrame , "open file" , FileDialog.LOAD );//打开文件对话框
d.addWindowListener( new WindowAdapter(){ //关闭文件对话框窗口
public void windowClosing(WindowEvent ee){
System.exit(0);
}
});
d.setVisible(true);
File f = new File( d.getDirectory()+d.getFile() ); //建立新文件
fileName = d.getDirectory()+d.getFile();//得到文件名
char ch[] = new char [(int)f.length()];///用此文件的长度建立一个字符数组
try//异常处理
{
//读出数据,并存入字符数组ch中
BufferedReader bw = new BufferedReader( new FileReader(f) );
bw.read(ch);
bw.close();
}
catch( FileNotFoundException fe ){
System.out.println("file not found");
System.exit(0);
}
catch( IOException ie){
System.out.println("IO error");
System.exit(0);
}
String s =new String (ch);
ta.setText(s);//设置文本区为所打开文件的内容
}
});
//保存
miSave.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
if( fileName.equals("") ){ //如果文件没有被保存过,即文件名为空
FileDialog d=new FileDialog(mainFrame , "save file" , FileDialog.SAVE );//保存文件对话框
d.addWindowListener( new WindowAdapter(){ //关闭文件对话框窗口
public void windowClosing(WindowEvent ee){
System.exit(0);
}
});
d.setVisible(true);
String s = ta.getText();//得到所输入的文本内容
try//异常处理
{
File f = new File( d.getDirectory()+d.getFile());//新建文件
fileName = d.getDirectory()+d.getFile();//得到文件名
BufferedWriter bw = new BufferedWriter( new FileWriter (f));//输入到文件中
bw.write(s , 0 , s.length());
bw.close();
}
catch(FileNotFoundException fe_){
System.out.println("file not found");
System.exit(0);
}
catch( IOException ie_)
{
System.out.println(" IO error");
System.exit(0);
}
}
else //如果文件已经保存过
{
String s = ta.getText();//得到所输入的文本内容
try//异常处理
{
File f = new File( fileName );//新建文件
BufferedWriter bw = new BufferedWriter( new FileWriter (f));//输入到文件中
bw.write(s , 0 , s.length());
bw.close();
}
catch(FileNotFoundException fe_){
System.out.println("file not found");
System.exit(0);
}
catch( IOException ie_)
{
System.out.println(" IO error");
System.exit(0);
}
}
}
});
//另存为
miSaveAs.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e) {
FileDialog d=new FileDialog(mainFrame , "save file" , FileDialog.SAVE );//保存文件对话框
d.addWindowListener( new WindowAdapter(){ //关闭文件对话框窗口
public void windowClosing(WindowEvent ee){
System.exit(0);
}
});
d.setVisible(true);
String s = ta.getText();//得到所输入的文本内容
try//异常处理
{
File f = new File( d.getDirectory()+d.getFile());//新建文件
BufferedWriter bw = new BufferedWriter( new FileWriter (f));//输入到文件中
bw.write(s , 0 , s.length());
bw.close();
}
catch(FileNotFoundException fe_){
System.out.println("file not found");
System.exit(0);
}
catch( IOException ie_)
{
System.out.println(" IO error");
System.exit(0);
}
}
});
//退出
miExit.addActionListener( new ActionListener(){ ///退出程序
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
////////////////"编辑"菜单:////////////////////
//剪切
miCut.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
tempString = ta.getSelectedText(); ///得到要复制的内容,暂存在tempString中
StringBuffer tmp = new StringBuffer ( ta.getText());//临时存储文本
int start = ta.getSelectionStart(); //得到要删除的字符串的起始位置
int len = ta.getSelectedText().length(); //得到要删除的字符串的长度
tmp.delete( start , start+len); ///删除所选中的字符串
ta.setText(tmp.toString());//用新文本设置原文本
}
});
//复制
miCopy.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
tempString = ta.getSelectedText(); ///得到要复制的内容,暂存在tempString中
}
});
//粘贴
miPaste.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
StringBuffer tmp = new StringBuffer ( ta.getText());//临时存储文本
int start = ta.getSelectionStart(); //得到要粘贴的位置
tmp.insert(start , tempString);//查入要粘贴的内容
ta.setText(tmp.toString());//用新文本设置原文本
}
});
//删除
miDelete.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
StringBuffer tmp = new StringBuffer ( ta.getText());//临时存储文本
int start = ta.getSelectionStart(); //得到要删除的字符串的起始位置
int len = ta.getSelectedText().length(); //得到要删除的字符串的长度
tmp.delete( start , start+len); ///删除所选中的字符串
ta.setText(tmp.toString());//用新文本设置原文本
}
});
////////////////"格式"菜单:////////////////////
//字体
miFont.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
final Dialog d = new Dialog ( mainFrame , "Font");//新建对话框
d.setLocation( 250 ,250);// 起始位置
d.setLayout( new BorderLayout());//表格布局
//////////////////////////上部分面板
Label l_font = new Label ("font");//font标签
Panel p_1 = new Panel();
p_1.add(l_font);
p_1.setVisible(true);
//////////////////////////中部分面板
List font_list = new List (6 , false);//字体列表
//添加字体项目
font_list.add("Plain");///普通字体
font_list.add("Bold"); ///粗体
font_list.add("Italic");//斜体
font_list.addItemListener( new MyItemListener_font() ); //字体增加监视器
Panel p_2 = new Panel();
p_2.add(font_list);
p_2.setVisible(true);
//////////////////////////下部分面板
Button ok = new Button ("OK");
ok.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
d.dispose();
}
});
ok.setSize( new Dimension (20 , 5) );
Panel p_3 = new Panel();//下部分面板
p_3.add(ok);
p_3.setVisible(true);
//添加三个面板
d.add(p_1 , BorderLayout.NORTH);
d.add(p_2 , BorderLayout.CENTER);
d.add(p_3 , BorderLayout.SOUTH);
d.pack();
d.addWindowListener( new WindowAdapter(){ //关闭对话框窗口
public void windowClosing(WindowEvent ee){
d.dispose();
}
});
d.setVisible(true);
}
});
//小写字母转大写
miLowtoCapital.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = ta.getText();//得到所输入的文本内容
StringBuffer temp = new StringBuffer("");
for(int i = 0 ; is.length() ; i++){
if((int)s.charAt(i)=97 (int)s.charAt(i)=122 ){
temp.append((char)((int)s.charAt(i)-32));
}
else
temp.append(s.charAt(i));
}
s = new String(temp);
ta.setText(s);
}
});
//大写字母转小写
miCapitaltoLow.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = ta.getText();//得到所输入的文本内容
StringBuffer temp = new StringBuffer("");
for(int i = 0 ; is.length() ; i++){
if((int)s.charAt(i)=65 (int)s.charAt(i)=90 ){
temp.append((char)((int)s.charAt(i)+32));
}
else
temp.append(s.charAt(i));
}
s = new String(temp);
ta.setText(s);
}
});
//加密
miEncrypt.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = ta.getText();//得到所输入的文本内容
StringBuffer temp = new StringBuffer("");
for(int i = 0 ; is.length() ; i++){
if(s.charAt(i)=40 s.charAt(i)=125){
if(i%2==0){
temp.append((char)(s.charAt(i) + 1 ));
}
else
temp.append((char)(s.charAt(i) - 1 ));
}
else
temp.append(s.charAt(i));
}
s = new String(temp);
ta.setText(s);
}
});
//解密
miDisencrypt.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = ta.getText();//得到所输入的文本内容
StringBuffer temp = new StringBuffer("");
for(int i = 0 ; is.length() ; i++){
if(s.charAt(i)=40 s.charAt(i)=125){
if(i%2==0){
temp.append((char)(s.charAt(i) - 1 ));
}
else
temp.append((char)(s.charAt(i) + 1 ));
}
else
temp.append(s.charAt(i));
}
s = new String(temp);
ta.setText(s);
}
});
////////////////"帮助"菜单:////////////////////
//关于记事本
miAboutNotepad.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
final Dialog d = new Dialog ( mainFrame , "AboutNotepad");//新建对话框
TextArea t = new TextArea("\nwelcome to use Notepad " + "\n\n" + "Copyright@Launching " + "\n\n" + "free software" + "\n\n" + "v0.99");//添加标签
t.setSize( new Dimension ( 5 , 5));
t.setEditable(false);
d.setResizable(false);//不可调整大小
d.add(t);
d.pack();
d.addWindowListener( new WindowAdapter(){ //关闭对话框窗口
public void windowClosing(WindowEvent ee){
d.dispose();
}
});
d.setLocation( 100 ,250);// 起始位置
d.setVisible(true);
}
});
}
class MyItemListener_font implements ItemListener { //字体监听器
public void itemStateChanged(ItemEvent e) {
id_font = ((java.awt.List)e.getSource()).getSelectedIndex();
switch( id_font){
case 0:{
ta.setFont(new Font("Times New Roman", Font.PLAIN ,ta.getFont().getSize()) );//普通文字
break;
}
case 1:{
ta.setFont(new Font("Times New Roman" , Font.BOLD ,ta.getFont().getSize()) );//粗体文字
break;
}
case 2:{
ta.setFont(new Font("Times New Roman" , Font.ITALIC ,ta.getFont().getSize()) );//斜体文字
break;
}
}
}
}
/////////////////////////////////////////主函数///////////////////////////////////////////////////
public static void main(String arg[]){
Notepad test = new Notepad(); ///创建记事本
}
//////////////////////////////////////////////////////////////////////////////////////////////////
}
JAVA编写好的文本编辑器代码怎么运行啊
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class MenuTester extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private static final String FILE = "d:/1.txt";
JTextArea textArea;
JScrollPane scrollPane;
public MenuTester ()
{
setTitle ("MenuTester");
setLayout (new BorderLayout ());
JMenuBar menuBar = new JMenuBar ();
JMenu[] menu = new JMenu[] { new JMenu ("文件"), new JMenu ("编辑") };
JMenuItem[] menuItem1 = new JMenuItem[] { new JMenuItem ("新建"), new JMenuItem ("打开"), new JMenuItem ("保存"), new JMenuItem ("关闭") };
JMenuItem[] menuItem2 = new JMenuItem[] { new JMenuItem ("复制"), new JMenuItem ("粘贴"), new JMenuItem ("剪切") };
for ( int i = 0; i menu.length; i++ )
{
menuBar.add (menu[i]);
}
for ( int i = 0; i menuItem1.length; i++ )
{
menu[0].add (menuItem1[i]);
}
for ( int i = 0; i menuItem2.length; i++ )
{
menu[1].add (menuItem2[i]);
}
menuItem1[0].addActionListener (this);
menuItem1[1].addActionListener (this);
menuItem1[2].addActionListener (this);
menuItem1[3].addActionListener (this);
setJMenuBar (menuBar);
textArea = new JTextArea ();
scrollPane = new JScrollPane (textArea);
scrollPane.setVisible (false);
add (scrollPane, BorderLayout.CENTER);
setResizable (false);
setSize (800, 600);
setLocationRelativeTo (null);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setVisible (true);
}
public static void main ( String[] args )
{
SwingUtilities.invokeLater (new Runnable ()
{
@Override
public void run ()
{
new MenuTester ();
}
});
}
@Override
public void actionPerformed ( ActionEvent e )
{
String command = e.getActionCommand ();
if ("新建".equals (command))
{
scrollPane.setVisible (true);
validate ();
}
else if ("关闭".equals (command))
{
scrollPane.setVisible (false);
textArea.setText ("");
validate ();
}
else if ("打开".equals (command))
{
scrollPane.setVisible (true);
validate ();
try
{
FileReader fr = new FileReader (FILE);
char[] cs = new char[1];
while (-1 != ( fr.read (cs) ))
{
textArea.append (new String (cs));
}
fr.close ();
}
catch (Exception e1)
{
e1.printStackTrace ();
}
}
else if ("保存".equals (command))
{
try
{
FileWriter fw = new FileWriter (FILE);
fw.write (textArea.getText ());
fw.flush ();
fw.close ();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
java 文本编辑器
这么说吧,其实java版的记事本就是一个JTextArea再加上一些菜单项,再加上查找对话框、替换对话框等。
除了在“打开”“保存”“新建”等操作时要判断一下是否弹出“编辑文件已改变,是否保存”的对话框,别的没多大难度吧。。。。
参考网址里是一个基本实现所有windows自带记事本的程序,里面分ReplaceDialog.java、Notepad.java、FontDialog.java、FindDialog.java四个文件,顾名思义,共要建四个类。
你要自己实现的话,可以一步一步地来,慢慢加入复杂的功能。
要的话留下邮箱。
能编译运行java的简单文本编辑器
import java.awt.BorderLayout;
public class WordProcessSystem extends JFrame{
private JFileChooser chooser;
private JTextArea textArea;
private File file;
private String string = "";
private Font font;
public WordProcessSystem(){
super();
setTitle("文字处理系统");
setBounds(100, 100,600, 500);
getContentPane().setLayout(new BorderLayout());
getContentPane().setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("文件");
JMenuItem menuItem = new JMenuItem("新建");
menuItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str1 = JOptionPane.showInputDialog("请输入新建文件名:");
try {
file = new File("E:\\", str1 + ".txt");
if(file.exists()){
JOptionPane.showMessageDialog(null, "文件名已存在!");
}
else{
file.createNewFile();
}
} catch (Exception e1) {
// TODO: handle exception
}
}
});
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
JMenuItem menuItem1 = new JMenuItem("打开");
menuItem1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int result = chooser.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
String str = chooser.getSelectedFile().toString();
try {
file = new File(str);
readFromFile(file);
textArea.setText(string);
} catch (Exception e1) {
// TODO: handle exception
}
}
}
});
JMenuItem menuItem2 = new JMenuItem("退出");
menuItem2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
JMenuItem menuItem3 = new JMenuItem("保存");
menuItem3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String string = textArea.getText();
try {
writeToFile(file, string);
} catch (Exception e1) {
// TODO: handle exception
}
}
});
menuItem3.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == KeyEvent.VK_C){
// if(e.getKeyChar() == KeyEvent.VK_S){
String string = textArea.getText();
try {
writeToFile(file, string);
} catch (Exception e1) {
// TODO: handle exception
}
// }
}
}
});
JMenuItem menuItem4 = new JMenuItem("另存为");
menuItem4.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s1 = JOptionPane.showInputDialog("请输入保存文件路径和文件名:");
file = new File(s1);
System.out.println(file.getPath());
try {
writeToFile(file, string);
System.out.println("aaaa");
} catch (Exception e1) {
// TODO: handle exception
}
}
});
menu.add(menuItem);
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
menu.add(menuItem4);
JMenu menu2 = new JMenu("格式");
final JMenu menu3 = new JMenu("字体");
String []fontString = {"宋体","楷体","隶书"};
final JMenuItem []menu3_1 = new JMenuItem[fontString.length];
for(int i = 0;i fontString.length;i++){
String changeString = "";
menu3_1[i] = new JMenuItem(fontString[i]);
menu3_1[i].setActionCommand(changeString + i);
menu3_1[i].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method
switch (e.getActionCommand().charAt(0)) {
case '0':
font = new Font("宋体",Font.PLAIN,20);
textArea.setFont(font);
break;
case '1':
font = new Font("楷体",Font.PLAIN,18);
textArea.setFont(font);
break;
case '2':
font = new Font("隶书",Font.BOLD,18);
textArea.setFont(font);
break;
default:
break;
}
}});
menu3.add(menu3_1[i]);
}
JMenu menu4 = new JMenu("字号");
String []fontBig = {"10","15","20","25","30","35","40"};
final JMenuItem []menu4_1 = new JMenuItem[fontBig.length];
for(int i = 0;i fontBig.length;i++){
String changeString = "";
menu4_1[i] = new JMenuItem(fontBig[i]);
menu4_1[i].setActionCommand(changeString + i);
menu4_1[i].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method
switch (e.getActionCommand().charAt(0)) {
case '0':
font = new Font(menu3.getText(),Font.PLAIN,10);
textArea.setFont(font);
break;
case '1':
font = new Font(menu3.getText(),Font.PLAIN,15);
textArea.setFont(font);
break;
case '2':
font = new Font(menu3.getText(),Font.PLAIN,20);
textArea.setFont(font);
break;
case '3':
font = new Font(menu3.getText(),Font.PLAIN,25);
textArea.setFont(font);
break;
case '4':
font = new Font(menu3.getText(),Font.PLAIN,30);
textArea.setFont(font);
break;
case '5':
font = new Font(menu3.getText(),Font.PLAIN,35);
textArea.setFont(font);
break;
case '6':
font = new Font(menu3.getText(),Font.PLAIN,40);
textArea.setFont(font);
break;
default:
break;
}
}});
menu4.add(menu4_1[i]);
}
menu2.add(menu3);
menu2.add(menu4);
menuBar.add(menu);
menuBar.add(menu2);
setJMenuBar(menuBar);
textArea = new JTextArea();
textArea.setVisible(true);
// textArea.setFont(new Font("宋体",Font.BOLD,20));
add(textArea);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setSize(600, 410);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
add(scrollPane);
}
public void readFromFile(File f) throws IOException{
FileReader fReader = new FileReader(file);
BufferedReader bReader = new BufferedReader(fReader);
char []data = new char[10000];
int length = 0;
while((length = fReader.read(data)) 0){
string += new String(data,0,length);
}
// string = new String("");
// while(true){
// String s1 = bReader.readLine();
// if(s1 == null){
// break;
// }
// string += (s1 + "\n");
bReader.close();
fReader.close();
}
public void writeToFile(File file,String string) throws IOException{
if(!file.exists()){
file.createNewFile();
}
FileWriter fWriter = new FileWriter(file);
fWriter.write(string);
fWriter.close();
}
public static void main(String[] args) {
WordProcessSystem wordProcessSystem = new WordProcessSystem();
wordProcessSystem.setVisible(true);
}
}
java编译文本编辑器
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EditorJFrame extends JFrame implements ActionListener, ItemListener, MouseListener
{
private JTextField text_size; //字号文本行
private JCheckBox checkbox_bold, checkbox_italic; //粗体、斜体复选框
private JButton button_cut, button_copy, button_paste; //剪切、复制、粘贴按钮
private JTextArea textarea; //文本区
private JPopupMenu popupmenu; //快捷菜单
private JDialog dialog; //出错提示对话框
private JLabel label_dialog; //对话框中的标签
public EditorJFrame()
{
super("文本编辑器"); //默认BorderLayout布局
this.setSize(500,300);
this.setLocation(300,240);
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //单击窗口关闭按钮时,结束程序运行
textarea = new JTextArea("TextArea");
textarea.addMouseListener(this); //为文本区注册鼠标事件监听器
this.add(textarea); //文本区添加到框架的中部
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //面板为流布局,左对齐
this.add(panel,"North"); //面板添加到框架的北部
text_size = new JTextField("12",10);
panel.add(text_size);
text_size.addActionListener(this); //注册文本行的单击事件监听器
checkbox_bold = new JCheckBox("粗体"); //复选框
panel.add(checkbox_bold);
checkbox_bold.addItemListener(this); //注册复选框的选择事件监听器
checkbox_italic = new JCheckBox("斜体");
panel.add(checkbox_italic);
checkbox_italic.addItemListener(this);
this.addmyMenu(); //调用自定义方法,添加菜单
this.setVisible(true);
}
private void addmyMenu() //添加主菜单、快捷菜单、对话框
{
JMenuBar menubar = new JMenuBar(); //菜单栏
this.setJMenuBar(menubar); //框架上添加菜单栏
JMenu menu_file = new JMenu("文件"); //菜单
menubar.add(menu_file); //菜单栏中加入菜单
menu_file.add(new JMenuItem("打开")); //生成菜单项并加入到菜单
menu_file.add(new JMenuItem("保存"));
menu_file.addSeparator(); //加分隔线
JMenuItem menuitem_exit = new JMenuItem("退出");
menu_file.add(menuitem_exit);
menuitem_exit.addActionListener(this); //为菜单项注册单击事件监听器
JMenu menu_edit = new JMenu("编辑");
menubar.add(menu_edit);
JMenu menu_style = new JMenu("字形");
menu_style.add(new JCheckBoxMenuItem("粗体")); //复选菜单项
menu_style.add(new JCheckBoxMenuItem("斜体"));
menu_edit.add(menu_style); //菜单加入到菜单中成为二级菜单
JMenu menu_color = new JMenu("颜色");
menu_edit.add(menu_color);
ButtonGroup buttongroup = new ButtonGroup(); //按钮组
JRadioButtonMenuItem rbmi_red = new JRadioButtonMenuItem("红",true); //单选菜单项
buttongroup.add(rbmi_red); //单选菜单项添加到按钮组
menu_color.add(rbmi_red); //单选菜单项添加到菜单
JRadioButtonMenuItem rbmi_green = new JRadioButtonMenuItem("绿",true);
buttongroup.add(rbmi_green);
menu_color.add(rbmi_green);
JRadioButtonMenuItem rbmi_blue = new JRadioButtonMenuItem("蓝",true);
buttongroup.add(rbmi_blue);
menu_color.add(rbmi_blue);
menubar.add(new JMenu("帮助"));
popupmenu = new JPopupMenu(); //弹出式菜单对象
JMenuItem menuitem_cut = new JMenuItem("剪切");
menuitem_cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));//设置快捷键Ctrl+X
popupmenu.add(menuitem_cut); //加入剪切菜单项
menuitem_cut.addActionListener(this);
JMenuItem menuitem_copy = new JMenuItem("复制");
menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));//设置快捷键Ctrl+C
popupmenu.add(menuitem_copy);
menuitem_copy.addActionListener(this);
JMenuItem menuitem_paste = new JMenuItem("粘贴");
menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));//设置快捷键Ctrl+V
popupmenu.add(menuitem_paste);
menuitem_paste.addActionListener(this);
textarea.add(popupmenu); //文本区添加快捷菜单
dialog = new JDialog(this,"提示");
dialog.setSize(240,80);
label_dialog = new JLabel("",JLabel.CENTER);
dialog.add(label_dialog);
dialog.setDefaultCloseOperation(HIDE_ON_CLOSE); //单击对话框的关闭按钮时,隐藏对话框而不结束程序运行
}
public void actionPerformed(ActionEvent e) //单击事件处理程序
{
if(e.getActionCommand()=="退出") //不能用switch(int)语句
System.exit(0); //单击菜单项时结束程序
if(e.getActionCommand()=="剪切")
textarea.cut(); //将选中文本剪切送系统剪贴板
if(e.getActionCommand()=="复制")
textarea.copy();
if(e.getActionCommand()=="粘贴")
textarea.paste();
if(e.getSource()==text_size) //单击文本行时,改变字号
{
int size=0;
try
{
size = Integer.parseInt(text_size.getText());
if (size=0 || size72)
throw new Exception("SizeException"); //抛出异常对象
java.awt.Font font = textarea.getFont();
textarea.setFont(new Font(font.getName(),font.getStyle(),size));
}
catch(NumberFormatException nfe)
{
label_dialog.setText("\""+text_size.getText()+"\" 不能转换成整数,请重新输入!");
dialog.setLocation(this.getX()+100,this.getY()+100);
dialog.setVisible(true);
}
catch(Exception ex)
{
if (ex.getMessage()=="SizeException") //捕获自己抛出的异常对象
{
label_dialog.setText(size+" 字号不合适,请重新输入!");
dialog.setLocation(this.getX()+100,this.getY()+100);
dialog.setVisible(true);
}
}
finally{}
}
}
public void itemStateChanged(ItemEvent e) //复选框选择事件处理程序
{ //实现ItemListener接口中的方法
Font font = textarea.getFont();
int style = font.getStyle();
if (e.getSource()==checkbox_bold)
style = style ^ 1; //整数的位运算,异或^
if (e.getSource()==checkbox_italic)
style = style ^ 2;
textarea.setFont(new Font(font.getName(),style,font.getSize()));
}
public void mouseClicked(MouseEvent mec) //单击鼠标时触发
{ //实现MouseListener接口中的方法
if (mec.getModifiers()==mec.BUTTON3_MASK) //单击的是鼠标右键
popupmenu.show(textarea,mec.getX(),mec.getY());//在鼠标单击处显示快捷菜单
}
public void mousePressed(MouseEvent mep) { }
public void mouseReleased(MouseEvent mer) { }
public void mouseEntered(MouseEvent mee) { }
public void mouseExited(MouseEvent mex) { }
public void mouseDragged(MouseEvent med) { }
public static void main(String arg[])
{
new EditorJFrame();
}
}
如何用java编写一个简单的文本编辑器?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class f1 extends Frame implements ActionListener
{
private MenuBar menubar=new MenuBar();
private Menu filemenu=new Menu("文件");
private Menu editmenu=new Menu("编辑");
private Menu formmenu=new Menu("格式");
private MenuItem[] itemf=new MenuItem[4];
private MenuItem[] iteme=new MenuItem[6];
private MenuItem[] items=new MenuItem[2];
private TextArea tf=new TextArea();
public int a=0,b=0,c=0,style=Font.PLAIN,size=15;
public String s1="red:"+a+" "+"green:"+b+" "+"blue"+c,
s2="宋体";
public String[] sz1={"10","16","24","30","32","36"},
sz2={"宋体","黑体","幼圆","隶书","行楷","Arial","Georgia"},
sz3={"粗体","倾斜","常规","粗斜"};
JDialog dialog=new JDialog(this,"字体",true);
Container cp=dialog.getContentPane();
JLabel[] lb=new JLabel[8];
JLabel lb1=new JLabel(s1,JLabel.LEFT);
JButton b1=new JButton("确定"),
b2=new JButton("取消");
JComboBox jc1=new JComboBox(),
jc2=new JComboBox(),
jc3=new JComboBox();
JScrollBar jb1=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);
JScrollBar jb2=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);
JScrollBar jb3=new JScrollBar(JScrollBar.HORIZONTAL,10,5,0,260);
网站标题:java代码文本编辑器,基于java的文本编辑器设计与实现
标题网址:http://lswzjz.com/article/dseepho.html