学习JAVA,自己写的一个文本编辑器

//打开保存文件,替换选定文本的颜色,字体,字号,字形
//参考了他人的代码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.text.*;

public class NotePad extends JFrame implements ActionListener {
	final String help = "选择文字,然后再选择操作。";
	final String about = "这是关于!!";
	final String test = "话说有一天,海民和人马大叔在下路猥琐(别问我为什么),他们静静等待着猎物…\n忽然,海民眼里闪过一道异彩,有人来了!谁?黑鸟!丫的,看我不杀了你。海民心想,他叫人马大叔准备。\n嘿嘿,天堂有路你不走,地狱无门你偏来。海民和人马揉成一个大雪球滚了过去,黑鸟见阴影中出来的雪球大叫道:雅灭蝶。\n只见一声雪蹦,冰霜四射,震耳欲聋,啊的一声惨叫,下路的那位黑皮肤好青年就挂了…黑鸟道:我有姿势我自豪。\n黑鸟在泉水边复活了,他摸摸兜里的钱3000了。黄光一闪,然后他又回程去了下路。\n正在下路近卫树林里调情的小俩口眼睛一亮,心想到,这ATM又来送了。\n黑鸟一下下A着小兵,显的格外悠闲…这时,雪球又出现了! 哼 一帮战斗力只有5的渣。黑鸟不屑道。他掏出了那根使他硬起来的棒子…\n纳尼?正和人马大叔滚得天翻地覆的海民看见了黑鸟手中的棒棒,吹风!……黑鸟被自己吹起来了,两个萎缩男等在下面强势围观,黑鸟冷冷一笑,shift+T…\n黑鸟禁锢了自己…人马大叔无语的看着海民,因为他刚刚踩地了……而海民也无语的看着人马,因为他刚才发了冰墙……\n4秒的禁锢很快过去了…黑鸟出来了!他身上散发出浓浓的王八之气,让两男深深后退了两步。 不怕!他只有一个人!海民对人马说道,人马点点头,道 杀!\n啊!啊!两声惨叫响彻云霄…黑鸟完成了一次双杀!黑鸟点了一支烟,乎出一口气,道:哥这般风骚的男生岂是你们能亵渎的…";

	// 字体相关
	private Frame fontFrame;
	private JLabel labelname, labeltype, labelsize, labelshow;
	private TextArea textshow;
	private List listname, listtype, listsize;
	private GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
	private String[] name = graphicsEnvironment.getAvailableFontFamilyNames();
	private String[] type = { "常规", "加粗", "倾斜", "加粗&倾斜" };
	private String[] size = { "6", "7", "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28",
			"36", "48" };
	private TextField tfname, tftype, tfsize;
	private Button buttonOk, buttonCancel;
	private String aname = "";
	private int atype, asize;
	boolean exit = false;
	private Font oldFont, newFont;

	private JMenuBar menuBar = new JMenuBar();
	private JMenu menuFile, menuFormat, menuHelp;
	private JMenuItem menuItemFileOpen, menuItemFileSave, menuItemFileExit, menuItemFormatFont, menuItemFormatColor,
			menuItemFormatTypeB, menuItemFormatTypeI, menuItemFormatClear, menuItemHelpHelp, menuItemHelpAbout;
	private JLabel label = new JLabel();
	private JTextPane textPane;
	private JScrollPane scrollPane = new JScrollPane(textPane = new JTextPane());
	private FileDialog fileDialog_Open, fileDialog_Save;
	private File file;
	private String filedir = "", filename = "";

	// 构造函数,创建菜单和快捷键
	public NotePad() {
		// super("JTextPane NotePad");
		getContentPane().setLayout(new BorderLayout());
		setTitle("文本编辑器");
		setLocation(383, 159);
		setSize(600, 450);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		textPane.setText(test);

		menuFile = new JMenu("文件(F)");
		menuFile.setMnemonic('F');
		menuFormat = new JMenu("格式(O)");
		menuFormat.setMnemonic('O');
		menuHelp = new JMenu("帮助(H)");
		menuHelp.setMnemonic('H');

		menuItemFileOpen = new JMenuItem("打开(O)");
		menuItemFileOpen.setMnemonic('O');
		menuItemFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
		menuItemFileSave = new JMenuItem("保存(S)");
		menuItemFileSave.setMnemonic('S');
		menuItemFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
		menuItemFileExit = new JMenuItem("退出(Q)");
		menuItemFileExit.setMnemonic('Q');
		menuItemFileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK));
		menuFile.add(menuItemFileOpen);
		menuFile.add(menuItemFileSave);
		menuFile.addSeparator();
		menuFile.add(menuItemFileExit);
		menuItemFileOpen.addActionListener(this);
		menuItemFileSave.addActionListener(this);
		menuItemFileExit.addActionListener(this);

		menuItemFormatFont = new JMenuItem("字体(T)");
		menuItemFormatFont.setMnemonic('T');
		menuItemFormatFont.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
		menuItemFormatColor = new JMenuItem("颜色(Y)");
		menuItemFormatColor.setMnemonic('Y');
		menuItemFormatColor.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK));
		menuItemFormatTypeB = new JMenuItem("粗体(B)");
		menuItemFormatTypeB.setMnemonic('B');
		menuItemFormatTypeB.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
		menuItemFormatTypeI = new JMenuItem("斜体(I)");
		menuItemFormatTypeI.setMnemonic('I');
		menuItemFormatTypeI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
		menuItemFormatClear = new JMenuItem("清除格式(G)");
		menuItemFormatClear.setMnemonic('G');
		menuItemFormatClear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK));
		menuFormat.add(menuItemFormatFont);
		menuFormat.add(menuItemFormatColor);
		menuFormat.addSeparator();
		menuFormat.add(menuItemFormatTypeB);
		menuFormat.add(menuItemFormatTypeI);
		menuFormat.addSeparator();
		menuFormat.add(menuItemFormatClear);
		menuItemFormatFont.addActionListener(this);
		menuItemFormatColor.addActionListener(this);
		menuItemFormatTypeB.addActionListener(this);
		menuItemFormatTypeI.addActionListener(this);
		menuItemFormatClear.addActionListener(this);

		menuItemHelpHelp = new JMenuItem("帮助(L)");
		menuItemHelpHelp.setMnemonic('L');
		menuItemHelpHelp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK));
		menuItemHelpAbout = new JMenuItem("关于(W)");
		menuItemHelpAbout.setMnemonic('W');
		menuItemHelpAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
		menuHelp.add(menuItemHelpHelp);
		menuHelp.add(menuItemHelpAbout);
		menuItemHelpHelp.addActionListener(this);
		menuItemHelpAbout.addActionListener(this);

		menuBar.add(menuFile);
		menuBar.add(menuFormat);
		menuBar.add(menuHelp);
		setJMenuBar(menuBar);
		getContentPane().add(label, BorderLayout.SOUTH);
		getContentPane().add(scrollPane, BorderLayout.CENTER);

		fileDialog_Open = new FileDialog(this, "打开", FileDialog.LOAD);
		fileDialog_Open.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				fileDialog_Open.setVisible(false);
			}
		});
		fileDialog_Save = new FileDialog(this, "保存", FileDialog.SAVE);
		fileDialog_Save.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				fileDialog_Save.setVisible(false);
			}
		});
	}

	// 打开文件
	public void open() {
		fileDialog_Open.setVisible(true);
		filedir = fileDialog_Open.getDirectory();
		filename = fileDialog_Open.getFile();
		if (filename != null) { // 判断打开的文件是否存在
			file = new File(filedir, filename);
			try {
				BufferedInputStream bread = new BufferedInputStream(new FileInputStream(file));
				byte[] gbyte = new byte[bread.available()];
				bread.read(gbyte, 0, gbyte.length);
				textPane.setText(new String(gbyte));
				bread.close();

				label.setText("文件:" + file.getName() + " 已打开!");
			} catch (IOException e) {
				label.setText("打开文件:" + file.getName() + "失败!");
			}
		}

	}

	// 保存文件
	public void save() {
		String filedir, filename;
		fileDialog_Save.setVisible(true);
		filedir = fileDialog_Save.getDirectory();
		filename = fileDialog_Save.getFile();
		if (filename != null) {
			file = new File(filedir, filename);
			try {
				BufferedOutputStream bsave = new BufferedOutputStream(new FileOutputStream(file));
				byte[] gbyte = (textPane.getText()).getBytes();
				bsave.write(gbyte, 0, gbyte.length);
				bsave.close();

				label.setText("文件:" + file.getName() + " 已保存!");
			} catch (IOException ex) {
				label.setText("保存文件:" + file.getName() + "失败!");
			}
		}

	}

	// 设置字体,颜色,粗体,斜体或清除格式
	public void setFontAndColor(int choice) {
		Font font;
		Color color = textPane.getForeground();
		StyleContext style = StyleContext.getDefaultStyleContext();
		AttributeSet attribute = textPane.getParagraphAttributes();
		switch (choice) {
		case 1:
			selectFont();
			break;
		case 2:
			color = JColorChooser.showDialog(null, "选择文字颜色", textPane.getForeground());
			if (color != null)
				attribute = style.addAttribute(attribute, StyleConstants.Foreground, color);
			else
				return;
			break;
		case 3:
			attribute = style.addAttribute(attribute, StyleConstants.Bold, true);
			break;
		case 4:
			attribute = style.addAttribute(attribute, StyleConstants.Italic, true);
			break;
		case 5:
			font = textPane.getFont();
			attribute = style.addAttribute(attribute, StyleConstants.Foreground, Color.BLACK);
			attribute = style.addAttribute(attribute, StyleConstants.Family, font.getFamily());
			attribute = style.addAttribute(attribute, StyleConstants.FontSize, font.getSize());
			attribute = style.addAttribute(attribute, StyleConstants.Bold, false);
			attribute = style.addAttribute(attribute, StyleConstants.Italic, false);
		default:
			break;
		}
		String str = textPane.getSelectedText();
		if (choice != 1) // 字体已在selectFont()替换
			textPane.setCharacterAttributes(attribute, false);
		if (str != null) {
			if (str.length() < 35)
				label.setText("选定文字:“" + str + "”已经替换");
			else
				label.setText("选定文字:“" + str.substring(0, 35) + "……”已经替换");
		}
	}

	// 选择字体
	public void selectFont() {
		int i;

		fontFrame = new Frame("字体");
		fontFrame.setVisible(true);
		fontFrame.setLayout(null);
		fontFrame.setSize(390, 300);
		fontFrame.setLocation((1366 - 390) / 2, (768 - 300) / 2);
		fontFrame.setResizable(false);
		// fontFrame.addMouseListener(mouseListener.mousePressed(e));

		labelname = new JLabel("字体:");
		labeltype = new JLabel("字形:");
		labelsize = new JLabel("字号:");
		labelshow = new JLabel("示例:");
		textshow = new TextArea("示例文字TEXTtext");
		fontFrame.add(labelname);
		fontFrame.add(labeltype);
		fontFrame.add(labelsize);
		fontFrame.add(labelshow);
		fontFrame.add(textshow);
		labelname.setBounds(20, 40, 100, 20);
		labeltype.setBounds(165, 40, 100, 20);
		labelsize.setBounds(300, 40, 60, 20);
		labelshow.setBounds(20, 210, 40, 20);
		textshow.setBounds(70, 190, 280, 70);

		// 字体名
		listname = new List();
		for (i = 0; i < name.length; ++i) {
			listname.add(name[i]);
		}
		listname.select(75);
		fontFrame.add(listname);
		listname.setBounds(20, 90, 120, 90);

		// 字形
		listtype = new List();
		for (i = 0; i < type.length; ++i) {
			listtype.add(type[i]);
		}
		listtype.select(0);
		fontFrame.add(listtype);
		listtype.setBounds(165, 90, 100, 90);

		// 字号
		listsize = new List();
		for (i = 0; i < size.length; ++i) {
			listsize.add(size[i]);
		}
		listsize.select(6);
		fontFrame.add(listsize);
		listsize.setBounds(300, 90, 80, 90);

		tfname = new TextField("Dialog");
		tftype = new TextField("常规");
		tfsize = new TextField("12");
		fontFrame.add(tfname);
		fontFrame.add(tftype);
		fontFrame.add(tfsize);
		tfname.setBounds(20, 65, 120, 20);
		tftype.setBounds(165, 65, 100, 20);
		tfsize.setBounds(300, 65, 80, 20);

		// 确定,取消按钮
		buttonOk = new Button("确定");
		buttonCancel = new Button("取消");
		fontFrame.add(buttonOk);
		fontFrame.add(buttonCancel);
		buttonOk.setBounds(140, 270, 40, 20);
		buttonCancel.setBounds(200, 270, 40, 20);

		listname.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				Font oldFont;
				oldFont = textshow.getFont();
				aname = listname.getSelectedItem();
				tfname.setText(listname.getSelectedItem());
				textshow.setFont(new Font(aname, oldFont.getStyle(), oldFont.getSize()));
			}
		});

		listtype.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				oldFont = textshow.getFont();
				if (listtype.getSelectedItem() == "常规") {
					atype = Font.PLAIN;
				} else if (listtype.getSelectedItem() == "加粗") {
					atype = Font.BOLD;
				} else if (listtype.getSelectedItem() == "倾斜") {
					atype = Font.ITALIC;
				} else {
					atype = 3;
				}
				tftype.setText(listtype.getSelectedItem());
				textshow.setFont(new Font(oldFont.getName(), atype, oldFont.getSize()));
			}
		});

		listsize.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				oldFont = textshow.getFont();
				asize = Integer.parseInt(listsize.getSelectedItem());
				tfsize.setText(listsize.getSelectedItem());
				textshow.setFont(new Font(oldFont.getName(), oldFont.getStyle(), asize));
			}
		});

		buttonOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				oldFont = textshow.getFont();
				newFont = new Font(oldFont.getName(), oldFont.getStyle(), oldFont.getSize());
				exit = true;
				fontFrame.dispose();
				StyleContext style = StyleContext.getDefaultStyleContext();
				AttributeSet attribute = textPane.getParagraphAttributes();
				attribute = style.addAttribute(attribute, StyleConstants.Family, newFont.getFontName());
				attribute = style.addAttribute(attribute, StyleConstants.FontSize, newFont.getSize());
				attribute = style.addAttribute(attribute, StyleConstants.Bold, newFont.isBold());
				attribute = style.addAttribute(attribute, StyleConstants.Italic, newFont.isItalic());
				textPane.setCharacterAttributes(attribute, false);
			}
		});

		buttonCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fontFrame.dispose();
			}
		});
	}

	// 选择的动作
	public void actionPerformed(ActionEvent actionEvent) {
		if (actionEvent.getSource() == menuItemFileOpen) {
			open();
		} else if (actionEvent.getSource() == menuItemFileSave) {
			save();
		} else if (actionEvent.getSource() == menuItemFileExit) {
			dispose();
			System.exit(0);
		} else if (actionEvent.getSource() == menuItemFormatFont) {
			setFontAndColor(1);
		} else if (actionEvent.getSource() == menuItemFormatColor) {
			setFontAndColor(2);
		} else if (actionEvent.getSource() == menuItemFormatTypeB) {
			setFontAndColor(3);
		} else if (actionEvent.getSource() == menuItemFormatTypeI) {
			setFontAndColor(4);
		} else if (actionEvent.getSource() == menuItemFormatClear) {
			setFontAndColor(5);
		} else if (actionEvent.getSource() == menuItemHelpHelp) {
			JOptionPane.showMessageDialog(null, help, "帮助", JOptionPane.INFORMATION_MESSAGE);
		} else if (actionEvent.getSource() == menuItemHelpAbout) {
			JOptionPane.showMessageDialog(null, about, "关于", JOptionPane.INFORMATION_MESSAGE);
		}
	}

	public static void main(String args[]) {
		// 使用Windows的界面风格
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}
		NotePad notePad = new NotePad();
		notePad.setVisible(true);
	}
}

你可能感兴趣的:(java)