本文实例为大家分享了java仿windows记事本小程序的具体代码,供大家参考,具体内容如下
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); //避免关闭对话框直接关闭文本文件 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; } //新建监听器 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(""); } } } } //打开监听器,从硬盘目录打开文本文件 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(); } } } } //保存监听器,以电脑时间命名 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(); } } } } //另存为监听器 class saveAsListener implements ActionListener{ public void actionPerformed(ActionEvent e) { save(); } } //剪切监听器 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()); } } //复制监听器 class copyAsListener implements ActionListener{ public void actionPerformed(ActionEvent e) { shearPlate = ta.getSelectedText(); } } //粘贴监听器 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()); } } //自动换行监听器 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); } } } //字体监听器 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[] {"常规","粗体","斜体","粗体&斜体"}); 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 "常规": 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(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。