java记事本

时间:2022-09-19 08:11:04

新知识点

1.撤销

textArea添加一个实现监听接口的类(添加了之后可以一直监视着添加的删除的情况,以便来撤销

        textArea.getDocument().addUndoableEditListener(
new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent e) {
undoManager.addEdit(e.getEdit());
updateButtons();
}
});

再弄一个管理监听的类,可以撤销和恢复

UndoManager undoManager = new UndoManager();

        undoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
undoManager.undo();
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
updateButtons();
}
}); redoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
undoManager.redo();
} catch (CannotRedoException cre) {
cre.printStackTrace();
}
updateButtons();
}
});

2删除选中的文本

            int start = text.getSelectionStart();
int end =text.getSelectionEnd();
text.replaceRange("", start, end); // 删除被选取的文本。

3设置时间格式

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String s=df.format(new Date());

4激活自动换行

                text.setLineWrap(true);//激活自动换行功能
text.setWrapStyleWord(true);//激活断行不断字功能(有单词会跳

5设置字体

font.setAccelerator(KeyStroke.getKeyStroke('a'));//点开菜单单键
font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));//使用组合键
font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0));//全局不用组合键

6打包后文件路径有错

因为打包后文件路径变了,要用URL来获得资源,由于,getClass().getResource是Object类的,可以用this调用

        URL url = this.getClass().getResource("/2.png");
ImageIcon addIcon = new ImageIcon(url);
about.setIcon(addIcon);

java记事本

bug:

1选中文本换颜色不能实现

全部代码

package testWin;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class FontDialog extends JDialog implements ListSelectionListener,ActionListener {
FontFamilyNames fontFamilyNames;
int fontSize=12;
int fontStyle=0;
String fontName="宋体"; JList fontNameList,fontSizeList,fontStyleList; Font font;
JButton yes,cancel;
static int YES=1,NO=0;
int state=-1;
FontDialog(JFrame f) {
super(f);
setTitle("字体对话框");
//font=new Font("宋体",Font.PLAIN,12);
fontFamilyNames=new FontFamilyNames();
setModal(true);//当前对话框调用setModal(boolean b)设置为有模式 //字体列表框:
String[] name=fontFamilyNames.getFontName();
fontNameList=new JList();
fontNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontNameList.setListData(name);
fontNameList.setVisibleRowCount(8);
//设置列表框第一条被选中
fontNameList.setSelectedIndex(0);
//添加滚动条
JScrollPane p1=new JScrollPane(fontNameList);
fontNameList.addListSelectionListener(this); //字形列表框:
String[] style={"常规 ","粗体","斜体","粗斜体"};
fontStyleList=new JList();
fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontStyleList.setListData(style);
fontStyleList.setVisibleRowCount(8);
fontStyleList.setSelectedIndex(0);
JScrollPane p2=new JScrollPane(fontStyleList);
fontStyleList.addListSelectionListener(this); //大小列表框:
String[] size={"8 ","10","12","14","16","18","20","22","24","26","28","30","32"};
fontSizeList=new JList();
fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
fontSizeList.setListData(size);
fontSizeList.setVisibleRowCount(8);
fontSizeList.setSelectedIndex(0);
JScrollPane p3=new JScrollPane(fontSizeList);
fontSizeList.addListSelectionListener(this); JPanel listPanel=new JPanel();
listPanel.add(p1);
listPanel.add(p2);
listPanel.add(p3);
add(listPanel,BorderLayout.NORTH); yes=new JButton("确定");
cancel=new JButton("取消");
yes.addActionListener(this);
cancel.addActionListener(this);
JPanel pSouth=new JPanel();
pSouth.add(yes);
pSouth.add(cancel);
add(pSouth,BorderLayout.SOUTH); setBounds(250,150,400,250);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
validate();
}
public void valueChanged(ListSelectionEvent e){
if(e.getSource()==fontNameList) {
fontName=(String)fontNameList.getSelectedValue();
}
else if(e.getSource()==fontStyleList) {
fontStyle=fontStyleList.getSelectedIndex();
}
else if(e.getSource()==fontSizeList) {
String s=(String)fontSizeList.getSelectedValue();
fontSize=Integer.parseInt(s.trim());
}
font=new Font(fontName,fontStyle,fontSize);
validate();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==yes) {
state=YES;
setVisible(false); //对话框设置为不可见
}
else if(e.getSource()==cancel) {
state=NO;
setVisible(false);
}
}
public int getState() {
return state;
}
public Font getFont() {
return font;
}
}
package testWin;

import java.awt.GraphicsEnvironment;
public class FontFamilyNames {
String allFontNames[];
public String [] getFontName() {
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
allFontNames=ge.getAvailableFontFamilyNames();
return allFontNames;
}
}
package testWin;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.undo.UndoManager; public class Polish implements ActionListener{
JFileChooser file1=new JFileChooser();
FileNameExtensionFilter filter=new FileNameExtensionFilter("txt文件","txt");//文件名过滤
private JTextArea text;
private int huanhang=0;//换行参数
UndoManager undoManager;
private JFrame frame;
void setFrame(JFrame a){
frame=a;
}
void setText(JTextArea a){
text=a;
}
void setUnodManager(UndoManager a){
undoManager=a;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
if(e.getActionCommand().equals("撤销")){
undoManager.undo();
}else if(e.getActionCommand().equals("剪贴")){
text.cut();
}else if(e.getActionCommand().equals("复制")){
text.copy();
}else if(e.getActionCommand().equals("粘贴")){
text.paste();
}else if(e.getActionCommand().equals("删除")){
int start = text.getSelectionStart();
int end =text.getSelectionEnd();
text.replaceRange("", start, end); // 删除被选取的文本。
// String s=text.getText(); 方法2
// String a=text.getSelectedText();
// text.setText(s.replace(a,""));
}else if(e.getActionCommand().equals("全选")){
text.selectAll();
}else if(e.getActionCommand().equals("时间/日期")){
Calendar calendar=Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String s=df.format(new Date());
text.append(s);
}else if(e.getActionCommand().equals("自动换行")){
if(huanhang%2==0){
text.setLineWrap(true);//激活自动换行功能
text.setWrapStyleWord(true);//激活断行不断字功能(有单词会跳
}else{
text.setLineWrap(false);
text.setWrapStyleWord(false);
}
huanhang++;
}else if(e.getActionCommand().equals("颜色")){
Color color2=new Color(120,30,0);
Color color1=JColorChooser.showDialog(frame,"color",color2);
text.setForeground(color1);
text.setSelectedTextColor(color1);
// JColorChooser jc=new JColorChooser();
// Color color3=jc.showDialog(null,"zb",color2);
// text.setSelectedTextColor(color3);
}else if(e.getActionCommand().equals("字体")){
FontDialog dialog1=new FontDialog(frame);
dialog1.setVisible(true);
Font font1=dialog1.getFont();
text.setFont(font1);
}else if(e.getActionCommand().equals("关于笔记本")){
JOptionPane.showMessageDialog(frame, "2015118043,黄煜成,2016/11/17完成");
}else if(e.getActionCommand().equals("打开")){
file1.setFileFilter(filter);//过滤下
int state=file1.showOpenDialog(frame);
if(state==JFileChooser.APPROVE_OPTION){
try{
File dir=file1.getSelectedFile();
FileReader fileReader=new FileReader(dir);
BufferedReader in1=new BufferedReader(fileReader);
text.setText(null);
String s=null;
for(;(s=in1.readLine())!=null;){
text.append(s+"\n");
}
in1.close();
fileReader.close();
}
catch(Exception e1){
System.out.println(e1.getMessage());
}
}
}else if(e.getActionCommand().equals("另存为")){
file1.setFileFilter(filter);//过滤下
int state=file1.showSaveDialog(frame);//显示出保存框
if(state==JFileChooser.APPROVE_OPTION){
try{
File dir=file1.getCurrentDirectory();//得到保存路径
String name=file1.getSelectedFile().getName();//得到选择的的名字
File file=new File(dir,name);
FileWriter fileWriter=new FileWriter(file);
BufferedWriter out1=new BufferedWriter(fileWriter);
out1.write(text.getText());
out1.close();
fileWriter.close();
}
catch(IOException e3){
System.out.println(e3.getMessage());
}
}
}
else if(e.getActionCommand().equals("新建")){
int n = 0;
if(text.getText()!="")
n=JOptionPane.showConfirmDialog(frame, "是否保存");
if(n==JOptionPane.YES_OPTION){ file1.setFileFilter(filter);//过滤下
int state=file1.showSaveDialog(frame);//显示出保存框
if(state==JFileChooser.APPROVE_OPTION){
try{
File dir=file1.getCurrentDirectory();//得到保存路径
String name=file1.getSelectedFile().getName();//得到选择的的名字
File file=new File(dir,name);
FileWriter fileWriter=new FileWriter(file);
BufferedWriter out1=new BufferedWriter(fileWriter);
out1.write(text.getText());
out1.close();
fileWriter.close();
}
catch(IOException e3){
System.out.println(e3.getMessage());
}
}
}
else if(n==JOptionPane.NO_OPTION){
text.setText(null);
}
}else if(e.getActionCommand().equals("退出")){
System.exit(0);
}else if(e.getActionCommand().equals("保存")){
System.out.println("1111");
File file1=new File ("新建保存文件.txt");
if(!file1.exists())
try {
file1.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
FileWriter fileWriter=new FileWriter(file1);
BufferedWriter out1=new BufferedWriter(fileWriter);
out1.write(text.getText());
out1.close();
fileWriter.close();
}
catch(Exception e5){
System.out.println(e5.getMessage());
}
}
}
}
package testWin;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL; import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import javax.swing.undo.UndoManager; public class Text extends JFrame { private JPanel contentPane;
JTextArea textArea = new JTextArea();
UndoManager undoManager = new UndoManager();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Text frame = new Text();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public Text() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 681, 570); JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar); JMenu file = new JMenu("\u6587\u4EF6");
menuBar.add(file); JMenuItem newFile = new JMenuItem("\u65B0\u5EFA");
newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
file.add(newFile); JMenuItem openFile = new JMenuItem("\u6253\u5F00");
openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
file.add(openFile); JMenuItem saveFile = new JMenuItem("\u4FDD\u5B58");
saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
file.add(saveFile); JMenuItem save2File = new JMenuItem("\u53E6\u5B58\u4E3A");
save2File.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK));
file.add(save2File); JMenuItem print = new JMenuItem("\u6253\u5370");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
file.add(print); JMenuItem close = new JMenuItem("\u9000\u51FA");
close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
file.add(close); JMenu menu = new JMenu("\u7F16\u8F91");
menuBar.add(menu); JMenuItem revoke = new JMenuItem("\u64A4\u9500");
revoke.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK));
menu.add(revoke); JMenuItem clip = new JMenuItem("\u526A\u8D34");
clip.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
menu.add(clip); JMenuItem copy = new JMenuItem("\u590D\u5236");
copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
menu.add(copy); JMenuItem paste = new JMenuItem("\u7C98\u8D34");
paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));
menu.add(paste); JMenuItem delete = new JMenuItem("\u5220\u9664");
delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK));
menu.add(delete); JMenuItem selectAll = new JMenuItem("\u5168\u9009");
selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
menu.add(selectAll); JMenuItem date = new JMenuItem("\u65F6\u95F4/\u65E5\u671F");
menu.add(date); JMenu format = new JMenu("\u683C\u5F0F");
menuBar.add(format); JMenuItem autoNextLine = new JMenuItem("\u81EA\u52A8\u6362\u884C");
autoNextLine.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
format.add(autoNextLine); JMenuItem font = new JMenuItem("\u5B57\u4F53");
font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
format.add(font); JMenuItem color = new JMenuItem("\u989C\u8272");
format.add(color); JMenu help = new JMenu("\u5E2E\u52A9");
menuBar.add(help); JMenuItem about = new JMenuItem("\u5173\u4E8E\u7B14\u8BB0\u672C");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK)); URL url = this.getClass().getResource("/2.png");
ImageIcon addIcon = new ImageIcon(url);
about.setIcon(addIcon); help.add(about);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(textArea); Polish polish1=new Polish();//锟斤拷锟斤拷锟斤拷
UndoPolish undo=new UndoPolish();//锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
textArea.getDocument().addUndoableEditListener(undo);//锟斤拷映锟斤拷锟斤拷锟斤拷锟� undo.setUnodManager(undoManager);
polish1.setText(textArea);
polish1.setUnodManager(undoManager);//锟斤拷锟捷癸拷锟斤拷锟斤拷
polish1.setFrame(this); revoke.addActionListener(polish1);//锟斤拷蛹锟斤拷锟�
clip.addActionListener(polish1);
copy.addActionListener(polish1);
paste.addActionListener(polish1);
delete.addActionListener(polish1);
selectAll.addActionListener(polish1);
date.addActionListener(polish1); autoNextLine.addActionListener(polish1);
color.addActionListener(polish1);
font.addActionListener(polish1); about.addActionListener(polish1); openFile.addActionListener(polish1);
save2File.addActionListener(polish1);
newFile.addActionListener(polish1);
close.addActionListener(polish1);
saveFile.addActionListener(polish1);
}
public ImageIcon getMyImage(String imageName){
ClassLoader loader = getClass().getClassLoader();
java.io.InputStream is = loader.getResourceAsStream(imageName);
Image img;
ImageIcon ii = null;
try {
img = ImageIO.read(is);
ii = new ImageIcon(img);
return ii;
} catch (IOException e) {
e.printStackTrace();
}
return ii;
} }
package testWin;

import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager; public class UndoPolish implements UndoableEditListener{
UndoManager undoManager;
void setUnodManager(UndoManager a){
undoManager=a;
} @Override
public void undoableEditHappened(UndoableEditEvent e) {
// TODO 自动生成的方法存根
undoManager.addEdit(e.getEdit());
} }

java记事本的更多相关文章

  1. JAVA记事本的图形用户界面应用程序含过滤

    JAVA记事本的图形用户界面应用程序 过滤 题目简介: 整体分析: 实验代码: package note; import java.awt.EventQueue; import java.awt.ev ...

  2. JAVA记事本的图形用户界面应用程序含加密

    JAVA记事本的图形用户界面应用程序 加密 题目简介: 整体分析: 实验代码: import java.awt.EventQueue; import java.awt.event.ActionEven ...

  3. JAVA记事本的图形用户界面应用程序

    JAVA记事本的图形用户界面应用程序 整体分析: 代码实现: import java.awt.EventQueue; import java.awt.event.ActionEvent; import ...

  4. java 记事本 - 实例

    记事本记事本实例中使用了以下知识1.ui界面2.io流3.事件监听4.图形5.JFileChooser 类,用于打开文件,另存为文件.弹出文件选择器对话框 学习重点:JFileChooser,有很多方 ...

  5. java记事本1.2版

    功能:实现了新建,打开,保存,退出,复制,剪切,粘贴等功能 效果图:

  6. java记事本开发

    今天我想要分享的是一个用java写的一个记事本程序.我知道现在市面上有各种各样的记事本了,但是我发现有的写的功能不够完善,或者是代码层次结构不够清晰,有的甚至看了之后云里雾里的,有的还不乏了非常明显的 ...

  7. Java记事本编译

    配置环境: 在“系统变量”栏下执行三项操作:①新建“Java_Home”,设置其值为 JDK所在的绝对路径,如果你的事刚才的默认路径,那值为:C:\Program Files\Java\jdk1.7. ...

  8. Java记事本编写第一个程序“你好,世界”

  9. java基础 swing编程实战

    1. 实现金山词霸,点击左右收缩 效果图: exmaple code : /* * 词霸 * */ package demo7; import java.awt.*; import java.awt. ...

随机推荐

  1. YII2.0 Activeform表单组件的使用方法

    Activeform文本框:textInput();密码框:passwordInput();单选框:radio(),radioList();复选框:checkbox(),checkboxList(); ...

  2. Django + Apache + 树莓派 搭建内网微信公众号服务器

    其实早在微信开放公众号开发平台时就想弄一个自己的公众号服务器,奈何对web服务器搭建和开发一窍不通,只是注册了一下开发者帐号,并没有采取行动,万恶的拖延症. 前一年,开始接触python,打开了神奇世 ...

  3. C 结构体位域

    位域 : 有些信息在存储时,并不需要占用一个完整的字节, 而只需占几个或一个二进制位.例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可.为了节省存储空间,并使处理简便,C语言又提供了一 ...

  4. CentOS 6.5安装配置LNMP服务器(Nginx+PHP+MySQL)

    CentOS 6.5安装配置LNMP服务器(Nginx+PHP+MySQL) 一.准备篇: /etc/init.d/iptables stop #关闭防火墙 关闭SELINUX vi /etc/sel ...

  5. [C#]『Barrier』任务并行库使用小计

    Barrier  是一个对象,它可以在并行操作中的所有任务都达到相应的关卡之前,阻止各个任务继续执行. 如果并行操作是分阶段执行的,并且每一阶段要求各任务之间进行同步,则可以使用该对象. --MSDN ...

  6. [精品书单]word排版设计

  7. RSA javascript加密 lua解密

    一个在线RSA非对称加密解密,可以用这个地址生成公钥和私钥 https://blog.zhengxianjun.com/online-tool/rsa/ javascript加密 jsencrypt. ...

  8. Day4--------------对文件的权限管理

    一.文件权限 ls -l         显示当前文件详细信息 例: -rw-r--rwx.1 root root 1415 11月 9 20:21 anaconda-ks.cfg 依次顺序为:权限信 ...

  9. operator笔记

    # operator.itemgetter(*items) # 获取item >>> from operator import itemgetter # list使用下标进行返回 & ...

  10. AngularJS directive 不执行

    检查下directive的命名,是不是含有特殊符号和大写,全部改为小写就ok: 原因:html不支持骆驼峰命名,只支持小写: