text

MainFrame

package p1;//0:刚启动1:新建 2: 修改过3:保存过

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.PrintJob;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.PrivateKey;
import java.sql.Savepoint;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.naming.spi.DirStateFactory.Result;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.colorchooser.ColorChooserComponentFactory;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.DefaultEditorKit.CopyAction;
import javax.swing.undo.UndoManager;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.omg.CORBA.PUBLIC_MEMBER;

public class MainFrame extends JFrame implements ActionListener{
private static final long serialVersionUID = 7390199394170L;
private JPanel contentPane;
private JTextArea textArea;

private JMenuItem iO;//打开
private JMenuItem iSave;//保存
private JMenuItem iSA;//另存为
private JMenuItem iN;//新建
private JMenuItem iPe;//页面设置
private JMenuItem iPt;//打印
private JMenuItem iExit;//退出
private JMenuItem iSFH;//查看帮助
private JMenuItem iAN;//关于记事本
private JMenuItem iU;//撤销
private JMenuItem iCut;//剪切
private JMenuItem iCopy;//复制
private JMenuItem iPte;//粘贴
private JMenuItem iD;//删除
private JMenuItem iFnd;//查找
private JMenuItem iFN;//查找下一个
private JMenuItem iR;//替换
private JMenuItem iT;//跳转
private JMenuItem iSAll;//全选
private JMenuItem iTime;//时间
private JMenuItem iFont;//字体大小
private JMenuItem iColor;//背景颜色
private JMenuItem iFC;//字体颜色

private JCheckBoxMenuItem iNL;// 自动换行
private JCheckBoxMenuItem iS;//设置状态

private JScrollPane scrollPane;

private JToolBar tS;//字数统计

private JLabel l2;
private JLabel l3;

private JMenu iEdit;//编辑
private JMenu iF;//格式
private JMenu iC;//查看
private JMenu iH;//帮助

private JSeparator separator;

public static JLabel l1;
public UndoManager undoMgr = new UndoManager();//撤销管理器
public Clipboard clipboard = new Clipboard("剪切");//剪切板

int flag = 0;
int length =0;
int sum = 0;
int linenum = 1;//文本行数
int columnnum = 1;//文本列数

String currentFileName = null;//文件名
String currentPath = null;//路径

PrintJob p = null;//声明一个要打印对象
Graphics g = null;//要打印的对象

JColorChooser jcc1 = null;//背景颜色
Color color = Color.BLACK;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable(){
        public void run() {
            try {
                MainFrame frame = new MainFrame();
                frame.setVisible(true);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
GregorianCalendar c = new GregorianCalendar();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
private JPopupMenu popupMenu;
private JMenuItem popM_Undo;//撤销
private JMenuItem popM_Cut;//剪切
private JMenuItem popM_Copy;//复制
private JMenuItem popM_Paste;//粘贴
private JMenuItem popM_Delete;//删除
private JMenuItem popM_SelectAll;//全选
private JMenuItem popM_toLeft;//从左向右阅读
private JMenuItem popM_showUnicode;//显示Unicode控制字符
private JMenuItem popM_closeMe;//关闭
private JMenuItem popM_InsertUnicode;//插入Unicode控制字符
private JMenuItem popM_RestartSelect;//汉字重选
private JMenuItem popM_Redo;
private JSeparator separator_1;
private JSeparator separator_2;
private JSeparator separator_3;
private JSeparator separator_4;
private JSeparator separator_5;
private JSeparator separator_6;
private JSeparator separator_7;
private JSeparator separator_8;
private JMenuItem iRedo;

public MainFrame() {
    try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (UnsupportedLookAndFeelException e1) {
                e1.printStackTrace();
            }
    setTitle("护眼记事本 V2019 1.0版");
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    setBounds(100, 100, 700, 572);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    
    JMenu iFile = new JMenu("文件(F)");
    iFile.setMnemonic('F');
    menuBar.add(iFile);
    
    iN = new JMenuItem("新建(N)",'N');
    iN.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N,
            java.awt.Event.CTRL_MASK));
    iN.addActionListener(this);
        iFile.add(iN);
        
        iO = new JMenuItem("打开(O)",'O');
        iO.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,
                        java.awt.Event.CTRL_MASK)); 
        iO.addActionListener(this);
        iFile.add(iO);
            
        iSave = new JMenuItem("保存(S)");
        iSave.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
                    java.awt.Event.CTRL_MASK));
        iSave.addActionListener(this);
        iFile.add(iSave);
            
        iSA = new JMenuItem("另存为(A)");
        iSA.addActionListener(this);
        iFile.add(iSA);
            
        separator = new JSeparator();
        iFile.add(separator);
            
        iPe = new JMenuItem("页面设置(U)",'U');
        iPe.addActionListener(this);
        iFile.add(iPe);
            
        iPt = new JMenuItem("打印(P)",'P');
        iPt.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P,
                    java.awt.Event.CTRL_MASK));
        iPt.addActionListener(this);
        iFile.add(iPt);
        
        separator_1=new JSeparator();
        iFile.add(separator_1);
        
        iExit = new JMenuItem("退出(X)",'X');
        iExit.addActionListener(this);
        iFile.add(iExit);
        
        iEdit = new JMenu("编辑(E)");
        iEdit.setMnemonic('E');
        menuBar.add(iEdit);
        
        iU = new JMenuItem("撤销(U)",'U');
        iU.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z,
                java.awt.Event.CTRL_MASK));
        iU.addActionListener(this);
        iEdit.add(iU);
        
        iRedo = new JMenuItem("恢复(R)");
        iRedo.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R,
                java.awt.Event.CTRL_MASK));
        iRedo.addActionListener(this);
        iEdit.add(iRedo);
        
        iCut = new JMenuItem("剪切(T)",'T');
        iCut.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X,
                java.awt.Event.CTRL_MASK));
        iCut.addActionListener(this);
        
        separator_6 = new JSeparator();
        iEdit.add(separator_6);
        iEdit.add(iCut);
        
        iCopy = new JMenuItem("复制(C)",'C');
        iCopy.addActionListener(this);
        iCopy.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C,
                java.awt.Event.CTRL_MASK));
        iEdit.add(iCopy);
        
        iPte = new JMenuItem("粘贴(P)",'P');
        iPte.addActionListener(this);
        iPte.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V,
                java.awt.Event.CTRL_MASK));
        iEdit.add(iPte);
        
        iD = new JMenuItem("删除(L)",'L');
        iD.addActionListener(this);
        iD.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,  
                InputEvent.CTRL_MASK));  
        iEdit.add(iD);
        
        separator_7 = new JSeparator();
        iEdit.add(separator_7);
        
        iFnd = new JMenuItem("查找(F)",'F');
        iFnd.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
                Event.CTRL_MASK));
        iFnd.addActionListener(this);
        iEdit.add(iFnd);
        
        iFN = new JMenuItem("查找下一个(N)",'N');
        iFN.setAccelerator(KeyStroke.getKeyStroke("F3"));
        iFN.addActionListener(this);
        iEdit.add(iFN);
        
        iR = new JMenuItem("替换(R)",'R');
        iR.addActionListener(this);
        iR.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
                Event.CTRL_MASK));
        iEdit.add(iR);
        
        iT = new JMenuItem("转到(G)",'G');
        iT.addActionListener(this);
        iT.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
                Event.CTRL_MASK));
        iEdit.add(iT);
        
        iSAll = new JMenuItem("全选(A)",'A');
        iSAll.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,
                java.awt.Event.CTRL_MASK));
        iSAll.addActionListener(this);
        
        separator_8 = new JSeparator();
        iEdit.add(separator_8);
        iEdit.add(iSAll);
        
        iTime = new JMenuItem("时间/日期(D)",'D');
        iTime.addActionListener(this);
        iTime.setAccelerator(KeyStroke.getKeyStroke("F5"));
        iEdit.add(iTime);
        
        iF = new JMenu("格式(O)");
        iF.setMnemonic('O');
        menuBar.add(iF);
        
        iNL = new JCheckBoxMenuItem("自动换行(W)");
        iNL.addActionListener(this);
        iF.add(iNL);
        
        iFont = new JMenuItem("字体大小(F)...");
        iFont.addActionListener(this);
        iF.add(iFont);
        
        iColor = new JMenuItem("背景颜色(C)...");
        iColor.addActionListener(this);
        iF.add(iColor);
        
        iFC = new JMenuItem("字体颜色(I)...");
        iFC.addActionListener(this);
        iF.add(iFC);
        
        iC = new JMenu("查看(V)");
        iC.setMnemonic('V');
        menuBar.add(iC);
        
        iS = new JCheckBoxMenuItem("状态栏(S)");
        iS.addActionListener(this);
        iC.add(iS);
        
        iH = new JMenu("帮助(H)");
        iH.setMnemonic('H');
        menuBar.add(iH);
        
        iSFH = new JMenuItem("查看帮助(H)",'H');
        iSFH.addActionListener(this);
        iH.add(iSFH);
        
        iAN = new JMenuItem("关于记事本(A)",'A');
        iAN.addActionListener(this);
        iH.add(iAN);
        
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        //设置边框布局
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        
        textArea = new JTextArea();
        
        //VERTICAL垂直    HORIZONTAL水平
        scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        //contentPane2=new JPanel();
        //contentPane2.setSize(10,textArea.getSize().height);
        //contentPane.add(contentPane2, BorderLayout.WEST);
        TestLine view = new TestLine();
        scrollPane.setRowHeaderView(view);
        
        popupMenu = new JPopupMenu();
        addPopup(textArea, popupMenu);
        
        popM_Undo = new JMenuItem("撤销(U)");
        popM_Undo.addActionListener(this);
        popupMenu.add(popM_Undo);
        
        popM_Redo = new JMenuItem("恢复(R)");
        popM_Redo.addActionListener(this);
        popupMenu.add(popM_Redo);
        
        separator_2 = new JSeparator();
        popupMenu.add(separator_2);
        
        popM_Cut = new JMenuItem("剪切(T)");
        popM_Cut.addActionListener(this);
        popupMenu.add(popM_Cut);
        
        popM_Copy = new JMenuItem("复制(C)");
        popM_Copy.addActionListener(this);
        popupMenu.add(popM_Copy);
        
        popM_Paste = new JMenuItem("粘贴(P)");
        popM_Paste.addActionListener(this);
        popupMenu.add(popM_Paste);
        
        popM_Delete = new JMenuItem("删除(D)");
        popM_Delete.addActionListener(this);
        popupMenu.add(popM_Delete);
        
        separator_3 = new JSeparator();
        popupMenu.add(separator_3);
        
        popM_SelectAll = new JMenuItem("全选(A)");
        popM_SelectAll.addActionListener(this);
        popupMenu.add(popM_SelectAll);
        
        separator_4 = new JSeparator();
        popupMenu.add(separator_4);
        
        popM_toLeft = new JMenuItem("从右到左的阅读顺序(R)");
        popM_toLeft.addActionListener(this);
        popupMenu.add(popM_toLeft);
        
        popM_showUnicode = new JMenuItem("显示Unicode控制字符(S)");
        popM_showUnicode.addActionListener(this);
        popupMenu.add(popM_showUnicode);
        
        popM_InsertUnicode = new JMenuItem("插入Unicode控制字符(I)");
        popM_InsertUnicode.addActionListener(this);
        popupMenu.add(popM_InsertUnicode);
        
        separator_5 = new JSeparator();
        popupMenu.add(separator_5);
        
        popM_closeMe = new JMenuItem("关闭IME(L)");
        popM_closeMe.addActionListener(this);
        popupMenu.add(popM_closeMe);
        
        popM_RestartSelect = new JMenuItem("汉字重选(R)");
        popM_RestartSelect.addActionListener(this);
        popupMenu.add(popM_RestartSelect);//添加到面板中
        
        contentPane.add(scrollPane, BorderLayout.CENTER);//撤销管理器
        
        textArea.getDocument().addUndoableEditListener(undoMgr);
        
        tS = new JToolBar();
        tS.setSize(textArea.getSize().width,10);
        
        l1=new JLabel("当前系统时间:"+hour+":"+min+":"+second+" ");
        tS.add(l1);
        tS.addSeparator();
        
        l2 = new JLabel("第"+linenum+" 行,第 "+columnnum+"列 ");
        tS.add(l2);
        tS.addSeparator();
        
        l3 = new JLabel("  一共 "+length+" 字 ");
        tS.add(l3);
        textArea.addCaretListener(new CaretListener() {//记录行数和列数
            public void caretUpdate(CaretEvent e) {
                JTextArea editArea = (JTextArea)e.getSource();
                try {
                    int caretpos = editArea.getCaretPosition();
                    linenum = editArea.getLineOfOffset(caretpos);
                    columnnum = caretpos - textArea.getLineStartOffset(linenum);
                    linenum += 1;
                    l2.setText("    第 " + linenum + " 行, 第 " + (columnnum+1)+" 列  ");
                    length=MainFrame.this.textArea.getText().toString().length();
                    l3.setText("    一共 " +length+" 字  ");
                }
                catch(Exception ex) { }
            }});
        
        contentPane.add(tS, BorderLayout.SOUTH);
        tS.setVisible(true);
        tS.setFloatable(true);
        Clock clock=new Clock();
        clock.start();
        
        
        final JPopupMenu jPopupMenu =new JPopupMenu();//创建弹出式菜单
        textArea.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getButton()==MouseEvent.BUTTON3)//只响应鼠标右击
                {
                    jPopupMenu.show(e.getComponent(),e.getX(),e.getY());
                }
            }
                    
        });
        
        isChanged();
        
        this.MainFrameWidowListener();
            }
private void isChanged() {
    textArea.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            Character c =e.getKeyChar();
            if(c != null && !textArea.getText().toString().contentEquals("")) {
                flag = 2;
            }
        }
    });
}
private void MainFrameWidowListener() {
     this.addWindowListener(new WindowAdapter(){
         @Override
         public void windowClosing(WindowEvent e) {
             if(flag==2 && currentPath==null){
                 //这是弹出小窗口
                 //1、(刚启动记事本为0,刚新建文档为1)条件下修改后
                 int result=JOptionPane.showConfirmDialog(MainFrame.this, "是否保存更改到十组课设", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                 if(result==JOptionPane.OK_OPTION){
                     MainFrame.this.saveAs();
                 }else if(result==JOptionPane.NO_OPTION){
                     MainFrame.this.dispose();
                     MainFrame.this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                 }
             }else if(flag==2 && currentPath!=null){
                 //弹出窗口
                 //1、(刚启动记事本为0,刚新建文档为1)条件下修改后
                 int result=JOptionPane.showConfirmDialog(MainFrame.this, "是否将更改保存到十组课设"+currentPath+"?", "记事本", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
                 if(result==JOptionPane.OK_OPTION){
                     MainFrame.this.save();
                 }else if(result==JOptionPane.NO_OPTION){
                     MainFrame.this.dispose();
                     MainFrame.this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                 }
             }else{
                 //弹出窗口
                 int result=JOptionPane.showConfirmDialog(MainFrame.this, "确定关闭", "系统提示", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                 if(result==JOptionPane.OK_OPTION){
                     MainFrame.this.dispose();
                     MainFrame.this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                 }
             }
         }
     });
 }
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if(e.getSource()==iO){//打开
        openFile();
    }else if(e.getSource()==iS) {//保存
        save();
    }else if(e.getSource()==iSA) {//另存为
        saveAs();
    }else if(e.getSource()==iN) {//新建
        newFile();
    }else if(e.getSource()==iExit) {//退出
        exit();
    }else if(e.getSource()==iPe) {//页面设置
        PageFormat pFormat = new PageFormat();
        PrinterJob.getPrinterJob().pageDialog(pFormat);}
    else if(e.getSource()==iPt) {//打印
        Print();
    }else if(e.getSource()==iU ||e.getSource() == popM_Undo){//撤销
        if(undoMgr.canRedo()) {
            undoMgr.canRedo();
        }
    }else if(e.getSource() == iCut || e.getSource() == popM_Cut) {//复制
        cut();
    }else if(e.getSource()==iPe || e.getSource()==popM_Copy) {//粘贴
        paste();
    }else if(e.getSource()==iD || e.getSource()==popM_Delete) {//删除
        String temString = textArea.getText().toString();
        textArea.setText(temString.substring(0,textArea.getSelectionStart()));
    }else if(e.getSource()==iFnd) {//查找
        mySearch();
    }else if(e.getSource()==iFN) {//查找下一个
        mySearch();
    }else if(e.getSource()==iR) {//替换
        mySearch();
    }else if(e.getSource()==iSA || e.getSource()==popM_SelectAll) {//全选
        textArea.selectAll();
    }else if(e.getSource()==iT) {//时间
        textArea.append(hour+":"+min+":"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH));
    }else if(e.getSource()==iNL) {//自动换行
        if(iNL.isSelected()) {
            textArea.setLineWrap(true);
        }else {
            textArea.setLineWrap(false);
        }
    }else if(e.getSource()==iFont) {//字体大小
        MQFontChooser fontChooser = new MQFontChooser(textArea.getFont());//字体选择器
        fontChooser.showFontDialog(this);
        Font font = fontChooser.getSelectFont();
        textArea.setFont(font);//将字体设置到图形界面
    }else if(e.getSource()==iColor) {//背景颜色
        jcc1=new JColorChooser();
        JOptionPane.showMessageDialog(this, jcc1,"选择背景颜色",-1);
        color = jcc1.getColor();
        textArea.setBackground(color);
    }else if(e.getSource()==iFC) {//字体颜色
        color = jcc1.getColor();
        JOptionPane.showMessageDialog(this, jcc1,"选择字体颜色",-1);
        color = jcc1.getColor();
        textArea.setForeground(color);
    }else if(e.getSource()==iS) {//状态
        if(iS.isSelected()) {
            tS.setVisible(true);
        }else {
            tS.setVisible(false);
        }
    }else if(e.getSource()==iSFH) {
        JOptionPane.showMessageDialog(this, "打开浏览器,百度搜索","帮助",1);
    }else if(e.getSource()==iAN) {
        JOptionPane.showMessageDialog(this, "记事本 V2019【网络十组制作】","软件说明",1);
    }
}
private void turnTo() {
    final JDialog gotoDialog = new JDialog(this, "转到下列行");
    JLabel gotoLabel= new JLabel("行数(L):");
    final JTextField linenum = new JTextField(5);
    linenum.setText("1");
    linenum.selectAll();

    JButton okButton = new JButton("确定");
     okButton.addActionListener(new ActionListener() {
         
         public void actionPerformed(ActionEvent e) {
             int totalLine = textArea.getLineCount();
             int[] lineNumber = new int[totalLine + 1];
             String s = textArea.getText();
             int pos = 0, t = 0;

             while (true) {
                 pos = s.indexOf('\12', pos);
                 // System.out.println("引索pos:"+pos);
                 if (pos == -1)
                     break;
                 lineNumber[t++] = pos++;
             }

             int gt = 1;
             try {
                 gt = Integer.parseInt(linenum.getText());
             } catch (NumberFormatException efe) {
                 JOptionPane.showMessageDialog(null, "请输入行数!", "提示", JOptionPane.WARNING_MESSAGE);
                 linenum.requestFocus(true);
                 return;
             }

             if (gt < 2 || gt >= totalLine) {
                 if (gt < 2)
                     textArea.setCaretPosition(0);
                 else
                     textArea.setCaretPosition(s.length());
             } else
                 textArea.setCaretPosition(lineNumber[gt - 2] + 1);

             gotoDialog.dispose();
         }

     });

     JButton cancelButton = new JButton("取消");
     cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             gotoDialog.dispose();
         }
     });

     Container con = gotoDialog.getContentPane();
     con.setLayout(new FlowLayout());
     con.add(gotoLabel);
     con.add(linenum);
     con.add(okButton);
     con.add(cancelButton);

     gotoDialog.setSize(200, 100);
     gotoDialog.setResizable(true);
     gotoDialog.setLocation(300, 280);
     gotoDialog.setVisible(true);

 }
private void exit() {
    
    if(flag==2&& currentPath==null) {
        int result = JOptionPane.showConfirmDialog(MainFrame.this,"是否更改保存到十组课设?","记事本" ,JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
        if(result == JOptionPane.OK_CANCEL_OPTION) {
            MainFrame.this.saveAs();
        }else if(result ==JOptionPane.NO_OPTION) {
            MainFrame.this.dispose();
            MainFrame.this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
    }else {
            int result =JOptionPane.showConfirmDialog(MainFrame.this, "确定关闭?","系统提示",JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
            if(result == JOptionPane.OK_OPTION) {
                MainFrame.this.dispose();
                MainFrame.this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            }
        }
    }

    private void newFile() {
        if(flag ==0 || flag ==1) {
            return;
        }else if(flag ==2 && this.currentPath ==null) {//修改后
            int result = JOptionPane.showConfirmDialog(MainFrame.this, "是否更改保存到十组课设?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
            if(result == JOptionPane.OK_OPTION) {
                this.saveAs();//另存为
            }else if(result == JOptionPane.NO_OPTION) {
                this.textArea.setText("十组课设");
                flag=1;
            }
            return;
        }else if(flag == 2 && this.currentPath != null) {
            int result = JOptionPane.showConfirmDialog(MainFrame.this,"是否更改保存到"+this.currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE );
            if(result == JOptionPane.OK_CANCEL_OPTION) {
                this.textArea.setText("");
                this.setTitle("十组课设");
                flag = 1;
            }
        }else if(flag == 3) {//保存的文件
            this.textArea.setText("十组课设");
        }
    }
    
    private void saveAs() {//打开保存框
        JFileChooser chooser = new JFileChooser();//选择文件
        int result = chooser.showSaveDialog(this);
        if(result == JFileChooser.APPROVE_OPTION) {//生成的文件
            File file = chooser.getSelectedFile();
            FileWriter fileWriter = null;
            //保存
            try {
                fileWriter=new FileWriter(file);
                fileWriter.write(textArea.getText());
                currentFileName=file.getName();
                currentPath=file.getAbsolutePath();
                fileWriter.flush();
                this.flag=3;
                this.setTitle(currentPath);
            } catch (IOException e1) {
                e1.printStackTrace();
            }finally{
                try {
                    if(fileWriter!=null) fileWriter.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }   
    }
     private void save()
     {
            if(this.currentPath==null)
            {
                this.saveAs();
                if(this.currentPath==null)
                {
                    return;
                }
            }
            FileWriter fileWriter=null;
            //保存
            try 
            {
                fileWriter=new FileWriter(new  File(currentPath));
                fileWriter.write(textArea.getText());
                fileWriter.flush();
                flag=3;
                this.setTitle(this.currentPath);
            } catch (IOException e1) 
            {
                e1.printStackTrace();
            }finally
            {
                try 
                {
                    if(fileWriter!=null) fileWriter.close();
                } catch (IOException e1) 
                {
                    e1.printStackTrace();
                }
            }
     }
     private void openFile() {
         if(flag == 2 && this.currentPath == null) {
             int result = JOptionPane.showConfirmDialog(MainFrame.this, "是否更改保存到十组课设?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
             if(result == JOptionPane.OK_CANCEL_OPTION) {
                 this.saveAs();
             }
         }else if(flag == 2 && this.currentPath !=null) {
             int result = JOptionPane.showConfirmDialog(MainFrame.this,"是否保存更改到"+this.currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
             if(result == JOptionPane.OK_CANCEL_OPTION) {
                 this.save();
             }
         }
         JFileChooser chooser = new JFileChooser();//选择文件
         int result = chooser.showOpenDialog(this);
         if(result == JFileChooser.APPROVE_OPTION) {//获得选取的文件
             File file = chooser.getSelectedFile();//打开已经保存过的文件,并提前保存文件名
             currentFileName = file.getAbsolutePath();
             flag = 3;
             this.setTitle(this.currentPath);
             BufferedReader bReader =null;
             try {
                    //建立文件流(字符流)
                    InputStreamReader isr=new InputStreamReader(new FileInputStream(file),"GBK");
                    bReader=new BufferedReader(isr);//动态绑定
                    //读取内容
                    StringBuffer sb=new StringBuffer();
                    String line=null;
                    while((line=bReader.readLine())!=null){
                        sb.append(line+SystemParam.LINE_SEPARATOR);
                    }
                    //显示在文本框(多框)
                    textArea.setText(sb.toString());
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally{
                    try {
                        if(bReader!=null) bReader.close();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
         }
     }
     public void Print() {
         try{
                p = getToolkit().getPrintJob(this,"ok",null);
                g = p.getGraphics();//p 获取一个用于打印的 Graphics 的对象
                this.textArea.printAll(g);
                p.end();//释放对象 g  
            }
         catch(Exception a){
             
            } 
        }
        
        
        private static void addPopup(Component component, final JPopupMenu popup) {
            component.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        showMenu(e);
                    }
                }
                public void mouseReleased(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        showMenu(e);
                    }
                }
                private void showMenu(MouseEvent e) {
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            });
        }
        
        public void cut(){
            copy();
            //标记开始位置
            int start = this.textArea.getSelectionStart();
            //标记结束位置
            int end = this.textArea.getSelectionEnd();
            //删除所选段
            this.textArea.replaceRange("", start, end);
            
        }
        
        public void copy(){
            //拖动选取文本
            String temp = this.textArea.getSelectedText();
            //把获取的内容复制到连续字符器,这个类继承了剪贴板接口
            StringSelection text = new StringSelection(temp);
            //把内容放在剪贴板
            this.clipboard.setContents(text, null);
        }
        
         public void paste(){
             //Transferable接口,把剪贴板的内容转换成数据
             Transferable contents = this.clipboard.getContents(this);
             //DataFalvor类判断是否能把剪贴板的内容转换成所需数据类型
             DataFlavor flavor = DataFlavor.stringFlavor;
             //如果可以转换
             if(contents.isDataFlavorSupported(flavor)){
                 String str;
                 try {//开始转换
                    str=(String)contents.getTransferData(flavor);
                    //如果要粘贴时,鼠标已经选中了一些字符
                    if(this.textArea.getSelectedText()!=null){
                        //定位被选中字符的开始位置
                        int start = this.textArea.getSelectionStart();
                        //定位被选中字符的末尾位置
                        int end = this.textArea.getSelectionEnd();
                        //把粘贴的内容替换成被选中的内容
                        this.textArea.replaceRange(str, start, end);
                    }else{
                        //获取鼠标所在TextArea的位置
                        int mouse = this.textArea.getCaretPosition();
                        //在鼠标所在的位置粘贴内容
                        this.textArea.insert(str, mouse);
                    }
                 } catch(UnsupportedFlavorException e) {
                    e.printStackTrace();
                 } catch (IOException e) {
                    e.printStackTrace();
                 } catch(IllegalArgumentException e){
                    e.printStackTrace();
                 }
             }
         }
         
        public void mySearch() {
            final JDialog findDialog = new JDialog(this, "查找与替换", true);
            Container con = findDialog.getContentPane();
            con.setLayout(new FlowLayout(FlowLayout.LEFT));
            JLabel searchContentLabel = new JLabel("查找内容(N) :");
            JLabel replaceContentLabel = new JLabel("替换为(P)  :");
            final JTextField findText = new JTextField(22);
            final JTextField replaceText = new JTextField(22);
            final JCheckBox matchcase = new JCheckBox("区分大小写");
            ButtonGroup bGroup = new ButtonGroup();
            final JRadioButton up = new JRadioButton("向上(U)");
            final JRadioButton down = new JRadioButton("向下(D)");
            down.setSelected(true);
            bGroup.add(up);
            bGroup.add(down);
            JButton searchNext = new JButton("查找下一个(F)");
            JButton replace = new JButton("替换(R)");
            final JButton replaceAll = new JButton("全部替换(A)");
            searchNext.setPreferredSize(new Dimension(110, 22));
            replace.setPreferredSize(new Dimension(110, 22));
            replaceAll.setPreferredSize(new Dimension(110, 22));
            // "替换"按钮的事件处理
            replace.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
     
                    if (replaceText.getText().length() == 0 && textArea.getSelectedText() != null)
                        textArea.replaceSelection("");
                    if (replaceText.getText().length() > 0 && textArea.getSelectedText() != null)
                        textArea.replaceSelection(replaceText.getText());
                }
            });
     
            // "替换全部"按钮的事件处理
            replaceAll.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
     
                    textArea.setCaretPosition(0); // 将光标放到编辑区开头
                    int a = 0, b = 0, replaceCount = 0;
     
                    if (findText.getText().length() == 0) {
                        JOptionPane.showMessageDialog(findDialog, "请填写查找内容!", "提示", JOptionPane.WARNING_MESSAGE);
                        findText.requestFocus(true);
                        return;
                    }
                    while (a > -1) {
     
                        int FindStartPos = textArea.getCaretPosition();
                        String str1, str2, str3, str4, strA, strB;
                        str1 = textArea.getText();
                        str2 = str1.toLowerCase();
                        str3 = findText.getText();
                        str4 = str3.toLowerCase();
     
                        if (matchcase.isSelected()) {
                            strA = str1;
                            strB = str3;
                        } else {
                            strA = str2;
                            strB = str4;
                        }
     
                        if (up.isSelected()) {
                            if (textArea.getSelectedText() == null) {
                                a = strA.lastIndexOf(strB, FindStartPos - 1);
                            } else {
                                a = strA.lastIndexOf(strB, FindStartPos - findText.getText().length() - 1);
                            }
                        } else if (down.isSelected()) {
                            if (textArea.getSelectedText() == null) {
                                a = strA.indexOf(strB, FindStartPos);
                            } else {
                                a = strA.indexOf(strB, FindStartPos - findText.getText().length() + 1);
                            }
     
                        }
     
                        if (a > -1) {
                            if (up.isSelected()) {
                                textArea.setCaretPosition(a);
                                b = findText.getText().length();
                                textArea.select(a, a + b);
                            } else if (down.isSelected()) {
                                textArea.setCaretPosition(a);
                                b = findText.getText().length();
                                textArea.select(a, a + b);
                            }
                        } else {
                            if (replaceCount == 0) {
                                JOptionPane.showMessageDialog(findDialog, "找不到您查找的内容!", "记事本", JOptionPane.INFORMATION_MESSAGE);
                            } else {
                                JOptionPane.showMessageDialog(findDialog, "成功替换" + replaceCount + "个匹配内容!", "替换成功", JOptionPane.INFORMATION_MESSAGE);
                            }
                        }
                        if (replaceText.getText().length() == 0 && textArea.getSelectedText() != null) {
                            textArea.replaceSelection("");
                            replaceCount++;
                        }
                        if (replaceText.getText().length() > 0 && textArea.getSelectedText() != null) {
                            textArea.replaceSelection(replaceText.getText());
                            replaceCount++;
                        }
                    }// end while
                }
            }); /* "替换全部"按钮的事件处理结束 */
     
            // "查找下一个"按钮事件处理
            searchNext.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) {
                    int a = 0, b = 0;
                    int FindStartPos = textArea.getCaretPosition();
                    String str1, str2, str3, str4, strA, strB;
                    str1 = textArea.getText();
                    str2 = str1.toLowerCase();
                    str3 = findText.getText();
                    str4 = str3.toLowerCase();
                    // "区分大小写"的CheckBox被选中
                    if (matchcase.isSelected()) {
                        strA = str1;
                        strB = str3;
                    } else {
                        strA = str2;
                        strB = str4;
                    }
     
                    if (up.isSelected()) {
                        if (textArea.getSelectedText() == null) {
                            a = strA.lastIndexOf(strB, FindStartPos - 1);
                        } else {
                            a = strA.lastIndexOf(strB, FindStartPos - findText.getText().length() - 1);
                        }
                    } else if (down.isSelected()) {
                        if (textArea.getSelectedText() == null) {
                            a = strA.indexOf(strB, FindStartPos);
                        } else {
                            a = strA.indexOf(strB, FindStartPos - findText.getText().length() + 1);
                        }
     
                    }
                    if (a > -1) {
                        if (up.isSelected()) {
                            textArea.setCaretPosition(a);
                            b = findText.getText().length();
                            textArea.select(a, a + b);
                        } else if (down.isSelected()) {
                            textArea.setCaretPosition(a);
                            b = findText.getText().length();
                            textArea.select(a, a + b);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本", JOptionPane.INFORMATION_MESSAGE);
                    }
     
                }
            });/* "查找下一个"按钮事件处理结束 */
            // "取消"按钮及事件处理
            JButton cancel = new JButton("取消");
            cancel.setPreferredSize(new Dimension(110, 22));
            cancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    findDialog.dispose();
                }
            });
     
            // 创建"查找与替换"对话框的界面
            JPanel bottomPanel = new JPanel();
            JPanel centerPanel = new JPanel();
            JPanel topPanel = new JPanel();
     
            JPanel direction = new JPanel();
            direction.setBorder(BorderFactory.createTitledBorder("方向 "));
            direction.add(up);
            direction.add(down);
            direction.setPreferredSize(new Dimension(170, 60));
            JPanel replacePanel = new JPanel();
            replacePanel.setLayout(new GridLayout(2, 1));
            replacePanel.add(replace);
            replacePanel.add(replaceAll);
     
            topPanel.add(searchContentLabel);
            topPanel.add(findText);
            topPanel.add(searchNext);
            centerPanel.add(replaceContentLabel);
            centerPanel.add(replaceText);
            centerPanel.add(replacePanel);
            bottomPanel.add(matchcase);
            bottomPanel.add(direction);
            bottomPanel.add(cancel);
     
            con.add(topPanel);
            con.add(centerPanel);
            con.add(bottomPanel);
     
            // 设置"查找与替换"对话框的大小、可更改大小(否)、位置和可见性
            findDialog.setSize(410, 210);
            findDialog.setResizable(true);
            findDialog.setLocation(230, 280);
            findDialog.setVisible(true);
        }
     
    }

MQFontChooser

package p1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.print.attribute.AttributeSet;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class MQFontChooser extends JDialog{
public static final double CANCEL_OPTION = 0;//选择取消按钮的返回值
public static final double APPROVE_OPTION = 1;//选择确定按钮的返回值
private static final String CHINA_STRING = " 请输入文字 ";//中文预览的字符串
private static final String ENGLISH_STRING =" write down please ";//英文预览字符串
private static final String NUMBER_STRING = " 1234 ";//数字预览的字符串
private Font font = null;//预设字体
private Box box =null;//字体选择器组件容器
private JTextField fontText = null;//字体样式文本框
private JTextField styleText = null;//样式文本框
private JTextField sizeText = null;//文字大小文本框
private JTextField previewText = null;//预览文本框
private JRadioButton chinaButton = null;//中文预览
private JRadioButton englishButton = null;//英文预览
private JRadioButton numberButton = null;//数字预览
private JList fontList = null;//字体选择框
private JList styleList = null;//样式选择框
private JList sizeList = null;//文字大小选择框
private JButton approveButton = null;//确定按钮
private JButton cancelButton = null;//取消字体
private String [] fontArray = null;//所有字体
private String [] styleArray = {"常规","加粗","斜体","斜体加粗"};//预设样式
private String [] sizeArray = {"初号","小初","一号","小一","二号","小二","三号","小三","四号","小四","五号","小五","六号","小六","七号","八号","5","5.5","6.5","7.5","8","9","10","10.5","11","12","14","16","18","20","22","24","26","28","36","48","72"};//字体大小
private double [] sizeintArray = {42,36,26,24,22,18,16,15,14,12,10,9,8,7,6,5,5,5.5,6.5,7.5,8,9,10,10.5,11,12,14,16,18,20,22,24,26,28,36,48,72};//对应上面数组中的字体大小
private double returnValue = CANCEL_OPTION;//构造字体选择器
public MQFontChooser() {
this(new Font("宋体",Font.PLAIN,12));
}
public MQFontChooser(Font font) {
setTitle("文字选择器");
this.font = font;
init();//初始化UI组件
addListener();//添加监听器
setup();//按照预设字体显示
setModal(true);//基本设置
setResizable(false);//自动适应大小
pack();
}
private void init() {
GraphicsEnvironment eqEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();//获得系统字体
fontArray = eqEnvironment.getAvailableFontFamilyNames();
box = Box.createVerticalBox();//主容器
box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
fontText = new JTextField();
fontText.setEditable(false);
fontText.setBackground(Color.WHITE);
styleText = new JTextField();
styleText.setEditable(false);
styleText.setBackground(Color.WHITE);
sizeText = new JTextField("12");
// 给文字大小文本框使用的Document文档,制定了一些输入字符的规则
Document doc = new PlainDocument(){
public void insertString(int offs, String str, javax.swing.text.AttributeSet a) throws BadLocationException {
if (str == null) {
return;
}
if (getLength() >= 3) {
return;
}
if (!str.matches("[0-9]+") && !str.equals("初号") && !str.equals("小初") && !str.equals("一号") && !str.equals("小一") && !str.equals("二号") && !str.equals("小二") && !str.equals("三号") && !str.equals("小三") && !str.equals("四号") && !str.equals("小四") && !str.equals("五号") && !str.equals("小五") && !str.equals("六号") && !str.equals("小六") && !str.equals("七号") && !str.equals("八号")) {
return;
}
super.insertString(offs, str, a);
sizeList.setSelectedValue(sizeText.getText(), true);
}
};

    sizeText.setDocument(doc);
    previewText = new JTextField(20);
    previewText.setHorizontalAlignment(JTextField.CENTER);
    previewText.setEditable(false);
    previewText.setBackground(Color.WHITE);
    chinaButton = new JRadioButton("中文预览", true);
    englishButton = new JRadioButton("英文预览");
    numberButton = new JRadioButton("数字预览");
    ButtonGroup bg = new ButtonGroup();
    bg.add(chinaButton);
    bg.add(englishButton);
    bg.add(numberButton);
    fontList = new JList(fontArray);
    styleList = new JList(styleArray);
    sizeList = new JList(sizeArray);
    approveButton = new JButton("确定");
    cancelButton = new JButton("取消");
    Box box1 = Box.createHorizontalBox();
    JLabel l1 = new JLabel("字体:");
    JLabel l2 = new JLabel("字形:");
    JLabel l3 = new JLabel("大小:");
    l1.setPreferredSize(new Dimension(165, 14));
    l1.setMaximumSize(new Dimension(165, 14));
    l1.setMinimumSize(new Dimension(165, 14));
    l2.setPreferredSize(new Dimension(95, 14));
    l2.setMaximumSize(new Dimension(95, 14));
    l2.setMinimumSize(new Dimension(95, 14));
    l3.setPreferredSize(new Dimension(80, 14));
    l3.setMaximumSize(new Dimension(80, 14));
    l3.setMinimumSize(new Dimension(80, 14));
    box1.add(l1);
    box1.add(l2);
    box1.add(l3);
    Box box2 = Box.createHorizontalBox();
    fontText.setPreferredSize(new Dimension(160, 20));
    fontText.setMaximumSize(new Dimension(160, 20));
    fontText.setMinimumSize(new Dimension(160, 20));
    box2.add(fontText);
    box2.add(Box.createHorizontalStrut(5));
    styleText.setPreferredSize(new Dimension(90, 20));
    styleText.setMaximumSize(new Dimension(90, 20));
    styleText.setMinimumSize(new Dimension(90, 20));
    box2.add(styleText);
    box2.add(Box.createHorizontalStrut(5));
    sizeText.setPreferredSize(new Dimension(80, 20));
    sizeText.setMaximumSize(new Dimension(80, 20));
    sizeText.setMinimumSize(new Dimension(80, 20));
    box2.add(sizeText);
    Box box3 = Box.createHorizontalBox();
    JScrollPane sp1 = new JScrollPane(fontList);
    sp1.setPreferredSize(new Dimension(160, 100));
    sp1.setMaximumSize(new Dimension(160, 100));
    sp1.setMaximumSize(new Dimension(160, 100));
    box3.add(sp1);
    box3.add(Box.createHorizontalStrut(5));
    JScrollPane sp2 = new JScrollPane(styleList);
    sp2.setPreferredSize(new Dimension(90, 100));
    sp2.setMaximumSize(new Dimension(90, 100));
    sp2.setMinimumSize(new Dimension(90, 100));
    box3.add(sp2);
    box3.add(Box.createHorizontalStrut(5));
    JScrollPane sp3 = new JScrollPane(sizeList);
    sp3.setPreferredSize(new Dimension(80, 100));
    sp3.setMaximumSize(new Dimension(80, 100));
    sp3.setMinimumSize(new Dimension(80, 100));
    box3.add(sp3);
    Box box4 = Box.createHorizontalBox();
    Box box5 = Box.createVerticalBox();
    JPanel box6 = new JPanel(new BorderLayout());
    box5.setBorder(BorderFactory.createTitledBorder("字符集"));
    box6.setBorder(BorderFactory.createTitledBorder("示例"));
    box5.add(chinaButton);
    box5.add(englishButton);
    box5.add(numberButton);
    box5.setPreferredSize(new Dimension(90, 95));
    box5.setMaximumSize(new Dimension(90, 95));
    box5.setMinimumSize(new Dimension(90, 95));
    box6.add(previewText);
    box6.setPreferredSize(new Dimension(250, 95));
    box6.setMaximumSize(new Dimension(250, 95));
    box6.setMinimumSize(new Dimension(250, 95));
    box4.add(box5);
    box4.add(Box.createHorizontalStrut(4));
    box4.add(box6);
    Box box7 = Box.createHorizontalBox();
    box7.add(Box.createHorizontalGlue());
    box7.add(approveButton);
    box7.add(Box.createHorizontalStrut(5));
    box7.add(cancelButton);
    box.add(box1);
    box.add(box2);
    box.add(box3);
    box.add(Box.createVerticalStrut(5));
    box.add(box4);
    box.add(Box.createVerticalStrut(5));
    box.add(box7);
    getContentPane().add(box);
}
/**
 * 按照预设字体显示
 */
private void setup() {
    String fontName = font.getFamily();
    int fontStyle = font.getStyle();
    int fontSize = font.getSize();
    /*
     * 如果预设的文字大小在选择列表中,则通过选择该列表中的某项进行设值,否则直接将预设文字大小写入文本框
     */
    boolean b = false;
    for (int i = 0; i < sizeArray.length; i++) {
        if (sizeArray[i].equals(String.valueOf(fontSize))) {
            b = true;
            break;
        }
    }
    if(b){
        // 选择文字大小列表中的某项
        sizeList.setSelectedValue(String.valueOf(fontSize), true);
    }else{
        sizeText.setText(String.valueOf(fontSize));
    }
    // 选择字体列表中的某项
    fontList.setSelectedValue(fontName, true);
    // 选择样式列表中的某项
    styleList.setSelectedIndex(fontStyle);
    // 预览默认显示中文字符
    chinaButton.doClick();
    // 显示预览
    setPreview();
}
/**
 * 添加所需的事件监听器
 */
private void addListener() {
    sizeText.addFocusListener(new FocusListener() {
        public void focusLost(FocusEvent e) {
            setPreview();
        }
        public void focusGained(FocusEvent e) {
            sizeText.selectAll();
        }
    });
    // 字体列表发生选择事件的监听器
    fontList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                fontText.setText(String.valueOf(fontList.getSelectedValue()));
                // 设置预览
                setPreview();
            }
        }
    });
    styleList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                styleText.setText(String.valueOf(styleList.getSelectedValue()));
                // 设置预览
                setPreview();
            }
        }
    });
    sizeList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if(!sizeText.isFocusOwner()){
                    sizeText.setText(String.valueOf(sizeList.getSelectedValue()));
                }
                // 设置预览
                setPreview();
            }
        }
    });
    // 编码监听器
    EncodeAction ea = new EncodeAction();
    chinaButton.addActionListener(ea);
    englishButton.addActionListener(ea);
    numberButton.addActionListener(ea);
    // 确定按钮的事件监听
    approveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 组合字体
            font = groupFont();
            // 设置返回值
            returnValue = APPROVE_OPTION;
            // 关闭窗口
            disposeDialog();
        }
    });
    // 取消按钮事件监听
    cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            disposeDialog();
        }
    });
}
/**
 * 显示字体选择器
 * @param owner 上层所有者
 * @return 该整形返回值表示用户点击了字体选择器的确定按钮或取消按钮,参考本类常量字段APPROVE_OPTION和CANCEL_OPTION
 */
public final double showFontDialog(JFrame owner) {
    setLocationRelativeTo(owner);
    setVisible(true);
    return returnValue;
}
/**
 * 返回选择的字体对象
 * @return 字体对象
 */
public final Font getSelectFont() {
    return font;
}
/**
 * 关闭窗口
 */
private void disposeDialog() {
    MQFontChooser.this.removeAll();
    MQFontChooser.this.dispose();
}

/**
 * 显示错误消息
 * @param errorMessage 错误消息
 */
private void showErrorDialog(String errorMessage) {
    JOptionPane.showMessageDialog(this, errorMessage, "错误", JOptionPane.ERROR_MESSAGE);
}
/**
 * 设置预览
 */
private void setPreview() {
    Font f = groupFont();
    previewText.setFont(f);
}
/**
 * 按照选择组合字体
 * @return 字体
 */
private Font groupFont() {
    String fontName = fontText.getText();
    double fontStyle = styleList.getSelectedIndex();
    String sizeStr = sizeText.getText().trim();
    // 如果没有输入
    if(sizeStr.length() == 0) {
        showErrorDialog("字体(大小)必须是有效“数值!");
        return null;
    }
    double fontSize = 0;
    // 通过循环对比文字大小输入是否在现有列表内
    for (int i = 0; i < sizeArray.length; i++) {
        if(sizeStr.equals(sizeArray[i])){
            fontSize = sizeintArray[i];
            break;
        }
    }
    // 没有在列表内
    if (fontSize == 0) {
        try{
            fontSize = Integer.parseInt(sizeStr);
            if(fontSize < 1){
                showErrorDialog("字体(大小)必须是有效“数值”!");
                return null;
            }
        }catch (NumberFormatException nfe) {
            showErrorDialog("字体(大小)必须是有效“数值”!");
            return null;
        }
    }
    return new Font(font.getFamily(),font.getStyle(),font.getSize());
}

/**
 * 编码选择事件的监听动作
 *
 */
class EncodeAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(chinaButton)) {
            previewText.setText(CHINA_STRING);
        } else if (e.getSource().equals(englishButton)) {
            previewText.setText(ENGLISH_STRING);
        } else {
            previewText.setText(NUMBER_STRING);
        }
    }
}

}

SystemParam

package p1;

public class SystemParam{
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
}

TestLine

package p1;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class TestLine extends javax.swing.JComponent{
private final Font DEFAULT_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 13);
public final Color DEFAULT_BACKGROUD = new Color(228,228,228);
public final Color DEFAULT_FOREGROUD = Color.red;
public final int nHEIGHT = Integer.MAX_VALUE - 1000000;
public final int MARGIN = 5;
private int lineHeight;
private int fontLineHeight;
private int currentRowWidth;
private FontMetrics fontMetrics;

public TestLine() {
    setFont(DEFAULT_FONT);
    setForeground(DEFAULT_FOREGROUD);
    setBackground(DEFAULT_BACKGROUD);
    setPreferredSize(999999);
}
public void setPreferredSize(int row) {
    int width = fontMetrics.stringWidth(String.valueOf(row));
    if(currentRowWidth < width) {
        currentRowWidth = width;
        setPreferredSize(new Dimension(2*MARGIN + width +1,nHEIGHT));
    }
}
@Override
public void setFont(Font font) {
    super.setFont(font);
    fontMetrics = getFontMetrics(getFont());
    fontLineHeight = fontMetrics.getHeight();
}
public int getLineHeight() {
    if(lineHeight ==0) {
        return fontLineHeight;
    }
    return lineHeight;
}
public void setLineHeight(int lineHeight) {
    if(lineHeight > 0) {
        this.lineHeight = lineHeight;
    }
}
public int getStartOffset() {
    return 4;
}
@Override
protected void paintComponent(Graphics g) {
    int nlineHeight = getLineHeight();
    int startOffset = getStartOffset();
    Rectangle drawHere = g.getClipBounds();
    g.setColor(getBackground());
    g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
    g.setColor(getForeground());
    int startLineNum = (drawHere.y/nlineHeight)+1;
    int endLineNum = startLineNum + (drawHere.height/nlineHeight);
    int start = (drawHere.y/nlineHeight)*nlineHeight+nlineHeight-startOffset;
    for(int i = startLineNum;i<=endLineNum;++i) {
        String lineNum = String.valueOf(i);
        int width = fontMetrics.stringWidth(lineNum);
        g.drawString(lineNum +" ", MARGIN + currentRowWidth-width-1, start);
        start +=nlineHeight;
    }
    setPreferredSize(endLineNum);
}

}

你可能感兴趣的:(text)