第十四周课程总结&实验报告(简单记事本的实现)

1、JDBC概述

JDBC提供了一种与平台无关的用于执行SQL语句的标准JavaAPI,可以方便的实现多种关系型数据库的统一操作,它由一组用Java语言编写的类和接口组成

主要常用操作类与接口:

java.sql.DriverManager 用于管理jdbc驱动程序

Java.sql.Connection 用于建立与特定数据库的连接

Java.sql.Statement 一个Statement的对象用于执行静态sql语句,并获得语句执行后产生的后果

Java.sql.PreparedStatement 创建一个可以编译的sql语句对象,该对象可以多次被运行,以提高执行效率,是Statement的子接口

Java.sql.ResultSet 用于创建表示sql语句检索结果的结果集,用户通过结果集完成对数据库的访问

2、JDBC操作步骤

(1)加载驱动

public class Text {
        public static final String DBDRIVER="ora.gjt.mm.mysql.Driver";
    public static void main(String[] args) {
        try {
            Class.forName(DBDRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

(2)连接数据库:使用DriverManager类连接数据库和Connection接口

jdbc:mysql://IP地址:端口号/数据库名称

(3)通过Statement发送sql语句

通过Prepared Statement发送sql语句

(4)关闭数据库

3、MySQL数据库操作

数据库连接

mysql -u用户名 -p密码

数据库创建

创建数据库 CREATE DATABASE 数据库名称;

数据库删除 DROP DATABASE 数据库名称;

使用数据库

USE 数据库名称;

创建数据库表

CREATE TABLE{
字段名称1   字段类型 [DEFAULT 默认值][约束]
字段名称2   字段类型 [DEFAULT 默认值][约束],
...,
字段名称n   字段类型 [DEFAULT 默认值][约束],

删除数据库表 DELETE FROM 表名称

更新 UPDATE 表名称

查询 SELECT{*lcolumn alias} FROM 表名称

记事本

package lastwork;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;

import javax.swing.event.UndoableEditListener;
import javax.swing.text.View;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

import org.w3c.dom.Text;


import jdk.jshell.execution.Util;


public class TextPad extends dialog implements ActionListener, DocumentListener{

	JFrame frame;
	JMenu fileMenu,editManu,formatMenu,checkMenu,helpMenu;
	JMenuBar bar;
	ImageIcon openicon,newicon,saveicon,saveanothericon,closeicon,linewrapicon;
	JMenuItem openitem,newitem,saveitem,saveanotheritem,closeitem,pageitem,pointitem;
	JMenuItem repealitem,cutitem,copyitem,stickitem,deleteitem,allitem,timedateitem,finditem,findnextitem,replaceitem,turnitem;
	JMenuItem prepealitem,pcutitem,pcopyitem,pstickitem,pdeleteitem,pallitem,ptimedateitem;
	JMenuItem linewrapitem,fontitem;
	JMenuItem checkhelpitem,aboutitem;
	JMenuItem stateitem;
	JTextArea area;
	JScrollPane scpane;
	JFileChooser chooser;
	File file;
	JButton bt;
	JPopupMenu pMenu;
	boolean i=false;
	boolean isNewFile=true;
	File currentFile;
	String oldValue;
	JLabel statusLabel;
	//系统剪贴板
	Toolkit toolkit=Toolkit.getDefaultToolkit();
	Clipboard clipBoard=toolkit.getSystemClipboard();
	//创建撤销操作管理器(与撤销操作有关)
	protected UndoManager undo=new UndoManager();
	protected UndoableEditListener undoHandler=new UndoHandler();
	 
	public TextPad(){
		frame=new JFrame("记事本");
		bar=new JMenuBar();
		fileMenu=new JMenu("文件(F)");
		editManu=new JMenu("编辑(E)");
		formatMenu=new JMenu("格式(O)");
		checkMenu=new JMenu("查看(V)");
		helpMenu=new JMenu("帮助(H)");
		statusLabel=new JLabel("              状态栏");
		frame.add(statusLabel,BorderLayout.SOUTH);
		area=new JTextArea();
		scpane=new JScrollPane(area);
		pMenu=new JPopupMenu();
		
		//图片导入路径
		newicon=new ImageIcon("d:"+File.separator+"111"+File.separator+"new.png");
		openicon=new ImageIcon("d:"+File.separator+"111"+File.separator+"open.png");
		saveicon=new ImageIcon("d:"+File.separator+"111"+File.separator+"save.png");
		saveanothericon=new ImageIcon("d:"+File.separator+"111"+File.separator+"saveanother.png");
		closeicon=new ImageIcon("d:"+File.separator+"111"+File.separator+"close.png");
		linewrapicon=new ImageIcon("d:"+File.separator+"111"+File.separator+"d.png");
		
		//调用图片
		newitem=new JMenuItem("新建(N)",newicon);
		openitem=new JMenuItem("打开(O)",openicon);
		saveitem=new JMenuItem("保存(S)",saveicon);
		saveanotheritem=new JMenuItem("另存为(A)",saveanothericon);
		closeitem=new JMenuItem("关闭(X)",closeicon);
		pageitem=new JMenuItem("页面设置(U)");
		pointitem=new JMenuItem("打印(P)");
		
		repealitem=new JMenuItem("撤销(U)");
		cutitem=new JMenuItem("剪切(T)");
		copyitem=new JMenuItem("复制(C)");
		stickitem=new JMenuItem("粘贴(V)");
		deleteitem=new JMenuItem("删除(L)");
		finditem=new JMenuItem("查找(F)");
		findnextitem=new JMenuItem("查找下一个(FN)");
		replaceitem=new JMenuItem("替换(H)");
		turnitem=new JMenuItem("转到(G)");
		allitem=new JMenuItem("全选(A)");
		timedateitem=new JMenuItem("时间/日期(D)");
		
		linewrapitem=new JMenuItem("自动换行(W)",linewrapicon);
		fontitem=new JMenuItem("字体(F)");
		
		stateitem=new JMenuItem("状态栏(S)");
		
		checkhelpitem=new JMenuItem("查看帮助(H)");
		aboutitem=new JMenuItem("关于(A)");
		
		//添加为菜单项
		fileMenu.add(newitem);
		fileMenu.add(openitem);
		fileMenu.add(saveitem);
		fileMenu.add(saveanotheritem);
		fileMenu.addSeparator();
		fileMenu.add(pageitem);
		fileMenu.add(pointitem);
		fileMenu.addSeparator();
		fileMenu.add(closeitem);
		
		editManu.add(repealitem);
		editManu.addSeparator();
		editManu.add(cutitem);
		editManu.add(copyitem);
		editManu.add(stickitem);
		editManu.add(deleteitem);
		editManu.addSeparator();
		editManu.add(finditem);
		editManu.add(findnextitem);
		editManu.add(replaceitem);
		editManu.add(turnitem);
		editManu.addSeparator();
		editManu.add(allitem);
		editManu.add(timedateitem);
		
		repealitem.setEnabled(false);
		cutitem.setEnabled(false);
		copyitem.setEnabled(false);
		deleteitem.setEnabled(false);
		
		
		formatMenu.add(linewrapitem);
		formatMenu.add(fontitem);
		
		checkMenu.add(stateitem);
		
		helpMenu.add(checkhelpitem);
		helpMenu.add(aboutitem);
		
		prepealitem=new JMenuItem("撤销(U)");
		pcutitem=new JMenuItem("剪切(T)");
		pcopyitem=new JMenuItem("复制(C)");
		pstickitem=new JMenuItem("粘帖(P)");
		pdeleteitem=new JMenuItem("删除(D)");
		pallitem=new JMenuItem("全选(A)");
		ptimedateitem=new JMenuItem("时间/日期(D)");
		 
		prepealitem.setEnabled(false);
		
		pMenu.add(prepealitem);
		pMenu.addSeparator();
		pMenu.add(pcutitem);
		pMenu.add(pcopyitem);
		pMenu.add(pstickitem);
		pMenu.add(pdeleteitem);
		pMenu.add(pallitem);
		pMenu.add(ptimedateitem);
		
		//设置快捷键和提示信息
		newitem.setMnemonic(KeyEvent.VK_N);
		newitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,InputEvent.CTRL_DOWN_MASK));
		openitem.setMnemonic(KeyEvent.VK_O);
		openitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_DOWN_MASK));
		saveitem.setMnemonic(KeyEvent.VK_S);
		saveitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_DOWN_MASK));
		saveanotheritem.setMnemonic(KeyEvent.VK_A);
		saveanotheritem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_DOWN_MASK));
		closeitem.setMnemonic(KeyEvent.VK_X);
		closeitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_DOWN_MASK));
		pageitem.setMnemonic(KeyEvent.VK_U);
		pointitem.setMnemonic(KeyEvent.VK_P);
		pointitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_DOWN_MASK));
		
		repealitem.setMnemonic(KeyEvent.VK_Z);
		repealitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_DOWN_MASK));
		cutitem.setMnemonic(KeyEvent.VK_T);
		cutitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,InputEvent.CTRL_DOWN_MASK));
		copyitem.setMnemonic(KeyEvent.VK_C);
		copyitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_DOWN_MASK));
		stickitem.setMnemonic(KeyEvent.VK_V);
		stickitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_DOWN_MASK));
		deleteitem.setMnemonic(KeyEvent.VK_L);
		deleteitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_DOWN_MASK));
		allitem.setMnemonic(KeyEvent.VK_A);
		allitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_DOWN_MASK));
		timedateitem.setMnemonic(KeyEvent.VK_D);
		timedateitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,InputEvent.CTRL_DOWN_MASK));
		finditem.setMnemonic(KeyEvent.VK_F);
		finditem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,InputEvent.CTRL_DOWN_MASK));
		findnextitem.setMnemonic(KeyEvent.VK_L);
		findnextitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_DOWN_MASK));
		replaceitem.setMnemonic(KeyEvent.VK_H);
		replaceitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,InputEvent.CTRL_DOWN_MASK));
		turnitem.setMnemonic(KeyEvent.VK_G);
		turnitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,InputEvent.CTRL_DOWN_MASK));
		
		prepealitem.setMnemonic(KeyEvent.VK_Z);
		prepealitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_DOWN_MASK));
		pcutitem.setMnemonic(KeyEvent.VK_T);
		pcutitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,InputEvent.CTRL_DOWN_MASK));
		pcopyitem.setMnemonic(KeyEvent.VK_C);
		pcopyitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_DOWN_MASK));
		pstickitem.setMnemonic(KeyEvent.VK_V);
		pstickitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_DOWN_MASK));
		pdeleteitem.setMnemonic(KeyEvent.VK_L);
		pdeleteitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_DOWN_MASK));
		pallitem.setMnemonic(KeyEvent.VK_A);
		pallitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,InputEvent.CTRL_DOWN_MASK));
		ptimedateitem.setMnemonic(KeyEvent.VK_D);
		ptimedateitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,InputEvent.CTRL_DOWN_MASK));
		
		linewrapitem.setMnemonic(KeyEvent.VK_W);
		fontitem.setMnemonic(KeyEvent.VK_F);
		stateitem.setMnemonic(KeyEvent.VK_S);
		
		checkhelpitem.setMnemonic(KeyEvent.VK_H);
		aboutitem.setMnemonic(KeyEvent.VK_A);
		
		//添加事件监听器
		newitem.addActionListener(this);
		openitem.addActionListener(this);
		saveitem.addActionListener(this);
		saveanotheritem.addActionListener(this);
		closeitem.addActionListener(this);
		pageitem.addActionListener(this);
		pointitem.addActionListener(this);
		
		repealitem.addActionListener(this);
		cutitem.addActionListener(this);
		copyitem.addActionListener(this);
		stickitem.addActionListener(this);
		deleteitem.addActionListener(this);
		allitem.addActionListener(this);
		timedateitem.addActionListener(this);
		finditem.addActionListener(this);
		findnextitem.addActionListener(this);
		replaceitem.addActionListener(this);
		turnitem.addActionListener(this);
		
		linewrapitem.addActionListener(this);
		fontitem.addActionListener(this);
		
		stateitem.addActionListener(this);
		
		checkhelpitem.addActionListener(this);
		aboutitem.addActionListener(this);
		
		area.addMouseListener(new MouseAdapter()
		 { public void mousePressed(MouseEvent e){ 
			 if(e.isPopupTrigger())//返回此鼠标事件是否为该平台的弹出菜单触发事件
				 { pMenu.show(e.getComponent(),e.getX(),e.getY());//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单
				 }
			 checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性
			 area.requestFocus();//编辑区获取焦点
		 	}
		 public void mouseReleased(MouseEvent e)
		 { if(e.isPopupTrigger())//返回此鼠标事件是否为该平台的弹出菜单触发事件
		 { pMenu.show(e.getComponent(),e.getX(),e.getY());//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单
		 }
		 checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性
		 area.requestFocus();//编辑区获取焦点
		 }
		 });
		
		prepealitem.addActionListener(this);
		pcutitem.addActionListener(this);
		pcopyitem.addActionListener(this);
		pstickitem.addActionListener(this);
		pdeleteitem.addActionListener(this);
		pallitem.addActionListener(this);
		ptimedateitem.addActionListener(this);
		
		
		//编辑区注册事件监听(与撤销操作有关)
		area.getDocument().addUndoableEditListener(undoHandler);
		area.getDocument().addDocumentListener(this);
		
		//添加主菜单项
		bar.add(fileMenu);
		bar.add(editManu);
		bar.add(formatMenu);
		bar.add(checkMenu);
		bar.add(helpMenu);
		
		//添加面板及显示
		frame.add(scpane);
		frame.setJMenuBar(bar);
		frame.setSize(800, 550);
		frame.setLocation(400, 200);
		
		frame.setVisible(true);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent arg0) {
				System.exit(1);
			}
		});
		
		
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		Object obj=e.getSource();
		if(obj instanceof JMenuItem) {
			JMenuItem item=(JMenuItem)obj;
			if(item==newitem) {
				new TextPad();
	 	
			}else if(item==openitem) {
				chooser=new JFileChooser();
				chooser.showOpenDialog(null);
				file=chooser.getSelectedFile();
				try {
					FileInputStream fis=new FileInputStream(file);
					byte[] b;
					try {
						b = new byte[fis.available()];
						fis.read(b);
						area.append(new String(b));
						fis.close();
					} catch (IOException e1) {
						
						e1.printStackTrace();
					}
					
				} catch (FileNotFoundException e1) {
					
					e1.printStackTrace();
				}
			}else if(item==saveanotheritem) {
				chooser=new JFileChooser();
				chooser.showSaveDialog(null);
				file=chooser.getSelectedFile();
				try {
					if(!file.exists()) {
						file.createNewFile();
					}
					FileOutputStream fos=new FileOutputStream(file);
					byte[] b=area.getText().getBytes();
					fos.write(b);
					fos.close();
				} catch (IOException e1) {
				
					e1.printStackTrace();
				}
			}else if(item==saveitem) {
				file=chooser.getSelectedFile();
				try {
					FileOutputStream fos=new FileOutputStream(file);
					byte[] b=area.getText().getBytes();
					fos.write(b);
					
					fos.close();
				} catch (FileNotFoundException e1) {
					
					e1.printStackTrace();
				} catch (IOException e1) {
					
					e1.printStackTrace();
				}
			
			}else if(item==closeitem) {
				 //System.exit(1);
				 int exitChoose=JOptionPane.showConfirmDialog(this,"确定要退出吗?","退出提示",JOptionPane.OK_CANCEL_OPTION);
				 if(exitChoose==JOptionPane.OK_OPTION){ 
					 System.exit(0);
				 }else{ 
					 return;
				 }
			}else if(item==cutitem||item==pcutitem) {
				area.cut();

			}else if(item==copyitem||item==pcopyitem) {
				area.copy();

			}else if(item==stickitem||item==pstickitem) {
				area.paste();

			}else if(item==allitem||item==pallitem) {
				area.selectAll();

			}else if(item==deleteitem||item==pdeleteitem) {
	 
				String temp = area.getSelectedText();//获得鼠标拖动选取的文本 
				int start = area.getSelectionStart(); 
				int end = area.getSelectionEnd(); 
				area.replaceRange("",start,end);//选中的区域用""替换 
					    
			}else if(item==repealitem||item==prepealitem) {
				if(e.getSource()==repealitem || e.getSource()==prepealitem){
					area.requestFocus();
			 		if(undo.canUndo()){
			 			try{ 
			 					undo.undo();
			 			}catch (CannotUndoException ex){ 
			 					System.out.println("Unable to undo:" + ex);
			 					//ex.printStackTrace();
			 			}
			 		}
			 if(!undo.canUndo()){ 
				 repealitem.setEnabled(false);
				 prepealitem.setEnabled(false);
			 }
			 }
				
			}else if(item==timedateitem||item==ptimedateitem) {
				 Date d = new Date();
				 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				 String dateNewStr=sdf.format(d);
				 area.append(dateNewStr);
				 
			}else if(item==pageitem) {
				area.requestFocus();
				JOptionPane.showMessageDialog(this,"对不起,此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
				
			}else if(item==pointitem) {
				area.requestFocus();
				JOptionPane.showMessageDialog(this,"对不起,此功能尚未实现!","提示",JOptionPane.WARNING_MESSAGE);
				
			}else if(item==finditem) {
				
				
			}else if(item==findnextitem) {
				
				
			}else if(item==replaceitem) {
				
				
			}else if(item==turnitem) {
				
				
			}
			
			else if(item==linewrapitem) {
				
				
				if(!i) {
					area.setLineWrap(true);    
//					area.setWrapStyleWord(true);

					
					i=true;
				}else {
					area.setLineWrap(false);    
//					area.setWrapStyleWord(false); 
					
					i=false;
				}
				
				
			}else if(item==fontitem) {
				area.requestFocus();
				font();
			}else if(item==stateitem) {
				if(!i) {
					statusLabel.setVisible(false);   
					i=true;
				}else {
					statusLabel.setVisible(true);
					i=false;
				}
				
				
			}else if(item==checkhelpitem) {
				 area.requestFocus();
				 JOptionPane.showMessageDialog(this,"请自行百度","帮助主题",JOptionPane.INFORMATION_MESSAGE);

			}else if(item==aboutitem) {
					area.requestFocus();
					JOptionPane.showMessageDialog(this,
				 "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n"+
				 " 编写者:张文龙    \n"+
				 " 编写时间:2019年11月 \n"+
				 " qq:908866340 \n"+
				 " 一些地方借鉴他人  \n"+
				 "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n",
				 "记事本",JOptionPane.INFORMATION_MESSAGE);
			}
		}

	}

	private void checkMenuItemEnabled() {
		String selectText=area.getSelectedText();
		 if(selectText==null){ 
			 cutitem.setEnabled(false);
			 pcutitem.setEnabled(false);
			 copyitem.setEnabled(false);
			 pcopyitem.setEnabled(false);
			 deleteitem.setEnabled(false);
			 pdeleteitem.setEnabled(false);
			 
		 	 }else{
		 		cutitem.setEnabled(true);
		 		pcutitem.setEnabled(true); 
		 		copyitem.setEnabled(true);
		 		pcopyitem.setEnabled(true);
		 		deleteitem.setEnabled(true);
		 		pdeleteitem.setEnabled(true);
		 }
		 //粘帖功能可用性判断
		 Transferable contents=clipBoard.getContents(this);
		 if(contents==null){ 
			 stickitem.setEnabled(false);
			 pstickitem.setEnabled(false);
		 }else{ 
			 stickitem.setEnabled(true);
			 pstickitem.setEnabled(true); 
		 }
		 
		
	}
	class UndoHandler implements UndoableEditListener{ 
		 public void undoableEditHappened(UndoableEditEvent uee){ 
			 undo.addEdit(uee.getEdit());
	 }
	 }

	public void font(){ 

	     final JDialog fontDialog=new JDialog(this,"字体设置",false);
		 Container con=fontDialog.getContentPane();
		 con.setLayout(new FlowLayout(FlowLayout.LEFT));

		 JLabel fontLabel=new JLabel("字体(F):");
		 fontLabel.setPreferredSize(new Dimension(100,20));//构造一个Dimension,并将其初始化为指定宽度和高度

		 JLabel styleLabel=new JLabel("字形(Y):");
		 styleLabel.setPreferredSize(new Dimension(100,20));

		 JLabel sizeLabel=new JLabel("大小(S):");
		 sizeLabel.setPreferredSize(new Dimension(100,20));

		 final JLabel sample=new JLabel("张文龙的记事本");

		 final JTextField fontText=new JTextField(9);
		 fontText.setPreferredSize(new Dimension(200,20));

		 final JTextField styleText=new JTextField(8);
		 styleText.setPreferredSize(new Dimension(200,20));

		 final int style[]={Font.PLAIN,Font.BOLD,Font.ITALIC,Font.BOLD+Font.ITALIC};
		 final JTextField sizeText=new JTextField(5);
		 sizeText.setPreferredSize(new Dimension(200,20));

		 JButton okButton=new JButton("确定");
		 JButton cancel=new JButton("取消");

		 cancel.addActionListener(new ActionListener(){ 
	         public void actionPerformed(ActionEvent e){ 
	             fontDialog.dispose(); 
		    }
		 });

		 Font currentFont=area.getFont();
		 fontText.setText(currentFont.getFontName());
		 fontText.selectAll();
		 
		 if(currentFont.getStyle()==Font.PLAIN){
	         styleText.setText("常规");
	     }
		 else if(currentFont.getStyle()==Font.BOLD){
	         styleText.setText("粗体");
	     }
		 else if(currentFont.getStyle()==Font.ITALIC){
	         styleText.setText("斜体");
	     }
		 else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC)){
	         styleText.setText("粗斜体");
	     }
		 
		 styleText.selectAll();

		 String str=String.valueOf(currentFont.getSize());
		 sizeText.setText(str);
		 sizeText.selectAll();

		 final JList fontList,styleList,sizeList;
		 GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
		 final String fontName[]=ge.getAvailableFontFamilyNames();

		 fontList=new JList(fontName);
		 fontList.setFixedCellWidth(86);
		 fontList.setFixedCellHeight(20);
		 fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		 final String fontStyle[]={"常规","粗体","斜体","粗斜体"};

		 styleList=new JList(fontStyle);
		 styleList.setFixedCellWidth(86);
		 styleList.setFixedCellHeight(20);
		 styleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		 if(currentFont.getStyle()==Font.PLAIN){
	         styleList.setSelectedIndex(0);
	     }
		 
		 else if(currentFont.getStyle()==Font.BOLD){
	         styleList.setSelectedIndex(1);
	     }
		 
		 else if(currentFont.getStyle()==Font.ITALIC){
	         styleList.setSelectedIndex(2);
	     }
		 
		 else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC)){
	         styleList.setSelectedIndex(3);
	     }
		 
		 final String fontSize[]={"8","9","10","11","12","14","16","18","20","22","24","26","28","36","48","72"};
		 sizeList=new JList(fontSize);
		 sizeList.setFixedCellWidth(43);
		 sizeList.setFixedCellHeight(20);
		 sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		 fontList.addListSelectionListener(new ListSelectionListener(){
	        public void valueChanged(ListSelectionEvent event){
	            fontText.setText(fontName[fontList.getSelectedIndex()]);
		        fontText.selectAll();
		        Font sampleFont1=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
		        sample.setFont(sampleFont1);
		    }
		 });
		 styleList.addListSelectionListener(new ListSelectionListener(){
	        public void valueChanged(ListSelectionEvent event){
	            int s=style[styleList.getSelectedIndex()];
		        styleText.setText(fontStyle[s]);
		        styleText.selectAll();
		        Font sampleFont2=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
		        sample.setFont(sampleFont2);
		 }
		 });
		 sizeList.addListSelectionListener(new ListSelectionListener(){ 
	         public void valueChanged(ListSelectionEvent event){ 
	            sizeText.setText(fontSize[sizeList.getSelectedIndex()]);
		        //sizeText.requestFocus();
		        sizeText.selectAll(); 
		        Font sampleFont3=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
		        sample.setFont(sampleFont3);
		    }
		 });
		 okButton.addActionListener(new ActionListener(){ 
	        public void actionPerformed(ActionEvent e){ 
	        Font okFont=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
		    area.setFont(okFont);
		    fontDialog.dispose();
		    }
		 });

		 JPanel samplePanel=new JPanel();
		 samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));
		 
		 samplePanel.add(sample);
		 JPanel panel1=new JPanel();
		 JPanel panel2=new JPanel();
		 JPanel panel3=new JPanel();
		 panel2.add(fontText);
		 panel2.add(styleText);
		 panel2.add(sizeText);
		 panel2.add(okButton);
		 panel3.add(new JScrollPane(fontList));//JList不支持直接滚动,所以要让JList作为JScrollPane的视口视图
		 panel3.add(new JScrollPane(styleList));
		 panel3.add(new JScrollPane(sizeList));
		 panel3.add(cancel);
		 con.add(panel1);
		 con.add(panel2);
		 con.add(panel3);
		 con.add(samplePanel);
		 fontDialog.setSize(350,340);
		 fontDialog.setLocation(200,200);
		 fontDialog.setResizable(false);
		 fontDialog.setVisible(true);
		 }
	public void insertUpdate(DocumentEvent e) {
		repealitem.setEnabled(true);
		prepealitem.setEnabled(true);
	}
	
	public void removeUpdate(DocumentEvent e) {
		repealitem.setEnabled(true);
		prepealitem.setEnabled(true);
	}
	
	public void changedUpdate(DocumentEvent e) {
		repealitem.setEnabled(true);
		prepealitem.setEnabled(true);
	}
}


运行截图

posted @ 2019-11-29 18:15  zzwwll  阅读(247)  评论(1编辑  收藏  举报