JAVA——Swing应用编写简单的记事本——源代码分析实战(二)

当将基本的框架搭建完成之后,只是界面上存在了各种菜单和菜单选项,只能看不能用(PS 最后面有源码的下载地址哦)

(1)接下来就是将每个菜单下的菜单选项的功能实现,比如


从上图中可以看出,在“文件”这个菜单下面有“新建”、“打开”等菜单的选项,这些选项的功能怎么实现呢,主要是通过对这些菜单选项添加事件监听来实现,当监听到该菜单选项的事件发生时,选择相应的动作,

例如,我在添加“新建”菜单选项时,添加了事件监听

fileNew = new JMenuItem("新建(N)");  //新建菜单项
fileNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
fileNew.addActionListener(this);  //添加事件监听
fileMenu.add(fileNew);   //添加菜单项然后

监听到事件发生时执行

public void actionPerformed(ActionEvent e) {  
//***********************************文件菜单栏功能************************************//
		//新建文本功能
    String currentText = editArea.getText();   //获取当前文本中的内容
    boolean isTextChange = (currentText.equals(oldText))?true:false;;   //用来判断文本内容是否发生变化
	if(e.getSource() == fileNew) {
	    if(!isTextChange) {    //文本内容发生变化
	        int saveChoose = JOptionPane.showConfirmDialog(this,"文件尚未保存,是否保存?", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
      	            if(saveChoose == JOptionPane.YES_OPTION) {
			saveAs();
	              }
                    else if(saveChoose == JOptionPane.NO_OPTION) {
			fileNew();   //新建文本
			//return;
		    }
		    else {
			statusLabel2.setText("未选择保存任何文件");
			return;
			}	
		}
	else {
	    fileNew();
	}
}
public void fileNew() {
	editArea.replaceRange("", 0, editArea.getText().length());
	statusLabel2.setText("新建文件");
	this.setTitle("无标题");
	isNewFile = true;
	undo.discardAllEdits();  //撤销所有的操作
	editUndo.setEnabled(false);
	oldText = editArea.getText();
}

这样就完成了文件菜单中“新建”功能的实现

其余的功能的实现基本上是相同的重复。

注意在“打开”文件的时候要对文件进行过滤,对文件名称不合法的过滤,

if(fileName == null || fileName.getName().equals("")) {  //文件名不合法
			JOptionPane.showConfirmDialog(this, "不合法的文件名", "不合法的文件名", JOptionPane.ERROR_MESSAGE);
		}

对文件格式不合法的文件过滤

 private void setFileFilter() {
	        // TODO Auto-generated method stub
    javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() {
     @Override
    public String getDescription() {
	return ".txt";
     }
     @Override
    public boolean accept(File f) {
         String name = f.getName();
         return f.isDirectory() || name.toLowerCase().endsWith(".txt"); // 仅显示目录和txt文件
        }
    };
     JFileChooser fileChooser = new JFileChooser();
     fileChooser.addChoosableFileFilter(filter);
     fileChooser.setFileFilter(filter);

主要是借助FileFiter实现对其余文件格式的过滤,要是设置文件过滤器的话,其余格式的文件也能打开,但是打开后的内容是乱码的。

其余的菜单选项的功能就是基本上是重复的,但是有些功能比较难实现,就是打印,还有页面设置,

关于打印功能的实现

public void print(){  
        try{  
            p = getToolkit().getPrintJob(this,"ok",null);//创建一个Printfjob 对象 p  
            g = p.getGraphics();//p 获取一个用于打印的 Graphics 的对象  
            //g.translate(120,200);//改变组建的位置   
            this.editArea.printAll(g);  
            p.end();//释放对象 g    
        }  
        catch(Exception a){  
         
        }   
	  }  

还有比较坑的页面设置的功能的实现,百度到的方法,两行解决问题

PageFormat pf = new PageFormat();  
PrinterJob.getPrinterJob().pageDialog(pf);
PageFormat这个类在java.awt.print下的。可以自己查一下API看一下

关于转到功能,这个功能其实就是转到文本中的某一行,就是获取文本编辑区的行数和你输入的行数,然后转到对应的位置

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 = editArea.getLineCount();  
                int[] lineNumber = new int[totalLine + 1];  
                String s = editArea.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)  
                        editArea.setCaretPosition(0);  
                    else  
                        editArea.setCaretPosition(s.length());  
                } else  
                    editArea.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, 110);  
        gotoDialog.setResizable(false);  
        gotoDialog.setLocation(300, 280);  
        gotoDialog.setVisible(true);  
    }  

(2)当菜单栏的功能实现之后需要对文本编辑区的功能进行设置,文本编辑区就是写文字的地方啦~


当右键时会弹出窗口有菜单选项,这个与之前菜单栏的实现就不太一样,因为要弹出,

public void initTextEditArea() {
		//创建文本编辑区
		editArea = new JTextArea(20,50);  //20列50行的文本区
		//初始化滚动条
		JScrollPane scroller = new JScrollPane(editArea);
		scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		this.add(scroller,BorderLayout.CENTER);    //在窗口中添加文本编辑区
		editArea.setWrapStyleWord(true);  //文字长度超过一行时自动换行
		editArea.setLineWrap(true);  //文本编辑区默认自动换行
		oldText = editArea.getText();   //获取文本编辑区的内容
		//撤销动作添加事件监听
		editArea.getDocument().addUndoableEditListener(undoHandler);
		editArea.getDocument().addDocumentListener(this);
		
		//创建右键弹出菜单
		popupMenu = new JPopupMenu();
		
		popupMenuUndo = new JMenuItem("撤销(U)");
		popupMenuUndo.addActionListener(this);
		popupMenuUndo.setEnabled(false);   
		popupMenu.add(popupMenuUndo);
		popupMenu.addSeparator();
		
		popupMenuCut = new JMenuItem("剪切(T)");
		popupMenuCut.addActionListener(this);
		popupMenu.add(popupMenuCut);
		
		popupMenuCopy = new JMenuItem("复制(C)");
		popupMenuCopy.addActionListener(this);
		popupMenu.add(popupMenuCopy);
		
		popupMenuPaste = new JMenuItem("粘贴(P)");
		popupMenuPaste.addActionListener(this);
		popupMenu.add(popupMenuPaste);
		
		popupMenuDelete = new JMenuItem("删除(D)");
		popupMenuDelete.addActionListener(this);
		popupMenu.add(popupMenuDelete);
		popupMenu.addSeparator();
		
		popupMenuSelectAll = new JMenuItem("全选(A)");
		popupMenuSelectAll.addActionListener(this);
		popupMenu.add(popupMenuSelectAll);
		
		//文本编辑区注册鼠标右键事件  //mouse必须写两遍,因为点击释放两个状态
		editArea.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if(e.isPopupTrigger()) {    //判断是否是编辑区触发的鼠标右键事件,弹出菜单触发器
					popupMenu.show(e.getComponent(), e.getX(), e.getY());  //在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单
				}
				checkMenuItemEnabled();   //设置菜单功能的可用性    
				editArea.requestFocus();  //编辑区获取焦点
			}
			public void mouseReleased(MouseEvent e) {
				if(e.isPopupTrigger()) {    //判断是否是编辑区触发的鼠标右键事件,弹出菜单触发器
					popupMenu.show(e.getComponent(), e.getX(), e.getY());  //在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单
				}
				checkMenuItemEnabled();   //设置菜单功能的可用性    
				editArea.requestFocus();  //编辑区获取焦点
			}
		});
		//component.setComponentPopupMenu(popupMenu);
		
		//创建和添加状态栏
		JPanel panel1 = new JPanel();
		statusLabel1 = new JLabel("");
		statusLabel2 = new JLabel("文件状态");
		
		panel1.add(statusLabel1);
		panel1.add(statusLabel2);  
		
		this.add(panel1, BorderLayout.SOUTH);//向窗口添加状态栏标签  
		
		//添加窗口监听器
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				exitWindowChoose();
			}
		});
		
		checkMenuItemEnabled();
		editArea.requestFocus();
		
		
	}
	

其实就是先添加借助popupMenu实现弹出菜单并添加鼠标右键监听事件,然后利用JMenuItem添加菜单选项

然后注意的细节就是当没有输入文字的时候,有些菜单选项的功能是不可用的,这个就需要一开始时进行设置

//设置菜单项的可用性
	public void checkMenuItemEnabled() {
		//复制粘贴删除功能
		String selectText = editArea.getSelectedText();
		if(selectText == null) {
			editCut.setEnabled(false);
			editCopy.setEnabled(false);
			editDelete.setEnabled(false);
			
			popupMenuCopy.setEnabled(false);
			popupMenuCut.setEnabled(false);
			popupMenuDelete.setEnabled(false);
		}
		else {
			editCut.setEnabled(true);
			editCopy.setEnabled(true);
			editDelete.setEnabled(true);
			
			popupMenuCopy.setEnabled(true);
			popupMenuCut.setEnabled(true);
			popupMenuDelete.setEnabled(true);
		}
		//粘贴功能
		Transferable contents=clipBoard.getContents(this);     //获取剪贴板的内容
		if(contents == null) {
			editPaste.setEnabled(false);
			popupMenuPaste.setEnabled(false);
		}
		else {
			editPaste.setEnabled(true);
			popupMenuPaste.setEnabled(true);
		}
	}

这样文本编辑区的基本的一些功能就实现了,还有些小细节什么的自己看一下源代码就好

(3)窗口关闭的这个功能,就是你打开文件然后关闭记事本的时候,需要检查文本内容有没有发生改变,选择你的操作,保存还是直接退出之类的

public void exitWindowChoose() {
		editArea.requestFocus();   //定到文本编辑区
		String currentText = editArea.getText();   //获取当前编辑区的内容
		if(currentText.equals(oldText)) {
			setMemory();            //保存文件的设置
			System.exit(0);
		}
		else {
			int exitChoose = JOptionPane.showConfirmDialog(this, "文件尚未保存", 
					"退出提示", JOptionPane.YES_NO_CANCEL_OPTION);
			if(exitChoose == JOptionPane.YES_OPTION) {
				if(isNewFile) {
					saveNewFile();
				}
				else {
					saveNotNewFile();
				}
				setMemory();
				System.exit(0);
			}
			else if (exitChoose == JOptionPane.NO_OPTION){
				setMemory();
				System.exit(0);
			}
			else if (exitChoose == JOptionPane.CANCEL_OPTION) {
				statusLabel2.setText("文件未保存");
				return;
			}
			else {
				return;
			}
		}
	}
	

(4)上面的其实还要用到就是保存,另存为,不保存这些功能,其实这些在菜单栏中都存在,就贴一下代码看一下

public void saveNewFile() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);    //只读方式打开
		fileChooser.setApproveButtonText("确定");
		fileChooser.setDialogTitle("另存为");
		
		int result = fileChooser.showSaveDialog(this);
		if(result == JFileChooser.CANCEL_OPTION) {
			statusLabel2.setText("文件未保存");
			return;
		}
		
		File saveFileName = fileChooser.getSelectedFile();
		if(saveFileName == null || saveFileName.getName().equals("")) {
			JOptionPane.showMessageDialog(this, "错误的文件名", "错误的文件名", JOptionPane.ERROR_MESSAGE);
		}
		else {
			try {        //将文件保存
				OutputStream os = new FileOutputStream(saveFileName);   //创建文件
				OutputStreamWriter osw = new OutputStreamWriter(os);   //OutputStreamWriter的接收类型是OutputStream,字节转换为字符流
				PrintWriter pw = new PrintWriter(osw);  //字符输出流
				pw.write(editArea.getText());  //获取文本编辑区中的内容并写入文本
				pw.flush();     //将缓冲区的数据流清除
				pw.close();    //关闭所有关联的输出串流
				
				isNewFile  = false;
				currentFile = saveFileName;
				this.setTitle(saveFileName.getName());
				statusLabel2.setText("当前文件名为:" + saveFileName.getAbsolutePath());   //获取文件的绝对路径
				
			}catch(IOException ioe) {
				ioe.printStackTrace();     //抛出异常产生的位置和原因
			}
		}
	}
	
	//当文件内容没有发生改变时不保存新文件
	public void saveNotNewFile() {
		try {
			OutputStream os = new FileOutputStream(currentFile);
			OutputStreamWriter osw = new OutputStreamWriter(os);
			PrintWriter pw = new PrintWriter(osw);
			pw.write(editArea.getText());
			pw.flush();
			pw.close();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	//文件另存为
	public void saveAs() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setApproveButtonText("确定");
		fileChooser.setDialogTitle("另存为");
		
		int result = fileChooser.showSaveDialog(this);
		if(result == JFileChooser.CANCEL_OPTION) {
			statusLabel2.setText("文件为保存");
			return;
		}
		
		File saveFileName = fileChooser.getSelectedFile();
		if(saveFileName == null || saveFileName.getName().equals("")) {
			JOptionPane.showMessageDialog(this, "错误的文件名", "错误的文件名", JOptionPane.ERROR_MESSAGE);
		}
		else {
			try {
				OutputStream os = new FileOutputStream(currentFile);
				OutputStreamWriter osw = new OutputStreamWriter(os);
				PrintWriter pw = new PrintWriter(osw);
				pw.write(editArea.getText());
				pw.flush();
				pw.close();
				
				isNewFile = false;
				currentFile = saveFileName;
				this.setTitle(saveFileName.getName());
				statusLabel2.setText("当前文件名  " + saveFileName.getAbsolutePath());
			}catch(IOException ioe) {
				ioe.printStackTrace();
			}
		}
		
	}
	

其实文件另存为和保存一样的,因为本来就是一样的功能

(5)字体设置,这个。。。。。给代码大家一起研究下

package Font;  
  
import java.awt.BorderLayout;    
import java.awt.Color;    
import java.awt.Dimension;    
import java.awt.Font;    
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.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.AttributeSet;    
import javax.swing.text.BadLocationException;    
import javax.swing.text.Document;    
import javax.swing.text.PlainDocument;    
/**   
 * 字体选择器,仿记事本中的字体控件,使用操作方法与文件选择器JFileChooser基本相同。   
 *  
 */    
@SuppressWarnings("serial")    
public class MyFont extends JDialog {    
    /**   
     * 选择取消按钮的返回值   
     */    
    public static final int CANCEL_OPTION = 0;    
    /**   
     * 选择确定按钮的返回值   
     */    
    public static final int APPROVE_OPTION = 1;    
    /**   
     * 中文预览的字符串   
     */    
    private static final String CHINA_STRING = "神马都是浮云!";    
    /**   
     * 英文预览的字符串   
     */    
    private static final String ENGLISH_STRING = "Hello Kitty!";    
    /**   
     * 数字预览的字符串   
     */    
    private static final String NUMBER_STRING = "0123456789";    
    // 预设字体,也是将来要返回的字体    
    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 = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "初号", "小初", "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号", "小五", "六号", "小六", "七号", "八号"};    
    // 上面数组中对应的字体大小    
    private int [] sizeIntArray = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 42, 36, 26, 24, 22, 18, 16, 15, 14, 12, 10, 9, 8, 7, 6, 5};    
    // 返回的数值,默认取消    
    private int returnValue = CANCEL_OPTION;    
    /**   
     * 体构造一个字体选择器   
     */    
    public MyFont() {    
        this(new Font("宋体", Font.PLAIN, 12));    
    }    
    /**   
     * 使用给定的预设字体构造一个字体选择器   
     * @param font 字体   
     */    
    public MyFont(Font font) {    
        setTitle("字体选择器");    
        this.font = font;    
        // 初始化UI组件    
        init();    
        // 添加监听器    
        addListener();    
        // 按照预设字体显示    
        setup();    
        // 基本设置    
        setModal(true);    
        setResizable(false);    
        // 自适应大小    
        pack();    
    }    
    /**   
     * 初始化组件   
     */    
    private void init(){    
        // 获得系统字体    
        GraphicsEnvironment eq = GraphicsEnvironment.getLocalGraphicsEnvironment();    
        fontArray = eq.getAvailableFontFamilyNames();    
        // 主容器    
        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, 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 int showFontDialog(JFrame owner) {    
        setLocationRelativeTo(owner);    
        setVisible(true);    
        return returnValue;    
    }    
    /**   
     * 返回选择的字体对象   
     * @return 字体对象   
     */    
    public final Font getSelectFont() {    
        return font;    
    }    
    /**   
     * 关闭窗口   
     */    
    private void disposeDialog() {    
        MyFont.this.removeAll();    
        MyFont.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();    
        int fontStyle = styleList.getSelectedIndex();    
        String sizeStr = sizeText.getText().trim();    
        // 如果没有输入    
        if(sizeStr.length() == 0) {    
            showErrorDialog("字体(大小)必须是有效“数值!");    
            return null;    
        }    
        int 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(fontName, fontStyle, fontSize);    
    }    
        
    /**   
     * 编码选择事件的监听动作   
     *   
     */    
    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);    
            }    
        }    
    }    
        
}    
到这里功能就基本完成了,有什么要改善的以后再完善

源代码下载地址:

https://github.com/songwell1024/NotePad.git


猜你喜欢

转载自blog.csdn.net/wilsonsong1024/article/details/79657956