溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java仿windows記事本小程序

發(fā)布時間:2020-08-27 20:09:32 來源:腳本之家 閱讀:209 作者:wuyihan1994 欄目:編程語言

本文實例為大家分享了java仿windows記事本小程序的具體代碼,供大家參考,具體內(nèi)容如下

import java.awt.CheckboxMenuItem;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.peer.ButtonPeer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
 
import javax.print.DocFlavor.STRING;
import javax.script.ScriptException;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.AncestorListener;
import javax.swing.filechooser.FileNameExtensionFilter;
 
public class Crazy_15_4 {
 private JFrame f = new JFrame("記事本");
 
 //成員變量
 static String shearPlate = null;
 static boolean isAutoWrap = true;//是否自動換行
 JTextArea ta = new JTextArea(20, 60);
 JScrollPane jsp = new JScrollPane(ta);
 private MenuBar mb = new MenuBar();
 public String fontStr = "宋體";
 public String shapeStr = "0";
 public String sizeStr = "20";
 Font font = new Font(fontStr, Integer.parseInt(shapeStr),Integer.parseInt(sizeStr) );
 
 
 //menu
 Menu file = new Menu("文件");
 Menu edit = new Menu("編輯");
 Menu format = new Menu("格式");
 
 //menuitem
 MenuItem newItem = new MenuItem("新建");
 MenuItem openItem = new MenuItem("打開");
 MenuItem saveItem = new MenuItem("保存");
 MenuItem saveAsItem = new MenuItem("另存為");
 MenuItem cutItem = new MenuItem("剪切");
 MenuItem copyItem = new MenuItem("復制");
 MenuItem pasteItem = new MenuItem("粘貼");
 CheckboxMenuItem autoWrap = new CheckboxMenuItem("自動換行",isAutoWrap);
 MenuItem FontItem = new MenuItem("字體");
 //使用“ctrl+x”快捷鍵
 MenuItem exitIitem = new MenuItem("退出", new MenuShortcut(KeyEvent.VK_X));
 
 
 
 
 
 public void init() {
 //帶滾動條的文本域
 ta.setLineWrap(isAutoWrap);
 jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
 jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
 
 
 file.add(newItem);
 file.add(openItem);
 file.add(saveItem);
 file.add(saveAsItem);
 
 edit.add(cutItem);
 edit.add(copyItem);
 edit.add(pasteItem);
 
 format.add(autoWrap);
 format.add(FontItem);
 
 mb.add(file);
 mb.add(edit);
 mb.add(format);
 
 f.setMenuBar(mb);
 f.addWindowListener(new WindowAdapter() {
 public void windowClosing(WindowEvent we) {
 if(!(ta.getText().equals(""))) {
  Object[] options = {"保存","不保存","取消"};
  int a = JOptionPane.showOptionDialog(null,"是否將更改保存到H:/Programing/無標題.txt","記事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
  if(a == JOptionPane.OK_OPTION ) {
  if(save()) {
  System.exit(0);
  }
  }else if(a == JOptionPane.NO_OPTION) {
  System.exit(0);
  }
 }else {
  System.exit(0);
 }
 }
 });
 
 newItem.addActionListener(new newListener());
 openItem.addActionListener(new openListener());
 saveItem.addActionListener(new saveListener());
 saveAsItem.addActionListener(new saveAsListener());
 cutItem.addActionListener(new cutAsListener());
 copyItem.addActionListener(new copyAsListener());
 pasteItem.addActionListener(new pasteAsListener());
 autoWrap.addItemListener(new autoWrapAsListener());
 FontItem.addActionListener(new fontListener());
 
 ta.setFont(font);
 //使文本框處在屏幕中間
 int width = Toolkit.getDefaultToolkit().getScreenSize().width;
 int height = Toolkit.getDefaultToolkit().getScreenSize().height; 
 f.add(jsp);
 f.pack();
 f.setLocation(width/2-f.getWidth()/2, height/2-f.getHeight()/2);
 f.setVisible(true);
 //避免關(guān)閉對話框直接關(guān)閉文本文件
 f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
 }
 public static void main(String[] args) {
 new Crazy_15_4().init();
 }
 
 //是否保存
 public void saveOrNot() {
 if(!(ta.getText().equals(""))) {
 Object[] options = {"保存","不保存","取消"};
 int a = JOptionPane.showOptionDialog(null,"是否將更改保存到H:/Programing/無標題.txt","記事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
 if(a == JOptionPane.OK_OPTION ) {
 save();
 }
 }
 }
 //保存文本文件
 public boolean save() {
 boolean isSaved = false;
 JFileChooser jf = new JFileChooser();
 FileNameExtensionFilter filter = new FileNameExtensionFilter("txt","txt");
 jf.setAcceptAllFileFilterUsed(false);
 jf.setFileFilter(filter);
 int value = jf.showSaveDialog(null);
 if(value == JFileChooser.APPROVE_OPTION) {
 File file = jf.getSelectedFile();
 String str = ta.getText();
 byte[] buf = str.getBytes();
 try {
 OutputStream os = new FileOutputStream(file);
 os.write(buf);
 os.flush();
 os.close();
 isSaved = true;
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 return isSaved;
 }
 //新建監(jiān)聽器
 class newListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 if(!(ta.getText().equals(""))) {
 Object[] options = {"保存","不保存","取消"};
 int a = JOptionPane.showOptionDialog(null,"是否將更改保存到H:/Programing/無標題.txt","記事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
 if(a == JOptionPane.OK_OPTION ) {
  if(save()) {
  ta.setText("");
  }
 }else if(a == JOptionPane.NO_OPTION) {
  ta.setText("");
 }
 }
 
 }
 }
 
 //打開監(jiān)聽器,從硬盤目錄打開文本文件
 class openListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 JFileChooser jf = new JFileChooser();
 FileNameExtensionFilter filter = new FileNameExtensionFilter("txt","txt");
 jf.setAcceptAllFileFilterUsed(false);
 jf.setFileFilter(filter);
 int value = jf.showOpenDialog(null);
 if(value == JFileChooser.APPROVE_OPTION) {
 File file = jf.getSelectedFile();
 try {
  String encoding = "GBK";//考慮編碼格式
  InputStreamReader isr = new InputStreamReader(new FileInputStream(file),encoding);
  BufferedReader br = new BufferedReader(isr);
  String str = null;
  while((str = br.readLine()) != null) {
  ta.append(str);
  }
 } catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 } catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 }
 }
 }
 }
 
 //保存監(jiān)聽器,以電腦時間命名
 class saveListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 String name = null;
 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
 name = df.format(System.currentTimeMillis());
 File file = new File("H:/Programing/workspace/"+name+".txt");
 String str = ta.getText();
 byte[] buf = str.getBytes();
 if(!str.equals("")) {
 try {
  OutputStream os = new FileOutputStream(file);
  os.write(buf);
  os.flush();
  os.close();
 } catch (IOException e2) {
  e2.printStackTrace();
 }
 }
 }
 }
 
 //另存為監(jiān)聽器 
 class saveAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 save();
 }
 }
 
 //剪切監(jiān)聽器 
 class cutAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 shearPlate = ta.getSelectedText();
 int startPosi = ta.getSelectionStart();
 int endPosi = ta.getSelectionEnd();
 StringBuffer sb = new StringBuffer(ta.getText());
 sb.delete(startPosi, endPosi);
 ta.setText(sb.toString());
 }
 }
 
 //復制監(jiān)聽器 
 class copyAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 shearPlate = ta.getSelectedText();
 }
 }
 
 //粘貼監(jiān)聽器 
 class pasteAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 int position = ta.getCaretPosition();
 StringBuilder sb = new StringBuilder(ta.getText());
 sb.insert(position, shearPlate);
 ta.setText(sb.toString());
 ta.setCaretPosition(position+shearPlate.length());
 }
 }
 
 //自動換行監(jiān)聽器 
 class autoWrapAsListener implements ItemListener{
 
 @Override
 public void itemStateChanged(ItemEvent e) {
 if(autoWrap.getState()) {
  isAutoWrap = true;
  ta.setLineWrap(isAutoWrap);
  jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
  jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
 }else {
  isAutoWrap = false;
  ta.setLineWrap(isAutoWrap);
  jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
 }
 }
 }
 
 //字體監(jiān)聽器 
 class fontListener implements ActionListener{
 JFrame jf = new JFrame("字體");
 JPanel jp = new JPanel();
 ButtonPanel fontButton = new ButtonPanel("字體",new String[] {"宋體","黑體","楷體","吳祎晗1.0"});
 ButtonPanel shapeButton = new ButtonPanel("字形",new String[] {"常規(guī)","粗體","斜體","粗體&斜體"});
 ButtonPanel sizeButton = new ButtonPanel("字號",new String[] {"12","16","20","24","26"});
 public void actionPerformed(ActionEvent e) {
 jp.setBorder(new TitledBorder(new EtchedBorder(),"字體選擇",TitledBorder.CENTER,TitledBorder.TOP));
 jp.add(fontButton);
 jp.add(shapeButton);
 jp.add(sizeButton);
 jf.add(jp);
 jf.pack();
 jf.setLocationRelativeTo(f);
 jf.setVisible(true);
 jf.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  fontStr = fontButton.getSelec();
  sizeStr = sizeButton.getSelec();
  font = new Font(fontStr, shapeVal(shapeButton.getSelec()), Integer.parseInt(sizeStr));
  ta.setFont(font);
  }
 });
 }
 
 public int shapeVal(String str) {
 int a = 0;
 switch (str) {
 case "常規(guī)":
  a = 0;
  break;
 case "粗體":
  a = 1;
  break;
 case "斜體":
  a = 2;
  break;
 case "粗體&斜體":
  a = 3;
  break;
 }
 return a;
 }
 }
 
}
 
//定義一個JPanel類擴展類,該類的對象包含多個縱向排列的
//JRadioButton控件,且panel擴展類可以指定一個字符串作為TitledBorder
class ButtonPanel extends JPanel{
 private ButtonGroup group;
 public ButtonPanel(String title, String[] options) {
 setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title));
 setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
 group = new ButtonGroup();
 for(int i=0; options!=null&&i<options.length; i++) {
 JRadioButton b = new JRadioButton(options[i]);
 b.setActionCommand(options[i]);
 this.add(b);
 group.add(b);
 if(title.equals("字號")) {
 b.setSelected(i == 2);
 }else {
 b.setSelected(i == 0);
 }
 }
 }
 public String getSelec() {
 return group.getSelection().getActionCommand();
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI