使用Swing组件编写一个支持中文文本编辑程序ChineseTextEdit.java


 


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;


public class ChineseTextEdit extends JFrame implements ActionListener{
    JTextArea texA;
    JScrollPane scroll;
    JButton but1;
    JButton but2;
    JButton but3;
    
    
    ChineseTextEdit(String name){
        super(name);
        init();
    }
    
    void init(){
        
        JPanel pan = new JPanel();
        pan.setLayout(new BorderLayout());
        pan.setBackground(Color.YELLOW);
        
        texA = new JTextArea("",20,30);
        texA.setLineWrap(true);//设置自动换行
        scroll = new JScrollPane(texA);//设置滚动条
        pan.add(scroll,BorderLayout.CENTER);
        
        JPanel pan1= new JPanel();
        pan1.setLayout(new GridLayout(1,3));//1行三列
        
        but1 = new JButton("保存");
        pan1.add(but1);
        but1.addActionListener(this);
        
        but2 = new JButton("取消");
        pan1.add(but2);
        but2.addActionListener(this);
        
        but3 = new JButton("退出");
        pan1.add(but3);
        but3.addActionListener(this);
        
        pan.add(pan1,BorderLayout.SOUTH);
        this.add(pan);
     File f = new File("F:\text.txt");
        
        if(f.exists())
        {
            try{
                BufferedReader br = new BufferedReader(new FileReader("F:\text.txt"));
                String strLine;
                
                while(br.ready()){
                    strLine = br.readLine();
                    texA.append(strLine);
                }
                
                br.close();
            }
            catch(IOException ie){
                ie.printStackTrace();
            }
        }
        else{
            try{
                f.createNewFile();
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
 } 
public void actionPerformed(ActionEvent e){
if(e.getSource() == but1)
{

  try
{
      BufferedWriter bw
= new BufferedWriter(new FileWriter("F:\text.txt"));//缓存写入
      String strLine
= texA.getText();
      bw.write(strLine); bw.flush(); bw.close();
    }
  catch(IOException ie)
  {
  ie.printStackTrace();
  }
}
else if(e.getSource() == but2){
  texA.setText(
"");
}
else if(e.getSource() == but3){
   dispose();//退出 }
}
/** * @param args */
public static void main(String[] args)
{
// TODO Auto-generated method stub
  ChineseTextEdit f = new ChineseTextEdit("test");
  f.pack();
  f.setVisible(
true);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
原文地址:https://www.cnblogs.com/xiaochi/p/4947185.html