運行結果以下:
保存:java
import java.awt.BorderLayout; import java.io.*; import javax.swing.*; public class A extends JFrame{ private static final long serialVersionUID = 1L; JTextArea jta; JButton jbt,SearchJBT,SearchCharJBT, ReplaceJBT,SearchNums; JFileChooser fileChooser = new JFileChooser(); public A(){ super("文本編輯器"); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(500,700 ); this.setLayout(new BorderLayout()); this.setLocation(500,300); this.setResizable(false); _initTextArea(); _initButton(); _initLable(); } private void _initTextArea(){ JPanel jp = new JPanel(); jta= new JTextArea(30,40); jp.add(jta); this.add(jp,BorderLayout.CENTER); } private void _initButton(){ JPanel jp = new JPanel(); jbt=new JButton("保存"); jbt.addActionListener((param)->saveDataToFile(jta.getText(),"my.txt")); jp.add(jbt); SearchJBT = new JButton("查找"); SearchJBT.addActionListener((param)->{ String inputContent = JOptionPane.showInputDialog(null,"輸入要找的字符串:",""); int res = _search(inputContent); if(res>-1){JOptionPane.showMessageDialog( null,"字符串開始在"+(int)(res+1)+"的位置","字符串找到了",JOptionPane.INFORMATION_MESSAGE);}else{ JOptionPane.showMessageDialog(null,"沒找到","字符串",JOptionPane.INFORMATION_MESSAGE ); } }); jp.add(SearchJBT); SearchCharJBT = new JButton("有多少個字符"); SearchCharJBT.addActionListener((param)->{ JOptionPane.showMessageDialog(null,"一共有"+_HowManyChar()+"個字符","QAQ",JOptionPane.INFORMATION_MESSAGE); }); jp.add(SearchCharJBT); ReplaceJBT = new JButton("替換"); ReplaceJBT.addActionListener((param)->{ String str1 = JOptionPane.showInputDialog(null,"輸入要替換的字符串:",""); String str2 = JOptionPane.showInputDialog(null,"你想換成什麼:",""); if(str1!=null&&str2!=null){ _replaces(str1, str2); } }); jp.add(ReplaceJBT); SearchNums = new JButton("有多少數字"); SearchNums.addActionListener((param)->{ JOptionPane.showMessageDialog(null,"一共有"+_HowManyNums()+"個數字","QAQ",JOptionPane.INFORMATION_MESSAGE); }); jp.add(SearchNums); this.add(jp,BorderLayout.NORTH); } private void saveDataToFile(String data, String fileName) { fileChooser.setSelectedFile(new File(fileName)); fileChooser.showSaveDialog(null); String filePath = fileChooser.getSelectedFile().toString(); try { FileWriter writer = new FileWriter(filePath); writer.append(data); writer.flush(); } catch (IOException e) { e.printStackTrace(); } } private void _initLable(){ JPanel jp = new JPanel(); jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS)); for(int i=1;i<30;i++){ jp.add(new JLabel(i+"")); } this.add(jp,BorderLayout.WEST); } private int _search(String str){ return jta.getText().indexOf(str); } private int _HowManyChar(){ return jta.getText().length(); } private void _replaces(String str1,String str2){ String str = jta.getText(); str = str.replaceAll(str1,str2); jta.setText(str); } private int _HowManyNums(){ String str = jta.getText(); int res = 0; for(int i=0;i<str.length();i++){ if(str.charAt(i)>='0'&&str.charAt(i)<='9') res++; } return res; } public static void main(String[] args) { new A(); } }