亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

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

java仿windows記事本功能完整版

發布時間:2020-09-11 17:35:36 來源:腳本之家 閱讀:173 作者:孟凡勇 欄目:編程語言

最近學了Java編程,就編了仿windows系統下的記事本練練手,這個記事本實現了windows系統下的大部分功能,只有很少的部分沒有實現,比如撤銷命令的不完美,這是本人的能力有限,還有那些JMenuItem的是否可用問題,這只是本人比較偷懶,無心再去實現,希望能夠與廣大的Java愛好者分享我的代碼,共同學習進步,我肯定有不足之處,比如有些代碼的重復,代碼的布置,以及變量的取名問題,希望廣大的Java大牛多提寶貴意見,話不多少,直接上代碼!

package org.mfy.notepad;
 
import java.awt.*;
 
import javax.swing.* ;
 
import java.awt.event.* ;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import javax.swing.undo.*;
public class MyNotepad extends JFrame{
 
 //文件的標題
 private String title = "無標題" ;
 //菜單欄
 private JPanel mp = new JPanel() ;
 private JMenuBar mb = new JMenuBar() ;
 private JMenu
 file = new JMenu("文件(F)"),
 edit = new JMenu("編輯(E)"),
 format = new JMenu("格式(V)"),
 view = new JMenu("查看(O)"),
 help = new JMenu("幫助(H)");
 //文件
 private JMenuItem 
 newFile = new JMenuItem("新建(N)") ,
 open = new JMenuItem("打開(O)") ,
 save = new JMenuItem("保存(S)") ,
 exit = new JMenuItem("退出(X)") ;
 //編輯
 private JMenuItem 
 undo = new JMenuItem("撤銷(U)") ,
 cut = new JMenuItem("剪切(T)") ,
 copy = new JMenuItem("復制(C)") ,
 paste = new JMenuItem("粘貼(P)") ,
 delete = new JMenuItem("刪除(L)") ,
 find = new JMenuItem("查找(F)") ,
 replace = new JMenuItem("替換(R)") ,
 goTo = new JMenuItem("轉到(G)") ,
 selectAll = new JMenuItem("全選(A)") ,
 time = new JMenuItem("時間/日期(D)") ;
 //格式
 private JMenuItem font = new JMenuItem("字體(F)") ;
 private JCheckBox autoLineWrap = new JCheckBox("自動換行(W)") ;
 //查看
 private JMenuItem state = new JMenuItem("狀態(S)") ;
 //幫助
 private JMenuItem
 checkHelp = new JMenuItem("查看幫助(H)") ,
 about = new JMenuItem("關于記事本(A)") ;
 //文本域
 private JTextArea txt = new JTextArea() ;
 //彈出菜單
 private JPopupMenu jpm = new JPopupMenu() ;
 //定義彈出窗口的打開狀態
 private static boolean isOpen = false ;
 //獲取屏幕的尺寸
 private int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() ;
 private int y = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() ;
 public MyNotepad(){
 //新建
 newFile.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 String text = txt.getText() ;
 if(!text.equals("")){
 String str[] = text.split("\n") ;
 int result = JOptionPane.showConfirmDialog(null, "是否將更改保存到 "+
 title+"?", "記事本", JOptionPane.YES_NO_CANCEL_OPTION) ;
 if(result == JOptionPane.NO_OPTION){ //不保存
 txt.setText("");
 }else if(result == JOptionPane.CANCEL_OPTION){} //取消保存
 else if(result == 0){ //保存
 JFileChooser jfc = new JFileChooser() ;
 jfc.setDialogTitle("保存");
 int ssd = jfc.showSaveDialog(MyNotepad.this) ;
 if(ssd == jfc.APPROVE_OPTION){
 File file = jfc.getSelectedFile() ;
 PrintStream out = null ;
 try {
 out = new PrintStream(new FileOutputStream(file)) ;
 } catch (FileNotFoundException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 for(String s:str){
 out.print(s + "\r\n");
 }
 out.close();
 txt.setText(""); ;
 }
 }
 }
 }
 });
 //打開
 open.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 JFileChooser jfc = new JFileChooser() ;
 jfc.setDialogTitle("打開");
 int result = jfc.showOpenDialog(MyNotepad.this) ;
 if(result == JFileChooser.CANCEL_OPTION){}
 else if(result == JFileChooser.APPROVE_OPTION){
 File file = jfc.getSelectedFile() ;
 BufferedReader input = null ;
 try {
 input = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
 } catch (FileNotFoundException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 String temp = null ;
 try {
 while((temp = input.readLine())!=null){
 txt.append(temp +"\n");
 }
 } catch (IOException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 try {
 input.close() ;
 } catch (IOException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 }
 } 
 });
 //保存
 save.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 String str[] = txt.getText().split("\n") ;
 JFileChooser jfc = new JFileChooser() ;
 jfc.setDialogTitle("保存");
 int ssd = jfc.showSaveDialog(MyNotepad.this) ;
 if(ssd == jfc.APPROVE_OPTION){
 File file = jfc.getSelectedFile() ;
 PrintStream out = null ;
 try {
 out = new PrintStream(new FileOutputStream(file)) ;
 } catch (FileNotFoundException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 for(String s:str){
 out.print(s + "\r\n");
 }
 out.close();
 }
 }
 });
 //退出
 exit.addActionListener(new ActionListener(){
 @Override
 public void actionPerformed(ActionEvent e) {
 String str = txt.getText() ;
 if(!str.equals("")){
 int result = JOptionPane.showConfirmDialog(null, "退出前是否保存?", "退出", 
 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) ;
 if(result == JOptionPane.YES_OPTION){}
 if(result == JOptionPane.NO_OPTION){
 dispose() ;
 }
 if(result == JOptionPane.CANCEL_OPTION){}
 }else{
 dispose() ;
 }
 }
 });
 /**
 * 撤銷功能
 */
 final UndoManager undom = new UndoManager() ;
 txt.getDocument().addUndoableEditListener(new UndoableEditListener(){
 @Override
 public void undoableEditHappened(UndoableEditEvent e) {
 undom.addEdit(e.getEdit()) ;
 }
 });
 undo.addActionListener(new ActionListener(){
 @Override
 public void actionPerformed(ActionEvent e) {
 if(undom.canUndo()){
 undom.undo();
 }
 }
 });
 //剪切
 cut.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 txt.cut() ;
 }
 });
 //粘貼
 paste.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 txt.paste();
 }
 });
 //刪除
 delete.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 int start = txt.getSelectionStart() ;
 int end = txt.getSelectionEnd() ;
 txt.replaceRange("", start, end);
 }
 });
 /**
 * 為了更好地訪問本類中的屬性,所以查找使用內部類
 */
 //定義查找內部類
 
 class FindDialog extends JDialog{
 private JPanel pan = new JPanel() ;
 private JLabel label = new JLabel("查找內容(N):") ;
 private JTextField txtf = new JTextField(20) ;
 private JButton btnf = new JButton("查找下一個(F)") ;
 private JButton btnc = new JButton("取消") ;
 private JCheckBox jcb = new JCheckBox("區分大小寫(C)") ;
 private JRadioButton jrb1 = new JRadioButton("向上(U)") ;
 private JRadioButton jrb2 = new JRadioButton("向下(D)",true) ;
 public FindDialog(){
 super(MyNotepad.this, "查找") ;
 //當文本框中有內容時按鈕才起作用
 txtf.getDocument().addDocumentListener(new DocumentListener(){
 
 @Override
 public void insertUpdate(DocumentEvent e) {
 btnf.setEnabled(true);
 }
 @Override
 public void removeUpdate(DocumentEvent e) {
 if(txtf.getText().length() == 0){
 btnf.setEnabled(false);
 }
 }
 @Override
 public void changedUpdate(DocumentEvent e) {
 }
 });
 btnf.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 String str = txtf.getText() ;
 String texta = txt.getText() ;
 int start = 0 ; 
 int end = 0 ;
 int caretPosition = txt.getCaretPosition() ; //記錄光標的起始位置
 if(jcb.isSelected()){ //區分大小寫
 if(jrb2.isSelected()){ //向下查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之后的位置開始查找
 start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
 start = texta.indexOf(str, start) ;
 if(start == -1){ //如果沒有找到
 JOptionPane.showMessageDialog(null, "找不到"+str);
 }else{ //如果找到了
 end = start + str.length() ;
 txt.select(start, end);
 }
 }else if(jrb1.isSelected()){ //向上查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之前的位置開始查找
 end = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionStart()) ;
 String subtext = texta.substring(0, end) ;
 start = subtext.lastIndexOf(str, end-1) ;
 if(start == -1){
 JOptionPane.showMessageDialog(null, "找不到"+str) ;
 }else{
 end = start + str.length() ;
 txt.select(start, end);
 }
 }
 }
 if(!jcb.isSelected()){ //不區分大小寫
 texta = texta.toLowerCase() ;
 if(jrb2.isSelected()){ //向下查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之后的位置開始查找
 start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
 start = texta.indexOf(str.toLowerCase(), start) ;
 if(start == -1){ //如果沒有找到
 JOptionPane.showMessageDialog(null, "找不到"+str) ;
 }else{ //如果找到了
 end = start + str.length() ;
 txt.select(start, end);
 }
 }else if(jrb1.isSelected()){ //向上查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之前的位置開始查找
 end = (txt.getSelectedText() == null ? caretPosition : txt.getSelectionStart()) ;
 String subtext = texta.substring(0, end) ;
 start = subtext.lastIndexOf(str.toLowerCase(), end-1) ;
 if(start == -1){
 JOptionPane.showMessageDialog(null, "找不到"+str) ;
 }else{
 end = start + str.length() ;
 txt.select(start, end);
 }
 }
 }
 }
 });
 btnc.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 dispose() ;
 isOpen = false ;
 }
 });
 
 this.setLayout(null) ;
 label.setBounds(12,10,80,20) ;
 txtf.setBounds(100,10,170,20) ;
 btnf.setBounds(280,10,90,20) ;
 btnf.setMargin(new Insets(0, 0,0, 0)) ;
 btnf.setEnabled(false); //初始化查找下一個按鈕不可選
 jcb.setBounds(12,70,110,20) ;
 jrb1.setMargin(new Insets(0,0,0,0)) ;
 jrb2.setMargin(new Insets(0,0,0,0)) ;
 ButtonGroup group = new ButtonGroup() ;
 group.add(jrb1);
 group.add(jrb2);
 pan.add(jrb1) ;
 pan.add(jrb2) ;
 pan.setBorder(BorderFactory.createTitledBorder("方向")) ;
 pan.setBounds(120,40,150,55) ;
 btnc.setBounds(280,40,90,20) ;
 btnc.setMargin(new Insets(0,0,0,0)) ;
 add(btnf) ;
 add(label) ;
 add(txtf) ;
 add(jcb) ;
 add(pan) ;
 add(btnc) ;
 setSize(380,130) ;
 setLocation(x/2-190,y/2-65) ;
 setResizable(false) ;
 setVisible(true) ;
 setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
 //每次只能顯示一個窗口
 addWindowListener(new WindowAdapter(){
 public void windowOpened(WindowEvent e){
 isOpen = true ;
 }
 }) ;
 addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e){
 isOpen = false ;
 }
 }) ;
 }
 }
 //查找的監聽事件
 find.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 if(!isOpen){
 new FindDialog() ;
 }
 }
 });
 
 
 //替換內部類
 class ReplaceDialog extends JDialog{
 private JLabel label1 = new JLabel("查找內容(N)") ;
 private JLabel label2 = new JLabel("替換為(P)") ;
 private JTextField field1 = new JTextField(20) ;
 private JTextField field2 = new JTextField(20) ;
 private JButton find = new JButton("查找下一個(F)") ;
 private JButton replace = new JButton("替換(R)") ;
 private JButton replaceAll = new JButton("全部替換(A)") ;
 private JButton canc = new JButton("取消") ;
 private JCheckBox jcb = new JCheckBox("區分大小寫(C)") ;
 public ReplaceDialog(){
 super(MyNotepad.this,"查找") ;
 this.setLayout(null) ;
 label1.setBounds(12,5,80,20) ;
 label2.setBounds(12,30,80,20) ;
 field1.setBounds(100,5,170,20) ;
 field2.setBounds(100,30,170,20) ;
 find.setBounds(280,5,90,20) ;
 find.setMargin(new Insets(0, 0,0, 0)) ;
 replace.setBounds(280,30,90,20) ;
 replace.setMargin(new Insets(0,0,0,0)) ;
 replaceAll.setBounds(280,55,90,20) ;
 replaceAll.setMargin(new Insets(0,0,0,0)) ;
 jcb.setBounds(12,70,105,20) ;
 jcb.setMargin(new Insets(0,0,0,0)) ;
 canc.setBounds(280,80,90,20) ;
 field1.getDocument().addDocumentListener(new DocumentListener(){
 //當文本框中有內容時按鈕才起作用
 @Override
 public void insertUpdate(DocumentEvent e) {
 find.setEnabled(true);
 replace.setEnabled(true);
 replaceAll.setEnabled(true);
 }
 @Override
 public void removeUpdate(DocumentEvent e) {
 if(field1.getText().length() == 0){
 find.setEnabled(false);
 replace.setEnabled(false);
 replaceAll.setEnabled(false);
 }
 }
 @Override
 public void changedUpdate(DocumentEvent e) {
 }
 });
 //查找下一個按鈕
 find.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 new findFunction() ;
 }
 });
 //替換按鈕
 replace.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 //如果有選中的內容就替換,然后選中下一個要替換的內容,否則先查找要替換的內容
 if(txt.getSelectedText()!=null){ 
 txt.replaceSelection(field2.getText());
 }
 new findFunction() ;
 }
 });
 //替換所有按鈕
 replaceAll.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 String str = txt.getText() ;
 if(jcb.isSelected()){
 str = str.replaceAll(field1.getText(), field2.getText()) ;
 }else{
 str = str.replaceAll("(?i)" + field1.getText(), field2.getText()) ;
 }
 txt.setText(str);
 }
 });
 //取消按鈕
 canc.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 dispose() ;
 isOpen = false ;
 }
 });
 add(label1) ;
 add(label2) ;
 add(field1) ;
 add(field2) ;
 find.setEnabled(false);
 replace.setEnabled(false);
 replaceAll.setEnabled(false);
 add(find) ;
 add(replace) ;
 add(replaceAll) ;
 add(jcb) ;
 add(canc) ;
 setSize(380,130) ;
 setLocation(x/2-190,y/2-65) ;
 setResizable(false) ;
 setVisible(true) ;
 setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
 addWindowListener(new WindowAdapter(){
 public void windowOpened(WindowEvent e){
 isOpen = true ;
 }
 }) ;
 addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e){
 isOpen = false ;
 }
 }) ;
 }
 //替換對話框中查找功能類
 /**
 * 為了簡化代碼,將替換對話框里面的查找功能提取出來,成為一個內部類
 */
 class findFunction {
 
 public findFunction(){ //要替換的字符串的位置
 int start = 0 ;
 int end = 0 ;
 int caretPosition = txt.getCaretPosition() ;
 String str = field1.getText() ;
 String texta = txt.getText() ;
 //區分大小寫,向下查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之后的位置開始查找
 if(jcb.isSelected()){ 
 start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
 start = texta.indexOf(str.toLowerCase(), start) ;
 if(start == -1){ //如果沒有找到
 JOptionPane.showMessageDialog(null, "找不到"+str) ;
 }else{ //如果找到了
 end = start + str.length() ;
 txt.select(start, end);
 }
 }else if(!jcb.isSelected()){ //不區分大小寫
 texta = texta.toLowerCase() ;
 //向下查詢,如果有光標就從光標的位置開始查找,否則就從選中的文本之后的位置開始查找
 start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
 start = texta.indexOf(str.toLowerCase(), start) ;
 if(start == -1){ //如果沒有找到
 JOptionPane.showMessageDialog(null, "找不到"+str) ;
 }else{ //如果找到了
 end = start + str.length() ;
 txt.select(start, end);
 }
 }
 }
 }
 }
 replace.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 if(!isOpen){
 new ReplaceDialog() ;
 }
 }
 });
 //轉到內部類
 class GoToDialog extends JDialog{
 private JLabel label = new JLabel("行號(L):") ;
 private JTextField field = new JTextField() ;
 private JButton goToBtn = new JButton("轉到") ;
 private JButton canBtn = new JButton("取消") ;
 private int rowNum = 0 ;//行號 
 public GoToDialog(){
 field.addKeyListener(new KeyAdapter(){
 public void keyTyped(KeyEvent e){
 if(!(e.getKeyChar()>='0' && e.getKeyChar()<='9' )){
 e.consume();
 }
 }
 });
 //轉到
 goToBtn.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 rowNum = Integer.parseInt(field.getText()) ;
 if(rowNum>txt.getLineCount()){
 JOptionPane.showMessageDialog(null, "行數超過了總行數", "記事本-跳行",JOptionPane.INFORMATION_MESSAGE);
 field.setText(txt.getLineCount() +"") ;
 field.requestFocus() ; //獲取文本域的焦點
 field.selectAll();
 }else{
 int position = 0 ;
 try {
 position = txt.getLineStartOffset(rowNum-1) ;
 } catch (BadLocationException e1) {
 // TODO Auto-generated catch block
 e1.printStackTrace();
 }
 GoToDialog.this.dispose();
 txt.requestFocus();
 txt.setCaretPosition(position);
 }
 }
 });
 //取消
 canBtn.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 dispose() ;
 isOpen = false ;
 }
 });
 setLayout(null) ;
 label.setBounds(12,10,100,20) ;
 field.setBounds(12,30,230,20) ;
 goToBtn.setBounds(85,65,75,20) ;
 canBtn.setBounds(167,65,75,20) ;
 add(label) ;
 add(field) ;
 add(goToBtn) ;
 add(canBtn) ; 
 setTitle("轉到指定行") ;
 setModal(true) ; //當對話框彈出時母窗口不可編輯
 setSize(270,130) ;
 setLocation(x/2-135,y/2-65) ;
 setResizable(false) ;
 setVisible(true) ;
 setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
 addWindowListener(new WindowAdapter(){
 public void windowOpened(WindowEvent e){
 isOpen = true ;
 }
 }) ;
 addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e){
 isOpen = false ;
 }
 }) ;
 }
 }
 //轉到
 goTo.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 if(!isOpen){
 new GoToDialog() ;
 }
 }
 });
 //全選
 selectAll.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 txt.requestFocus();
 txt.selectAll() ;
 }
 });
 time.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 String dateTime = null ;
 int pos = txt.getCaretPosition() ;
 dateTime = new SimpleDateFormat("hh:mm yyyy/MM/dd").format(new Date()) ;
 txt.insert(dateTime, pos);
 }
 });
 //自動換行
 autoLineWrap.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 if(autoLineWrap.isSelected()){
 txt.setLineWrap(true);
 }else{
 txt.setLineWrap(false);
 }
 }
 });
 //字體內部類
 class FontDialog extends JDialog{
 private JLabel label1 = new JLabel("字體(F):") ;
 private JLabel label2 = new JLabel("字形(Y):") ;
 private JLabel label3 = new JLabel("大小(S):") ;
 private JLabel instns = new JLabel("中文示例AaBaCc",JLabel.CENTER) ;
 private JTextField field1 = new JTextField() ;
 private JTextField field2 = new JTextField() ;
 private JTextField field3 = new JTextField() ;
 private String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames() ;
 private JScrollPane scr1 = new JScrollPane() ;
 private JScrollPane scr2 = new JScrollPane() ;
 private JScrollPane scr3 = new JScrollPane() ;
 private JList fontList = null ;
 private JList fStyleList = null ;
 private JList fSizeList = null ;
 private JButton okBtn = new JButton("確定") ;
 private JButton cancBtn = new JButton("取消") ;
 //示例的顯示
 private String selectedFont = "Fixedsys";
 private int selectedStyle = Font.PLAIN;
 private float selectedSize = 16;
 public FontDialog() {
 
 fontList = new JList(fonts) ;
 //fontStyle
 String style[] = {"常規","傾斜","粗體","傾斜 粗體"} ;
 fStyleList = new JList(style) ;
 //fontSize
 String size[] = {"8","9","10","11","12","14","16","18","20","22","24",
 "26","28","36","48","72","初號","小號","一號","小一","二號",
 "小二","三號","小三","四號","小四","五號","六號","小六","七號","八號"} ;
 fSizeList = new JList(size) ;
 //Jlist中一次只能選擇一個選項
 fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
 fStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
 fSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
 scr1.add(fontList) ;
 scr2.add(fStyleList) ;
 scr3.add(fSizeList) ;
 scr1.setViewportView(fontList);
 scr2.setViewportView(fStyleList);
 scr3.setViewportView(fSizeList);
 okBtn.setBounds(250,450,80,30) ;
 cancBtn.setBounds(340,450,80,30) ;
 label1.setBounds(20,20,50,20) ;
 label2.setBounds(205,20,50,20) ;
 label3.setBounds(350,20,50,20) ;
 instns.setBounds(205,280,215,80) ;
 instns.setBorder(BorderFactory.createTitledBorder("示例")) ;
 field1.setBounds(20,40,170,20) ;
 field2.setBounds(205,40,130,20) ;
 field3.setBounds(350,40,70,20) ;
 scr1.setBounds(20,60,170,170) ;
 scr2.setBounds(205,60,130,170) ;
 scr3.setBounds(350,60,70,150) ;
 scr1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
 scr2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
 scr3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
 //文本框1
 field1.addKeyListener(new KeyAdapter(){
 public void keyTyped(KeyEvent e){
 int count = 0 ; //文本框中的字符數
 String str = null ; //保存輸入到文本框中的字符
 int size = fontList.getModel().getSize() ; //fontList中的文本個數
 str = field1.getText()+e.getKeyChar()+"" ;
 count = str.length() ;
 
 for(int i=0; i=count){
 //判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
 if(fontList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
 fontList.ensureIndexIsVisible(size-i>=10 ? i+9 : size-1);
 if(fontList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
 fontList.setSelectedIndex(i);
 }
 break ;
 }
 else{
 fontList.ensureIndexIsVisible(0);
 fontList.clearSelection();
 }
 }
 }
 }
 });
 //文本框2
 field2.addKeyListener(new KeyAdapter(){
 public void keyTyped(KeyEvent e){
 int count = 0 ; //文本框中的字符數
 String str = null ; //保存輸入到文本框中的字符
 int size = fStyleList.getModel().getSize() ; //fontList中的文本個數
 str = field2.getText()+e.getKeyChar()+"" ;
 count = str.length() ;
 
 for(int i=0; i=count){
 //判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
 if(fStyleList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
 if(fStyleList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
 fStyleList.setSelectedIndex(i);
 }
 break ;
 }
 else{
 fStyleList.clearSelection();
 }
 }
 }
 }
 });
 //文本框3
 field3.addKeyListener(new KeyAdapter(){
 public void keyTyped(KeyEvent e){
 int count = 0 ; //文本框中的字符數
 String str = null ; //保存輸入到文本框中的字符
 int size = fSizeList.getModel().getSize() ; //fontList中的文本個數
 str = field3.getText()+e.getKeyChar()+"" ;
 count = str.length() ;
 
 for(int i=0; i=count){
 //判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
 if(fSizeList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
 fSizeList.ensureIndexIsVisible(size-i>=9 ? i+8 : size-1);
 if(fSizeList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
 fSizeList.setSelectedIndex(i);
 }
 break ;
 }
 else{
 fSizeList.ensureIndexIsVisible(0);
 fSizeList.clearSelection();
 }
 }
 }
 }
 });
 //設置示例中的文本字體樣式
 //設置字形與字號對照表
 final Map map = new HashMap() ;
 map.put("常規", (float) Font.PLAIN) ;
 map.put("傾斜", (float) Font.ITALIC) ;
 map.put("粗體", (float) Font.BOLD) ;
 map.put("傾斜 粗體", (float) (Font.ITALIC+Font.BOLD)) ;
 map.put("初號", 42f) ;
 map.put("小號", 36f) ;
 map.put("一號", 26f) ;
 map.put("小一", 24f) ;
 map.put("二號", 22f) ;
 map.put("小二", 18f) ;
 map.put("三號", 16f) ;
 map.put("小三", 15f) ;
 map.put("四號", 14f) ;
 map.put("小四", 12f) ;
 map.put("五號", 10.5f) ;
 map.put("六號", 7.5f) ;
 map.put("小六", 6.5f) ;
 map.put("七號", 5.5f) ;
 map.put("八號", 5f) ;
 
 //字體列表監聽事件
 fontList.addListSelectionListener(new ListSelectionListener(){
 @Override
 public void valueChanged(ListSelectionEvent e) {
 String txtFont = txt.getFont().getName() ; //獲取文本中的字體
 selectedFont = fontList.isSelectionEmpty() ? txtFont :fontList.getSelectedValue() ;
 instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
 }
 }) ;
 //字體樣式監聽事件
 fStyleList.addListSelectionListener(new ListSelectionListener(){
 @Override
 public void valueChanged(ListSelectionEvent e) {
 int txtStyle = txt.getFont().getStyle() ; //獲取文本中的字體
 selectedStyle = (int) (fStyleList.isSelectionEmpty() ? txtStyle :map.get(fStyleList.getSelectedValue())) ;
 instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
 }
 }) ;
 //字體大小監聽
 fSizeList.addListSelectionListener(new ListSelectionListener(){
 public void valueChanged(ListSelectionEvent e){
 int txtSize = txt.getFont().getSize() ;
 if(!fSizeList.isSelectionEmpty()){
 String temp = fSizeList.getSelectedValue() ;
 if(temp.matches("\\d+")){
 selectedSize = Integer.parseInt(temp) ;
 }else{
 selectedSize = map.get(fSizeList.getSelectedValue()) ;
 }
 }
 instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
 }
 });
 //確定按鈕
 okBtn.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 txt.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
 isOpen = false ;
 dispose() ;
 }
 });
 //取消按鈕
 cancBtn.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 dispose() ;
 isOpen = false ;
 }
 });
 /*class MyRender extends DefaultListCellRenderer{
 public Component getListCellRendererComponent(JList<?> list, Object value, 
 int index, boolean isSelected,
 boolean cellHasFocus){
 String font = value.toString() ;
 setFont(new Font(font,Font.PLAIN,12)) ;
 return this ;
 }
 }*/
 setLayout(null) ;
 add(label1) ;
 add(label2) ;
 add(label3) ;
 add(instns) ;
 add(field1) ;
 add(field2) ;
 add(field3) ;
 add(scr1) ;
 add(scr2) ;
 add(scr3) ;
 add(okBtn) ;
 add(cancBtn) ;
 setModal(true) ; //當對話框彈出時母窗口不可編輯
 setSize(440,530) ;
 setLocation(x/2-220,y/2-265) ;
 setResizable(false) ;
 setVisible(true) ;
 setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
 addWindowListener(new WindowAdapter(){
 public void windowOpened(WindowEvent e){
 isOpen = true ;
 }
 }) ;
 addWindowListener(new WindowAdapter(){
 public void windowClosing(WindowEvent e){
 isOpen = false ;
 }
 }) ;
 }
 }
 //字體
 font.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 if(!isOpen){
 new FontDialog() ;
 }
 }
 });
 //查看幫助
 checkHelp.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 JOptionPane.showMessageDialog(null, "與Windows系統下的幫助相似", "幫助", JOptionPane.CLOSED_OPTION);
 }
 });
 //關于
 about.addActionListener(new ActionListener(){
 public void actionPerformed(ActionEvent e){
 JOptionPane.showMessageDialog(null, "仿Windows記事本,初學Java的練手作品", "關于", JOptionPane.CLOSED_OPTION);
 }
 });
 //右鍵彈出菜單內部類
 class popupListener extends MouseAdapter{
 private JPopupMenu popup = null ;
 public popupListener(JPopupMenu popup){
 this.popup = popup ;
 
 }
 public void mouseReleased(MouseEvent e){
 showPopupMenu(e) ;
 }
 public void mouseClicked(MouseEvent e){
 showPopupMenu(e) ;
 }
 private void showPopupMenu(MouseEvent e) {
 if (e.isPopupTrigger()) {
 //右鍵彈出菜單
 jpm.add(undo) ;
 jpm.add(cut) ;
 jpm.add(copy) ;
 jpm.add(delete) ;
 jpm.add(find) ;
 jpm.add(replace) ;
 jpm.add(goTo) ;
 jpm.add(selectAll) ;
 jpm.add(time) ;
 popup.show(e.getComponent(), e.getX(), e.getY());
 }
 }
 }
 
 //右鍵彈出菜單
 txt.addMouseListener(new popupListener(jpm)) ;
 //設置快捷鍵
 newFile.setAccelerator(KeyStroke.getKeyStroke('N',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 open.setAccelerator(KeyStroke.getKeyStroke('O',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 save.setAccelerator(KeyStroke.getKeyStroke('S',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 
 undo.setAccelerator(KeyStroke.getKeyStroke('Z',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 cut.setAccelerator(KeyStroke.getKeyStroke('X',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 copy.setAccelerator(KeyStroke.getKeyStroke('C',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 paste.setAccelerator(KeyStroke.getKeyStroke('V',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 find.setAccelerator(KeyStroke.getKeyStroke('F',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 replace.setAccelerator(KeyStroke.getKeyStroke('H',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 goTo.setAccelerator(KeyStroke.getKeyStroke('G',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 selectAll.setAccelerator(KeyStroke.getKeyStroke('A',java.awt.event.InputEvent.CTRL_DOWN_MASK));
 time.setAccelerator((KeyStroke) KeyStroke.getAWTKeyStroke((char) KeyEvent.VK_F5));
 //設置助記鍵
 file.setMnemonic('F');
 edit.setMnemonic('E');
 format.setMnemonic('O');
 view.setMnemonic('V');
 help.setMnemonic('H');
 
 newFile.setMnemonic('N');
 open.setMnemonic('O');
 save.setMnemonic('S');
 exit.setMnemonic('X');
 
 undo.setMnemonic('U'); 
 cut.setMnemonic('T'); 
 copy.setMnemonic('C');
 paste.setMnemonic('P'); 
 delete.setMnemonic('L');
 find.setMnemonic('F');
 replace.setMnemonic('R');
 goTo.setMnemonic('G');
 selectAll.setMnemonic('A');
 time.setMnemonic('D');
 
 font.setMnemonic('F');
 autoLineWrap.setMnemonic('W');
 
 state.setMnemonic('S');
 
 checkHelp.setMnemonic('H');
 about.setMnemonic('A');
 
 txt.setFont(new Font("Fixedsys",Font.PLAIN,16));
 txt.setEditable(true);
 
 file.add(newFile) ;
 file.add(open) ;
 file.add(save) ;
 file.addSeparator();
 file.add(exit) ;
 
 edit.add(undo) ;
 edit.addSeparator();
 edit.add(cut) ;
 edit.add(copy) ;
 edit.add(paste) ;
 edit.add(delete) ;
 edit.addSeparator();
 edit.add(find) ;
 edit.add(replace) ;
 edit.add(goTo) ;
 edit.addSeparator();
 edit.add(selectAll) ;
 edit.add(time) ;
 
 format.add(autoLineWrap) ;
 format.add(font) ;
 view.add(state) ;
 help.add(checkHelp) ;
 help.addSeparator();
 help.add(about) ;
 
 mb.add(file) ;
 mb.add(edit) ;
 mb.add(format) ;
 mb.add(view) ;
 mb.add(help) ;
 setJMenuBar(mb) ;
 add(mp) ;
 add(new JScrollPane(txt)) ;
 setVisible(true) ;
 setSize(530,640) ;
 setLocation(x/2-265,y/2-320);
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
 }
}
package org.mfy.notepad;
 
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
public class Notepad {
 
 public static void main(String[] args) {
 try {
 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 } catch (ClassNotFoundException | InstantiationException
 | IllegalAccessException | UnsupportedLookAndFeelException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 new MyNotepad() ;
 }
 
}

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

向AI問一下細節

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

AI

曲沃县| 镇坪县| 新津县| 思茅市| 海盐县| 金溪县| 甘南县| 航空| 芒康县| 鹤壁市| 中阳县| 丽江市| 沙洋县| 锡林郭勒盟| 祁门县| 遵义县| 娄烦县| 永定县| 甘洛县| 盐山县| 高邑县| 无棣县| 临沭县| 开化县| 庆元县| 克山县| 金平| 尼勒克县| 上虞市| 桦甸市| 和林格尔县| 华池县| 澄迈县| 万载县| 通榆县| 闻喜县| 镇康县| 宿州市| 芷江| 治县。| 齐齐哈尔市|