本来是Java课做一个仿windows记事本的实验,后来突然脑子一热,结果就给它加了一个编译运行Java文件的功能。
本工程总共大约3000行代码,基本上把所学的java界面、文件、控件的功能都包含在内啦。除此之外俺还脑子一热给这个文本编辑器加了个可以编译运行java文件的功能,但是由于多线程还不咋滴,所以有些需要在DOS输入的java文件就无法运行啦。
现在过了一个寒假,好像有点忘了,所以拿出来研究一下,顺便写个博客,全做复习一下java啦,嘻嘻>_<!
notepad包:
1、关于对话框 :介绍软件运行环境作者,版权声明。这里用JDialog便于生成模式窗口,用2个JButton一个是OK按钮,一个是无边框图标,用4个Jlable来显示文字(这里涉及字体颜色,字体设置)。更多介绍请看代码:(可单独运行)
package notepad;
//about 对话框
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel; public class AboutDialog implements ActionListener{
public JDialog Dialog;
public JButton OK,Icon;
public JLabel Name,Version,Author,Java;
public JPanel Panel;
AboutDialog(JFrame notepad, int x, int y) {//构造函数(父窗口,x,y)
//实例化界面控件
Dialog=new JDialog(notepad,"About Notepad...",true);//用JDialog便于写出模式窗口
OK=new JButton("OK");
Icon=new JButton(new ImageIcon("50.png"));
Name=new JLabel("Notepad");
Version=new JLabel("Version 1.0");
Java=new JLabel("JRE Version 6.0");
Author=new JLabel("Copyright (c) 2013-11-30 TaoLi. No rights reserved.");
Panel=new JPanel();//用一个JPanel使界面显得更美观
Color c=new Color(0,95,191);//颜色构造函数(r,g,b)
//美化界面控件
Name.setForeground(c);//字体前景颜色
Version.setForeground(c);
Java.setForeground(c);
Panel.setBackground(Color.WHITE);//Panel设为白色
OK.setFocusable(false);
Dialog.setSize(280, 180);//控件设置大小
Dialog.setLocation(x, y);//控件设置位置
Dialog.setResizable(false);//大小不可变
Dialog.setLayout(null);
Panel.setLayout(null);
OK.addActionListener(this);//给按钮加入监听
Icon.setFocusable(false);
Icon.setBorderPainted(false);//无边框处理
Author.setFont(new Font(null,Font.PLAIN,11));//设置字体
//组合各个控件并设置各自大小
Panel.add(Icon);//加入托盘
Panel.add(Name);
Panel.add(Version);
Panel.add(Author);
Panel.add(Java);
Dialog.add(Panel);//加入主界面
Dialog.add(OK);
Panel.setBounds(0, 0, 280, 100);//Panel大小设置
OK.setBounds(180, 114, 72, 26);//OK大小设置
Name.setBounds(80, 10, 160, 20);
Version.setBounds(80, 27, 160, 20);
Author.setBounds(15, 70, 250, 20);
Java.setBounds(80, 44, 160, 20);
Icon.setBounds(16, 14, 48, 48);
}
public void actionPerformed(ActionEvent e) {//事件监听
Dialog.setVisible(false);
Dialog.dispose();
}
public static void main(String args[]){//测试用的main函数
JFrame f=new JFrame();
AboutDialog a=new AboutDialog(f,400,400);
a.Dialog.setVisible(true);
}
}
AboutDialog.java
2、颜色选择对话框: 主要为主窗口的文字的前景和背景颜色设置,主窗口的背景和选中时的背景颜色设置;其中第二个窗口负责选择颜色(也可直接输入RGB值)。这里窗口1上半部分主要由4个JLable用于文字显示,4个JButton用于分别功能选择,2个JTextArea用于显示效果;窗口2用了2维的按钮矩阵[16][16]来显示颜色。这里设置好的颜色值分别保存在public Color NFC,NBC,SFC,SBC;//4个颜色中,当其他函数调用时可以通过访问这些值来做相关操作;此外这里还把选择的数据保存在文件里了,刚开始初始化和数据改变都涉及文件操作。更多介绍请看代码:(可单独运行)
package notepad;
//2个窗口,2个类
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.RandomAccessFile; import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField; public class ColorDialog implements ActionListener, WindowListener{
public JDialog Dialog;
public JLabel NFL,NBL,SFL,SBL;//4个label
public JTextArea Normal,Selected;//2个文本显示
public JButton NFB,NBB,SFB,SBB,OK,Cancel,Reset;//7个按钮
public Color NFC,NBC,SFC,SBC;//4个颜色
public ColorChooser Chooser;//1个颜色选择自定义类实例
private RandomAccessFile file;//存储颜色文件
public ColorDialog(JFrame notepad, int x, int y){//构造函数(父类,x,y)
try {//初始化信息,从保存文件读取
file=new RandomAccessFile("D:\\colorData.txt","rw");
if(file.length()!=0){
NFC=new Color(file.readInt(),file.readInt(),file.readInt());//初始化四种颜色
NBC=new Color(file.readInt(),file.readInt(),file.readInt());
SFC=new Color(file.readInt(),file.readInt(),file.readInt());
SBC=new Color(file.readInt(),file.readInt(),file.readInt());
}else{
NFC=new Color(0,0,0);//初始化四种颜色
NBC=new Color(249,249,251);
SFC=new Color(0,0,0);
SBC=new Color(191,207,223);
}
if(file!=null)file.close();
} catch (Exception e) {
e.printStackTrace();
}
//实例化组建
Dialog=new JDialog(notepad,"Color...",true);
NFL=new JLabel("Normal Foreground:");//初始化四个jlable
NBL=new JLabel("Normal Background:");
SFL=new JLabel("Selected Foreground:");
SBL=new JLabel("Selected Background:");
Normal=new JTextArea("\n Normal 正常");//2个文本显示区
Selected=new JTextArea("\n Selected 选中 ");
NFB=new JButton("");//四个颜色选择按钮
NBB=new JButton("");
SFB=new JButton("");
SBB=new JButton("");
OK=new JButton("OK");//3个逻辑按钮
Cancel=new JButton("Cancel");
Reset=new JButton("Reset");
Chooser=new ColorChooser(Dialog, x+65, y-15);//一个颜色选择器
//各个组件设置
Normal.setEditable(false);//设置1文本显示区不可编辑
Normal.setFocusable(false);
Normal.setFont(new Font("新宋体", 0, 16));//初始化文本显示区
Normal.setForeground(NFC);
Normal.setBackground(NBC);
Selected.setEditable(false);//设置2文本显示区不可编辑
Selected.setFocusable(false);
Selected.setFont(Normal.getFont());//初始化文本显示区
Selected.setForeground(SFC);
Selected.setBackground(SBC);
NFB.setBackground(NFC);//设置4个颜色选择按钮颜色
NBB.setBackground(NBC);
SFB.setBackground(SFC);
SBB.setBackground(SBC);
Dialog.setLayout(null);
Dialog.setLocation(x, y);
Dialog.setSize(410, 220);
Dialog.setResizable(false);
Reset.setFocusable(false);
OK.setFocusable(false);
Cancel.setFocusable(false);
//组建组合并设置位置大小
Dialog.add(Normal);
Dialog.add(Selected);
Dialog.add(NFL);
Dialog.add(NBL);
Dialog.add(SFL);
Dialog.add(SBL);
Dialog.add(SBB);
Dialog.add(SFB);
Dialog.add(NBB);
Dialog.add(NFB);
Dialog.add(OK);
Dialog.add(Cancel);
Dialog.add(Reset);
SBB.setBounds(144, 100, 60, 22);
SFB.setBounds(144, 70, 60, 22);
NBB.setBounds(144, 40, 60, 22);
NFB.setBounds(144, 10, 60, 22);
NFL.setBounds(10, 10, 130, 22);
NBL.setBounds(10, 40, 130, 22);
SFL.setBounds(10, 70, 130, 22);
SBL.setBounds(10, 100, 130, 22);
Normal.setBounds(220, 10, 174, 56);
Selected.setBounds(220, 66, 174, 56);
Reset.setBounds(10, 160, 74, 24);
OK.setBounds(236, 160, 74, 24);
Cancel.setBounds(320, 160, 74, 24);
Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Dialog.addWindowListener(this);//屏幕监听
//7个按钮监听
NFB.addActionListener(this);
NBB.addActionListener(this);
SFB.addActionListener(this);
SBB.addActionListener(this);
Reset.addActionListener(this);
OK.addActionListener(this);
Cancel.addActionListener(this);
}
public void setTextAreaColor(){//将textArea的颜色设置为4个按钮的背景颜色
Normal.setForeground(NFB.getBackground());
Normal.setBackground(NBB.getBackground());
Selected.setForeground(SFB.getBackground());
Selected.setBackground(SBB.getBackground());
}//(获取组件背景颜色和设置组件背景颜色)
public void cancel(){//cancel时调用的函数
Normal.setForeground(NFC);
Normal.setBackground(NBC);
Selected.setForeground(SFC);
Selected.setBackground(SBC);
NFB.setBackground(NFC);
NBB.setBackground(NBC);
SFB.setBackground(SFC);
SBB.setBackground(SBC);
Dialog.setVisible(false);
}
public void actionPerformed(ActionEvent e) {//事件监听函数(适合多事件的处理简洁方便)
Object obj=e.getSource();//通过资源比较的
if(obj==Reset){//恢复原来
NFB.setBackground(new Color(0,0,0));
NBB.setBackground(new Color(249,249,251));
SFB.setBackground(new Color(0,0,0));
SBB.setBackground(new Color(191,207,223));
setTextAreaColor();
}
else if(obj==OK){//更新
NFC=NFB.getBackground();
NBC=NBB.getBackground();
SFC=SFB.getBackground();
SBC=SBB.getBackground();
try {//数据写入文件
file=new RandomAccessFile("D:\\colorData.txt","rw");
file.writeInt(NFC.getRed());file.writeInt(NFC.getGreen());file.writeInt(NFC.getBlue());
file.writeInt(NBC.getRed());file.writeInt(NBC.getGreen());file.writeInt(NBC.getBlue());
file.writeInt(SFC.getRed());file.writeInt(SFC.getGreen());file.writeInt(SFC.getBlue());
file.writeInt(SBC.getRed());file.writeInt(SBC.getGreen());file.writeInt(SBC.getBlue());
if(file!=null)file.close();
} catch (Exception e1) {
e1.printStackTrace();
}
Dialog.setVisible(false);
}
else if(obj==Cancel)//取消
cancel();
else{//其他情况直接获取颜色并更新
Chooser.init(((Component) obj).getBackground());
Chooser.Dialog.setVisible(true);
((Component) obj).setBackground(Chooser.New.getBackground());
setTextAreaColor();
}
}
public void windowClosing(WindowEvent e) {//重定义窗口关闭操作
cancel();
}//必须加Dialog.addWindowListener(this);屏幕监听,并且所有接口都要实现
public void windowActivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {} public static void main(String args[]){//main函数,测试用
JFrame c=new JFrame();
ColorDialog a=new ColorDialog(c,400,400);
a.Dialog.setVisible(true);
}
} class ColorChooser implements ActionListener,WindowListener,KeyListener{
JDialog Dialog;
JButton Choice[][],Old,New,OK,Cancel;//结果保存在New的背景颜色中
JPanel Panel;
JTextField R,G,B;
JLabel OldLabel,NewLabel,RL,GL,BL;
ColorChooser(JDialog color,int x, int y){//构造函数(parent,x,y)
//实例化
Dialog=new JDialog(color,true);
Choice=new JButton[16][16];//颜色选择区按钮
Panel=new JPanel();
Old=new JButton("");
New=new JButton("");
OldLabel=new JLabel("Old:");
NewLabel=new JLabel("New:");
RL=new JLabel("R:");
GL=new JLabel("G:");
BL=new JLabel("B:");
R=new JTextField("");
G=new JTextField("");
B=new JTextField("");
OK=new JButton("OK");
Cancel=new JButton("Cancel");
//按钮的布局格式(表格布局)
Panel.setLayout(new GridLayout(16,16,0,0));//设置表格布局16x16.存放颜色选择按钮
int i=0,j=0;
Color c;
Choice[0 ][15]=new JButton("");Choice[0 ][15].setBackground(new Color(255,255,255));//设置按钮背景颜色
Choice[1 ][15]=new JButton("");Choice[1 ][15].setBackground(new Color(255,223,191));
Choice[2 ][15]=new JButton("");Choice[2 ][15].setBackground(new Color(255,207,207));
Choice[3 ][15]=new JButton("");Choice[3 ][15].setBackground(new Color(223,191,255));
Choice[4 ][15]=new JButton("");Choice[4 ][15].setBackground(new Color(207,207,255));
Choice[5 ][15]=new JButton("");Choice[5 ][15].setBackground(new Color(191,223,255));
Choice[6 ][15]=new JButton("");Choice[6 ][15].setBackground(new Color(207,255,207));
Choice[7 ][15]=new JButton("");Choice[7 ][15].setBackground(new Color(255, 0, 0));
Choice[8 ][15]=new JButton("");Choice[8 ][15].setBackground(new Color( 0,255, 0));
Choice[9 ][15]=new JButton("");Choice[9 ][15].setBackground(new Color( 0, 0,255));
Choice[10][15]=new JButton("");Choice[10][15].setBackground(new Color(255,255, 0));
Choice[11][15]=new JButton("");Choice[11][15].setBackground(new Color( 0,255,255));
Choice[12][15]=new JButton("");Choice[12][15].setBackground(new Color(255, 0,255));
Choice[13][15]=new JButton("");Choice[13][15].setBackground(new Color(255,255,223));
Choice[14][15]=new JButton("");Choice[14][15].setBackground(new Color(223,255,255));
Choice[15][15]=new JButton("");Choice[15][15].setBackground(new Color(255,223,255));
for(i=0;i<16;i++){
c=Choice[i][15].getBackground();//获取背景颜色
for(j=0;j<16;j++){
if(j!=15){
Choice[i][j]=new JButton("");
Choice[i][j].setBackground(new Color(c.getRed()*(j+1)/16,c.getGreen()*(j+1)/16,c.getBlue()*(j+1)/16));
}
Choice[i][j].setFocusable(false);//?
Choice[i][j].addActionListener(this);
Panel.add(Choice[i][j]);
}
}
//控件格式设置和监听
Dialog.setSize(280,250);
Dialog.setLayout(null);
Dialog.setLocation(x, y);
Dialog.setResizable(false);
Dialog.add(Panel);
Panel.setBounds(10, 10, 160, 160);
Dialog.add(Old);
Dialog.add(OldLabel);
Old.setEnabled(false);
Old.setBorderPainted(false);
Old.setBounds(214, 10, 44, 22);
OldLabel.setBounds(180, 10, 44, 22);
Dialog.add(New);
Dialog.add(NewLabel);
New.setEnabled(false);//不可按****
New.setBorderPainted(false);//无边界***
New.setBounds(214, 32, 44, 22);
NewLabel.setBounds(180, 32, 44, 22);
Dialog.add(R);
Dialog.add(G);
Dialog.add(B);
R.setBounds(214, 97, 44, 22);
G.setBounds(214, 123, 44, 22);
B.setBounds(214, 149, 44, 22);
Dialog.add(RL);
Dialog.add(GL);
Dialog.add(BL);
RL.setBounds(196, 97, 16, 22);
GL.setBounds(196, 123, 16, 22);
BL.setBounds(196, 149, 16, 22);
Dialog.add(OK);
Dialog.add(Cancel);
OK.setFocusable(false);
Cancel.setFocusable(false);
OK.setBounds(106, 190, 74, 24);
Cancel.setBounds(190, 190, 74, 24);
OK.addActionListener(this);
Cancel.addActionListener(this);
G.addKeyListener(this);
R.addKeyListener(this);
B.addKeyListener(this);
}
public void setText(Color c){//由颜色修改RGB的数值函数
R.setText(String.valueOf(c.getRed()));
G.setText(String.valueOf(c.getGreen()));
B.setText(String.valueOf(c.getBlue()));
}//(JTextField的文本设置)
public void init(Color c){//初始化颜色(new old 显示和RGB数值区)
New.setBackground(c);
Old.setBackground(c);
setText(c);
}
public void actionPerformed(ActionEvent e) {//总监听
Object obj=e.getSource();
if(obj==OK) Dialog.setVisible(false);
else if(obj==Cancel){//取消
New.setBackground(Old.getBackground());//设回原来值
Dialog.setVisible(false);
}
else{
New.setBackground(((Component) obj).getBackground());
setText(New.getBackground());
}
}
public void windowClosing(WindowEvent e) {//窗口关闭定义
New.setBackground(Old.getBackground());
Dialog.setVisible(false);
}
public void keyReleased(KeyEvent e) {//案件监听用于填写RGB数值并修改new显示
try{
int r,g,b;
if(R.getText().length()==0) r=0;
else r=Integer.valueOf(R.getText());
if(G.getText().length()==0) g=0;
else g=Integer.valueOf(G.getText());
if(B.getText().length()==0) b=0;
else b=Integer.valueOf(B.getText());
New.setBackground(new Color(r,g,b));
}
catch(NumberFormatException nfe){setText(New.getBackground());}//异常处理1
catch(IllegalArgumentException iae){setText(New.getBackground());}//2变回原来
}//(按键监听)
public void keyPressed(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void windowActivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {}
}
ColorDialog.java
3、确认对话框: 主要是在一些关键的步骤让用户确认是否进行操作的对话框。其选择的结果保存在state里面,外部函数可以访问这个值来查看用户的选择。更多介绍请看代码:(可单独运行)
package notepad;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel; public class EnsureDialog implements WindowListener, ActionListener{
public int YES,NO,CANCEL,Status;
public JDialog Ensure;
public JButton Yes,No,Cancel;
public JLabel Question;
public JPanel ButtonPanel,TextPanel;
EnsureDialog(JFrame notepad, int x, int y) {
YES=0;
NO=1;
CANCEL=2;
Status=CANCEL;
Ensure=new JDialog(notepad,true);/*
* 这里的模式标志true的作用是使对话框处于notepad的上端,并且当对话框显示时进程处于停滞状态,
* 直到对话框不再显示为止。在本程序中,由于对对话框进行了事件监听处理,当对话框消失时状态标
* 志Status同时发生了变化,这样就可以在进程继续时获得新的Status值 */
Yes=new JButton("Yes");//3个按钮
No=new JButton("No");
Cancel=new JButton("Cancel");
Question=new JLabel(" Do you want to save changes to the file?");//1个label
ButtonPanel=new JPanel();//按钮托盘
TextPanel=new JPanel();//文本托盘
ButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,16,10));//按钮居中上下间距16,左右间距10
TextPanel.setLayout(new BorderLayout());//充满
Ensure.setLayout(new BorderLayout());//充满
ButtonPanel.add(Yes);//3个按钮加入按钮托盘
ButtonPanel.add(No);
ButtonPanel.add(Cancel);
TextPanel.add(Question);//将文本加入文本托盘
Ensure.add(TextPanel,BorderLayout.CENTER);
Ensure.add(ButtonPanel,BorderLayout.SOUTH);
Ensure.setLocation(x, y);
Ensure.setSize(360, 140);
Ensure.setResizable(false);
TextPanel.setBackground(Color.WHITE);
Question.setFont(new Font(null,Font.PLAIN,16));
Question.setForeground(new Color(0,95,191));
Yes.setFocusable(false);
No.setFocusable(false);
Cancel.setFocusable(false);
Ensure.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Ensure.addWindowListener(this);//窗口监听
Yes.addActionListener(this);//个按钮监听
No.addActionListener(this);
Cancel.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==Yes) Status=YES;
else if(e.getSource()==No) Status=NO;
else if(e.getSource()==Cancel) Status=CANCEL;
Ensure.setVisible(false);
}
public void windowClosing(WindowEvent e){
Status=CANCEL;
Ensure.setVisible(false);
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {} public static void main(String args[]){
JFrame a=new JFrame();
EnsureDialog c=new EnsureDialog(a,400,400);
c.Ensure.setVisible(true);
}
}
EnsureDialog.java
4、查找与替换对话框:主要负责查找与替换。其功能部分不在这里,这里只是界面部分。更多介绍请看代码:(可单独运行)
package notepad;
import java.awt.TextField;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
//只是一个窗口,没有其他函数
public class FindAndReplace{
public JDialog Dialog;
public JButton FindNext,Replace,ReplaceAll,Finish;//4个按钮
public JCheckBox MatchCase;//1个CheckBox
public JRadioButton Up,Down;//1组单选按钮(上下)
public ButtonGroup DirectionGroup;
public JLabel FindWhat,ReplaceWith,Direction;//3个label
public TextField FindText,ReplaceText;//2个文本区
FindAndReplace(JFrame notepad){//构造函数
Dialog=new JDialog(notepad,"Find And Replace...",false);/*
* 与EnsureDialog不同的是,这里的模式标志false使对话框始终处于notepad的上端,但点击notepad
* 时notepad会继续处于活动状态,对话框则变成不活动状态 注意!!!*/
FindNext=new JButton("Find Next");//4个按钮实例
Replace=new JButton("Replace");
ReplaceAll=new JButton("Replace All");
Finish=new JButton("Finish");
MatchCase=new JCheckBox("Match Case",false);//1个CheckBox
Down=new JRadioButton("Down",true);//1组单选
Up=new JRadioButton("Up",false);
FindWhat=new JLabel("Find What:");//3个label
ReplaceWith=new JLabel("Replace With:");
Direction=new JLabel("Direction:");
FindText=new TextField("");//2个文本区
ReplaceText=new TextField("");
Dialog.setSize(380, 160);
Dialog.setResizable(false);
FindNext.setFocusable(false);//?
Replace.setFocusable(false);
ReplaceAll.setFocusable(false);
MatchCase.setFocusable(false);
Finish.setFocusable(false);
Up.setFocusable(false);
Down.setFocusable(false);
DirectionGroup=new ButtonGroup();
Dialog.setLayout(null);
FindWhat.setBounds(10,12,80,22);
ReplaceWith.setBounds(10,42,80,22);
FindText.setBounds(95, 12, 160, 22);
ReplaceText.setBounds(95, 42, 160, 22);
FindNext.setBounds(265, 12, 98, 22);
Replace.setBounds(265, 42, 98, 22);
ReplaceAll.setBounds(265, 72, 98, 22);
Direction.setBounds(10, 72, 80, 22);
MatchCase.setBounds(6, 102, 98, 22);
Down.setBounds(95, 72, 80, 22);
Up.setBounds(175, 72, 80, 22);
Finish.setBounds(265, 102, 98, 22);
DirectionGroup.add(Up);//单选加入group
DirectionGroup.add(Down);
Dialog.add(FindWhat);
Dialog.add(MatchCase);
Dialog.add(FindText);
Dialog.add(FindNext);
Dialog.add(Direction);
Dialog.add(ReplaceWith);
Dialog.add(ReplaceText);
Dialog.add(Replace);
Dialog.add(ReplaceAll);
Dialog.add(Finish);
Dialog.add(Down);
Dialog.add(Up);
}
public static void main(String args[]){
JFrame a=new JFrame();
FindAndReplace c=new FindAndReplace(a);
c.Dialog.setVisible(true);
}
}
FindAndReplace.java
5、字体选择对话框:主要负责字体设置。更多介绍请看代码:(可单独运行)
package notepad;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.RandomAccessFile; import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextArea; public class FontDialog implements ItemListener, ActionListener, WindowListener{
public JDialog Dialog;
public JCheckBox Bold,Italic;//2个CheckBox用于选择粗细和倾斜
public List Size,Name;//2个list用于列出字型和大小
public int FontName;
public int FontStyle;
public int FontSize;
public JButton OK,Cancel;//2个按钮
public JTextArea Text;//1个文本编辑区
private RandomAccessFile file;//存储字体文件
FontDialog(JFrame notepad, int x, int y){//构造函数
GraphicsEnvironment g=GraphicsEnvironment.getLocalGraphicsEnvironment();
String name[]=g.getAvailableFontFamilyNames();//获得系统字体
Bold=new JCheckBox("Bold",false);//粗细倾斜设为false
Italic=new JCheckBox("Italic",false);
Dialog=new JDialog(notepad,"Font...",true);
Text=new JTextArea("字体预览用例\n9876543210\nAaBbCcXxYyZz");
OK=new JButton("OK");
Cancel=new JButton("Cancel");
Size=new List();//实例化字形和大小列表
Name=new List();
int i=0;
Name.add("Default Value");
for(i=0;i<name.length;i++) Name.add(name[i]);//名字加进list
for(i=8;i<257;i++) Size.add(String.valueOf(i));//把字体加进list
try {//初始化信息,从保存文件读取
file=new RandomAccessFile("D:\\fontData.txt","rw");
if(file.length()!=0){
FontName=file.readInt();
FontStyle=file.readInt();
FontSize=file.readInt();
}else{
FontName=0;
FontStyle=0;
FontSize=0;
}
if(file!=null)file.close();
//System.out.print(file.readInt()+" ");
//System.out.print(file.readInt()+" ");
//System.out.print(file.readInt()+" ");
} catch (Exception e) {
e.printStackTrace();
}
Dialog.setLayout(null);
Dialog.setLocation(x, y);
Dialog.setSize(480, 306);
Dialog.setResizable(false);
OK.setFocusable(false);
Cancel.setFocusable(false);
Bold.setFocusable(false);
Bold.setSelected(FontStyle%2==1);
Italic.setFocusable(false);
Italic.setSelected(FontStyle/2==1);
Name.setFocusable(false);
Size.setFocusable(false);
Name.setBounds(10, 10, 212, 259);
Dialog.add(Name);
Bold.setBounds(314, 10, 64, 22);
Dialog.add(Bold);
Italic.setBounds(388, 10, 64, 22);
Dialog.add(Italic);
Size.setBounds(232, 10, 64, 259);
Dialog.add(Size);
Text.setBounds(306, 40, 157, 157);
Dialog.add(Text);
OK.setBounds(306, 243, 74, 26);
Dialog.add(OK);
Cancel.setBounds(390, 243, 74, 26);
Dialog.add(Cancel);
Name.select(FontName);//初始化列表选择!!!!
Size.select(FontSize);
Text.setFont(getFont());//初始化文本区字体形式
Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Name.addItemListener(this);//列表和checkbox是item监听
Size.addItemListener(this);
Bold.addItemListener(this);
Italic.addItemListener(this);
OK.addActionListener(this);//按钮是动作监听
Cancel.addActionListener(this);
Dialog.addWindowListener(this);//dialog是窗口监听
}
public void itemStateChanged(ItemEvent e) {//item监听(只需改变文本区字体样式)
Text.setFont(getFont());
}
public void actionPerformed(ActionEvent e) {//窗口动作监听
if(e.getSource()==OK){//若是ok则全部更新
FontName=Name.getSelectedIndex();
FontStyle=getStyle();//粗细和倾斜
FontSize=Size.getSelectedIndex();
Dialog.setVisible(false);
try {
file=new RandomAccessFile("D:\\fontData.txt","rw");
file.writeInt(FontName);
file.writeInt(FontStyle);
file.writeInt(FontSize);
if(file!=null)file.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
else cancel();
}
public void windowClosing(WindowEvent e) {//窗口关闭
cancel();
}
public Font getFont(){//获得字体函数
if(Name.getSelectedIndex()==0) return new Font("新宋体",getStyle(),Size.getSelectedIndex()+8);//大小是从8开始的
else return new Font(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex()+8);
}
public void cancel(){//cancel函数
Name.select(FontName);//将2个列表还原,字体粗细还原,设为不可视
Size.select(FontSize);
setStyle();
Text.setFont(getFont());
Dialog.setVisible(false);
}
public void setStyle(){//设置字体粗细(由FontStyle推得00,01,10,11)
if(FontStyle==0 || FontStyle==2) Bold.setSelected(false);
else Bold.setSelected(true);
if(FontStyle==0 || FontStyle==1) Italic.setSelected(false);
else Italic.setSelected(true);
}
public int getStyle(){//获得粗细数值(00,01,10,11)=FontStyle
int bold=0,italic=0;
if(Bold.isSelected()) bold=1;
if(Italic.isSelected()) italic=1;
return bold+italic*2;
}
public void windowActivated(WindowEvent arg0) {}
public void windowClosed(WindowEvent arg0) {}
public void windowDeactivated(WindowEvent arg0) {}
public void windowDeiconified(WindowEvent arg0) {}
public void windowIconified(WindowEvent arg0) {}
public void windowOpened(WindowEvent arg0) {} public static void main(String args[]){
JFrame a=new JFrame();
FontDialog c=new FontDialog(a,400,400);
c.Dialog.setVisible(true);
}
}
FontDialog.java
6、MenuList类:负责把menu的各个功能集成到这个类中单独处理,这样很方便对menu进行扩展(这里只是各个元件的组合,其监听实现不在这里,不能单独运行出现界面)
package notepad;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke; public class MenuList{
public JMenuBar Menu;
public JMenu File, Edit, App,Run,TXL,View, Help;
public JMenuItem
New,Open,Save,SaveAs,Print,Exit,//File
Undo,Redo,Cut,Copy,Paste,Delete,SelectAll,FindAndReplace,//Edit
HuiWen,FanYi,TongJi,QiuHe,//App
Build,Go,//Run
TXL_1,TXL_2,//TXL
Font,Color,//View
ViewHelp,AboutNotepad;//Help
public JCheckBoxMenuItem WordWrap,Truncation;
MenuList(){
Menu=new JMenuBar();
//File//////////////////////////////////////////////
File=new JMenu(" File ");
New=new JMenuItem("New");
Open=new JMenuItem("Open...");
Save=new JMenuItem("Save");
SaveAs=new JMenuItem("Save As...");
Print=new JMenuItem("Print...");
Exit=new JMenuItem("Exit");
////Edit////////////////////////////////////////////
Edit=new JMenu(" Edit ");
Undo=new JMenuItem("Undo");
Redo=new JMenuItem("Redo");
Cut=new JMenuItem("Cut");
Copy=new JMenuItem("Copy");
Paste=new JMenuItem("Paste");
Delete=new JMenuItem("Delete");
SelectAll=new JMenuItem("Select All");
FindAndReplace=new JMenuItem("Find And Replace...");
Undo.setEnabled(false);
Redo.setEnabled(false);
//App///////////////////////////////////////////////
App=new JMenu(" App ");
HuiWen=new JMenuItem("HuiWen");
FanYi=new JMenuItem("FanYi");
TongJi=new JMenuItem("TongJi");
QiuHe=new JMenuItem("QiuHe");
//Run//////////////////////////////////////////////
Run=new JMenu(" Run ");
Build=new JMenuItem("Build");
Go=new JMenuItem("Go");
Build.setEnabled(false);
Go.setEnabled(false);
//TXL//////////////////////////////////////////////
TXL=new JMenu(" TongXunLu ");
TXL_1=new JMenuItem("详细.....");
TXL_2=new JMenuItem("设置路径");
//View/////////////////////////////////////////////
View=new JMenu(" View ");
WordWrap=new JCheckBoxMenuItem("Word Wrap",true);
Truncation=new JCheckBoxMenuItem("Truncation",false);
Font=new JMenuItem("Font...");
Color=new JMenuItem("Color...");
//Help/////////////////////////////////////////////
Help=new JMenu(" Help ");
ViewHelp=new JMenuItem("View Help...");
AboutNotepad=new JMenuItem("About Notepad..."); Help.add(ViewHelp);
Help.add(AboutNotepad);
View.add(WordWrap);
View.add(Truncation);
View.addSeparator();
View.add(Font);
View.add(Color);
TXL.add(TXL_1);
TXL.add(TXL_2);
Run.add(Build);
Run.add(Go);
App.add(HuiWen);
App.add(FanYi);
App.add(TongJi);
App.add(QiuHe);
Edit.add(Undo);
Edit.add(Redo);
Edit.addSeparator();
Edit.add(Cut);
Edit.add(Copy);
Edit.add(Paste);
Edit.add(Delete);
Edit.addSeparator();
Edit.add(SelectAll);
Edit.add(FindAndReplace);
File.add(New);
File.add(Open);
File.addSeparator();
File.add(Save);
File.add(SaveAs);
File.addSeparator();
File.add(Print);
File.add(Exit);
Menu.add(File);
Menu.add(Edit);
Menu.add(App);
Menu.add(Run);
Menu.add(TXL);
Menu.add(View);
Menu.add(Help);
New.setAccelerator(KeyStroke.getKeyStroke('N',128));
Open.setAccelerator(KeyStroke.getKeyStroke('O',128));
Save.setAccelerator(KeyStroke.getKeyStroke('S',128));
Print.setAccelerator(KeyStroke.getKeyStroke('P',128));
Undo.setAccelerator(KeyStroke.getKeyStroke('Z',128));
Redo.setAccelerator(KeyStroke.getKeyStroke('Y',128));
Cut.setAccelerator(KeyStroke.getKeyStroke('X',128));
Copy.setAccelerator(KeyStroke.getKeyStroke('C',128));
Paste.setAccelerator(KeyStroke.getKeyStroke('V',128));
Build.setAccelerator(KeyStroke.getKeyStroke('B',128));
Go.setAccelerator(KeyStroke.getKeyStroke('G',128));
Delete.setAccelerator(KeyStroke.getKeyStroke(127,0));
SelectAll.setAccelerator(KeyStroke.getKeyStroke('A',128));
}
}
MenuList.java
7、 TextArea类:主要的文本编辑区类,同时集成上面的menu类,基本构成该软件的主要界面和功能的封装。把menu的监听函数需要用的函数封装了一下。具体请看代码,不能单独运行出现界面:
package notepad;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoManager; import toolBarTest.ToolBar; public class TextArea extends JTextArea implements MouseListener,UndoableEditListener,
MenuListener,ActionListener,ItemListener{
private static final long serialVersionUID = 1L;
public boolean Saved;//标记变量,看是否保存
public String Name,Path;
public JScrollPane Pane;//分隔条
public JPopupMenu Popup;//弹出菜单
public JMenuItem Redo,Undo,Cut,Copy,Paste,Delete,SelectAll,FindAndReplace;//弹出菜单元素
public UndoManager Manager;//
public MenuList menu;//自定义菜单
ToolBar toolbar;//自定义工具条
public FindAndReplace find;//查找替换菜单元
TextArea(JFrame notepad,int x,int y){//构造函数(父类,x,y)
super();
Saved=true;//构造时,设为已保存
Name=null;
Path=null;
Popup=new JPopupMenu();
Undo=new JMenuItem(" Undo");
Redo=new JMenuItem(" Redo");
Cut=new JMenuItem(" Cut");
Copy=new JMenuItem(" Copy");
Paste=new JMenuItem(" Paste");
Delete=new JMenuItem(" Delete");
SelectAll=new JMenuItem(" Select All");
FindAndReplace=new JMenuItem(" Find And Replace...");
Pane=new JScrollPane(this);
Manager=new UndoManager();
menu=new MenuList();
toolbar=new ToolBar();//工具条
find=new FindAndReplace(notepad);//初始化
find.Dialog.setLocation(x,y);
Undo.setEnabled(false);
Redo.setEnabled(false);
setLineWrap(true);//自动换行
setWrapStyleWord(true);//自动换行换单词
Manager.setLimit(-1);//无限次返回
Popup.add(Undo);
Popup.add(Redo);
Popup.addSeparator();
Popup.add(Cut);
Popup.add(Copy);
Popup.add(Paste);
Popup.add(Delete);
Popup.addSeparator();
Popup.add(SelectAll);
Popup.add(FindAndReplace);
add(Popup);//将元素加入弹出窗口,将弹出窗口加入文本区
menu.Edit.addMenuListener(this);//菜单-编辑-菜单监听
menu.WordWrap.addItemListener(this);//菜单-换行-元素监听
menu.Truncation.addItemListener(this);//菜单-文字换行-元素监听
getDocument().addUndoableEditListener(this);//文本-撤销恢复监听
addMouseListener(this);//鼠标监听
find.FindNext.addActionListener(this);//find的4个动作监听
find.Replace.addActionListener(this);
find.ReplaceAll.addActionListener(this);
find.Finish.addActionListener(this);
}
public void saveFile(){//保存文件
try {
FileWriter fw = new FileWriter(Path+Name,false);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(getText());
bw.close();
fw.close();
Saved=true;
} catch (IOException e){}
}
public void openFile(){//打开文件
try {
int c;
StringBuffer sb=new StringBuffer();
FileReader fr=new FileReader(Path+Name);
setText(null);
while((c=fr.read())!=-1)
sb.append((char)c);
setText(sb.toString());
Saved=true;
fr.close();
Undo.setEnabled(false);//刚打开的撤销和重做都设成false
Redo.setEnabled(false);
menu.Undo.setEnabled(false);
menu.Redo.setEnabled(false);
toolbar.Undo.setEnabled(false);
toolbar.Redo.setEnabled(false);
}
catch (IOException e){}
}
public void delete(){//删除
int start=getSelectionStart();
int end=getSelectionEnd();
replaceRange("",start,end);
}
public int lastOf(String s1,int i){//从后往前查找
String s=getText();
if(find.MatchCase.isSelected()) return s.lastIndexOf(s1,i);
else{
s=s.toLowerCase();
return s.lastIndexOf(s1.toLowerCase(),i);
}
}
public int nextOf(String s1,int i){//从前往后查找
String s=getText();
if(find.MatchCase.isSelected()) return s.indexOf(s1,i);
else{
s=s.toLowerCase();
return s.indexOf(s1.toLowerCase(),i);
}
}
public void actionPerformed(ActionEvent e){//find&&replace
Object obj=e.getSource();
if(obj==find.Finish) find.Dialog.setVisible(false);//结束时让窗口不可见
String s1=find.FindText.getText();
String s2=find.ReplaceText.getText();
int len1=s1.length(),len2=s2.length();
if(len1<1) return;
int head=getSelectionStart(),rear=getSelectionEnd();//J函数,获取选中区开始和结束
if(obj==find.Replace){
if(head<rear) replaceRange(s2,head,rear);//J函数,把
else obj=find.FindNext;
}
if(obj==find.FindNext){//查找下一个
if(find.Up.isSelected()){//向上
head=lastOf(s1,head-len1);
if(head<0) return;
select(head, head+len1);
}
else{//向下
rear=nextOf(s1, rear);
if(rear<0) return;
select(rear,rear+len1);
}
}
else if(obj==find.ReplaceAll){
rear=0;
while(true){
rear=nextOf(s1,rear);
if(rear<0) return;
replaceRange(s2,rear,rear+len1);
rear=rear+len2;
setCaretPosition(rear);
}
}
}
public void menuSelected(MenuEvent e){//和弹出菜单类似,不做详解
Clipboard Board=Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = Board.getContents(Board);
DataFlavor flavor = DataFlavor.stringFlavor;
if(contents.isDataFlavorSupported(flavor))
menu.Paste.setEnabled(true);
else
menu.Paste.setEnabled(false);
if(getSelectedText()!=null){
menu.Cut.setEnabled(true);
menu.Copy.setEnabled(true);
menu.Delete.setEnabled(true);
}
else{
menu.Cut.setEnabled(false);
menu.Copy.setEnabled(false);
menu.Delete.setEnabled(false);
}
if(getText().isEmpty()){
menu.SelectAll.setEnabled(false);
menu.FindAndReplace.setEnabled(false);
}
else{
menu.SelectAll.setEnabled(true);
menu.FindAndReplace.setEnabled(true);
}
}
public void undoableEditHappened(UndoableEditEvent e){//文本变化监听
Manager.addEdit(e.getEdit());
Saved=false;
menu.Undo.setEnabled(true);
menu.Redo.setEnabled(false);
Undo.setEnabled(true);
Redo.setEnabled(false);
toolbar.Undo.setEnabled(true);
toolbar.Redo.setEnabled(false);
menu.Go.setEnabled(false);
}
public void mouseReleased(MouseEvent e) {//鼠标释放监听
if(e.isPopupTrigger())
{
Clipboard Board=Toolkit.getDefaultToolkit().getSystemClipboard();//此类实现一种使用剪切/复制/粘贴操作传输数据的机制
Transferable contents = Board.getContents(Board);//定义为传输操作提供数据所使用的类的接口
DataFlavor flavor = DataFlavor.stringFlavor;//通常用于访问剪切板上的数据,或者在执行拖放操作时使用
if(contents.isDataFlavorSupported(flavor))//如果剪切板中有数据就把past激活
Paste.setEnabled(true);
else
Paste.setEnabled(false);
if(getSelectedText()!=null){//如果选中文本,就把剪切、复制、删除激活
Cut.setEnabled(true);
Copy.setEnabled(true);
Delete.setEnabled(true);
}
else{
Cut.setEnabled(false);
Copy.setEnabled(false);
Delete.setEnabled(false);
}
if(getText().isEmpty()){//如果没有文本,就把全选和查找替换封闭
SelectAll.setEnabled(false);
FindAndReplace.setEnabled(false);
}
else{
SelectAll.setEnabled(true);
FindAndReplace.setEnabled(true);
}
Popup.show(this,e.getX(),e.getY());//显示弹出窗口
}
}
public void itemStateChanged(ItemEvent e) {//换行监听器监听
if(e.getSource()==menu.WordWrap){
setLineWrap(menu.WordWrap.isSelected());
menu.Truncation.setEnabled(menu.WordWrap.isSelected());
}
else
setWrapStyleWord(!menu.Truncation.isSelected());
}
public void mousePressed(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void menuCanceled(MenuEvent e) {}
public void menuDeselected(MenuEvent e) {}
}
TextArea.java
8、Notepad类:主程序。实现各种监听。代码如下:
package notepad; import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.print.PrinterException;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import tongxunlu.MyAddBook;
import toolBarTest.ToolBar;
import App.CountString;
import App.FQiuHe;
import App.HuiWen;
import App.NumExchangeEnglish;
import BianYi.Commond; public class Notepad implements ActionListener,WindowListener{
static Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕大小
static Image icon=Toolkit.getDefaultToolkit().getImage("50.png");//程序图标
static JFrame notepad;//总窗口
EnsureDialog ensure;//确定窗口
TextArea text;//文件编辑区(主要元素都在这里)
FileDialog dialog;//文件对话框
FontDialog font;//字体对话框
ColorDialog color;//颜色对话框
AboutDialog about;//about对话框
MyAddBook tongXunLu;//通讯录对话框
private RandomAccessFile file;//存储通讯录地址文件夹
Commond C;//编译结果窗口
Notepad(){
notepad=new JFrame("201226100108-李涛-java程序设计综合实验");//界面
dialog=new FileDialog(notepad);//文件对话框
text=new TextArea(notepad,screen.width/2-190,screen.height/2-90);//文本区
ensure=new EnsureDialog(notepad,screen.width/2-180,screen.height/2-80);//确认对话框
font=new FontDialog(notepad,screen.width/2-240,screen.height/2-150);//字体对话框
color=new ColorDialog(notepad,screen.width/2-205,screen.height/2-110);//颜色对话框
about=new AboutDialog(notepad,screen.width/2-140,screen.height/2-100);//about对话框
tongXunLu=new MyAddBook();//通讯录对话框
C=new Commond(600,400,100,100);//编译运行对话框
notepad.setJMenuBar(text.menu.Menu);
notepad.setLayout(new BorderLayout());//
notepad.add("Center",text.Pane);
notepad.add("North",text.toolbar);
notepad.setSize(840,480);//设置大小
notepad.setLocation(screen.width/2-420,screen.height/2-240);//设置位置
notepad.setMinimumSize(new Dimension(185,185));//设置最小大小
notepad.setIconImage(icon);//设置图标
notepad.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//关闭
notepad.addWindowListener(this);//窗口监听%%%%%%%
text.setFont(font.getFont());//字体初始化
text.setForeground(color.NFC);//前景窗口颜色
text.setBackground(color.NBC);//背景窗口颜色
text.setSelectedTextColor(color.SFC);//前景字体颜色
text.setSelectionColor(color.SBC);//背景字体颜色
text.menu.Save.addActionListener(this);//所有监听.......
text.menu.SaveAs.addActionListener(this);
text.menu.Open.addActionListener(this);
text.menu.New.addActionListener(this);
text.menu.Print.addActionListener(this);
text.menu.Exit.addActionListener(this);
text.menu.Undo.addActionListener(this);
text.menu.Redo.addActionListener(this);
text.menu.Cut.addActionListener(this);
text.menu.Copy.addActionListener(this);
text.menu.Paste.addActionListener(this);
text.menu.Delete.addActionListener(this);
text.menu.SelectAll.addActionListener(this);
text.menu.FindAndReplace.addActionListener(this);
text.menu.WordWrap.addActionListener(this);
text.menu.Truncation.addActionListener(this);
text.menu.Font.addActionListener(this);
text.menu.Color.addActionListener(this);
text.menu.ViewHelp.addActionListener(this);
text.menu.AboutNotepad.addActionListener(this);
text.menu.HuiWen.addActionListener(this);//app
text.menu.FanYi.addActionListener(this);
text.menu.TongJi.addActionListener(this);
text.menu.QiuHe.addActionListener(this);
text.menu.TXL_1.addActionListener(this);//TXL
text.menu.TXL_2.addActionListener(this);
text.menu.Build.addActionListener(this);//run
text.menu.Go.addActionListener(this);
text.toolbar.New.addActionListener(this);//toolbar
text.toolbar.Open.addActionListener(this);
text.toolbar.Save.addActionListener(this);
text.toolbar.Build.addActionListener(this);
text.toolbar.Run.addActionListener(this);
text.toolbar.Undo.addActionListener(this);
text.toolbar.Redo.addActionListener(this);
text.Undo.addActionListener(this);//弹出窗口监听
text.Redo.addActionListener(this);
text.Cut.addActionListener(this);
text.Copy.addActionListener(this);
text.Paste.addActionListener(this);
text.Delete.addActionListener(this);
text.SelectAll.addActionListener(this);
text.FindAndReplace.addActionListener(this);
}
public void windowClosing(WindowEvent e) {//关闭按钮重定义
if(text.Saved){
if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
System.exit(0);
else return;
}
else{
if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
ensure.Ensure.setVisible(true);//确认窗口打开
else return;
}
if(ensure.Status==ensure.YES && saveFile()) System.exit(0);
else if(ensure.Status==ensure.NO) System.exit(0);
}
public void actionPerformed(ActionEvent e){//
Object obj=e.getSource();
if(obj==text.menu.Save || obj==text.toolbar.Save) saveFile();//保存
else if(obj==text.menu.SaveAs) saveAsFile();//另存为
else if(obj==text.menu.New || obj==text.toolbar.New){//新建
if(!(text.Saved)){//若没有保存
ensure.Ensure.setVisible(true);
if(ensure.Status==ensure.YES && saveFile()){}
else if(ensure.Status==ensure.NO){}
else return;
}
newFile();
}
else if(obj==text.menu.Open || obj==text.toolbar.Open){//打开
if(!(text.Saved)){
ensure.Ensure.setVisible(true);
if(ensure.Status==ensure.YES && saveFile()){}
else if(ensure.Status==ensure.NO){}
else return;
}
openFile();
}
else if(obj==text.menu.Print){//打印
try {
text.print();
} catch (PrinterException pe){}
}
else if(obj==text.menu.Exit){//退出
if(text.Saved){
if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
System.exit(0);
else return;
}
else{
if((JOptionPane.showConfirmDialog(notepad, "Are You Sure Exit ?",null,JOptionPane.YES_NO_OPTION))==0)
ensure.Ensure.setVisible(true);//确认窗口打开
else return;
}
if(ensure.Status==ensure.YES && saveFile()) System.exit(0);
else if(ensure.Status==ensure.NO) System.exit(0);
}
else if(obj==text.menu.Undo || obj==text.Undo || obj==text.toolbar.Undo){//返回一步
text.Manager.undo();
text.Saved=false;
text.menu.Redo.setEnabled(true);
text.Redo.setEnabled(true);
text.toolbar.Redo.setEnabled(true);
if(!text.Manager.canUndo()){
text.menu.Undo.setEnabled(false);
text.Undo.setEnabled(false);
text.toolbar.Undo.setEnabled(false);
}
}
else if(obj==text.menu.Redo || obj==text.Redo || obj==text.toolbar.Redo){//前进一步
text.Manager.redo();
text.Saved=false;
text.menu.Undo.setEnabled(true);
text.Undo.setEnabled(true);
text.toolbar.Undo.setEnabled(true);
if(!text.Manager.canRedo()){
text.menu.Redo.setEnabled(false);
text.Redo.setEnabled(false);
text.toolbar.Redo.setEnabled(false);
}
}
else if(obj==text.Cut || obj==text.menu.Cut){//剪切
text.cut();
}
else if(obj==text.Copy || obj==text.menu.Copy){//复制
text.copy();
}
else if(obj==text.Paste || obj==text.menu.Paste){//粘贴
text.paste();
}
else if(obj==text.Delete || obj==text.menu.Delete){//删除
text.delete();
}
else if(obj==text.SelectAll || obj==text.menu.SelectAll){//全选
text.selectAll();
}
else if(obj==text.FindAndReplace || obj==text.menu.FindAndReplace){//查找替换
text.find.Dialog.setVisible(true);
} else if(obj==text.menu.HuiWen){//回文串
HuiWen a=new HuiWen();
}else if(obj==text.menu.FanYi){//翻译
NumExchangeEnglish a=new NumExchangeEnglish();
}else if(obj==text.menu.TongJi){//统计
if(text.Name==null){saveFile();text.Saved=true;}
else if(!text.Saved){saveFile();text.Saved=true;}
try {
CountString a=new CountString(text.Path+text.Name);
} catch(IOException e1){}
}else if(obj==text.menu.QiuHe){//求和
if(text.Name==null){saveFile();text.Saved=true;}
else if(!text.Saved){saveFile();text.Saved=true;}
FQiuHe a=new FQiuHe(text.Path+text.Name,Notepad.notepad);
}
else if(obj==text.menu.TXL_1){//通讯录
if(tongXunLu==null)tongXunLu=new MyAddBook();
tongXunLu.frame.setVisible(true);
}else if(obj==text.menu.TXL_2){//更改路径
if(tongXunLu==null)tongXunLu=new MyAddBook();
String path,name;
dialog.setMode(FileDialog.SAVE);
dialog.setTitle("Change As...");
dialog.setFile(tongXunLu.Name);
dialog.setVisible(true);
path=dialog.getDirectory();
name=dialog.getFile();
if(name!=null){
tongXunLu.changeRoad(path,name);//改变路径
JOptionPane.showMessageDialog(notepad,"路径已修改至: "+path+name);
}
}else if(obj==text.menu.Build || obj==text.toolbar.Build){//编译
String s;
if(!text.Saved)saveFile();
try {
s=C.getInfoDOS(text.Name,text.Path,false);Commond.show.addStr(s);
text.menu.Go.setEnabled(true);//将按钮激活
text.toolbar.Run.setEnabled(true);
} catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
}else if(obj==text.menu.Go || obj==text.toolbar.Run){//运行
String s;
try {
s=C.getInfoDOS(text.Name,text.Path,true);Commond.show.addStr(s);
} catch (IOException | InterruptedException e1){
e1.printStackTrace();
}
}
else if(obj==text.menu.Font){//字体
font.Dialog.setVisible(true);
if(text.getFont()!=font.getFont())
text.setFont(font.getFont());
}
else if(obj==text.menu.Color){//颜色
color.Dialog.setVisible(true);
text.setForeground(color.NFC);
text.setBackground(color.NBC);
text.setSelectedTextColor(color.SFC);
text.setSelectionColor(color.SBC);
text.setCaretColor(color.NFC);
}
else if(obj==text.menu.AboutNotepad){//about
about.Dialog.setVisible(true);
}
} public boolean saveFile(){//保存函数
if(text.Name==null){
dialog.setMode(FileDialog.SAVE);
dialog.setTitle("Save As...");
dialog.setFile("Untitled.txt");
dialog.setVisible(true);
text.Path=dialog.getDirectory();
text.Name=dialog.getFile();
}
if(text.Name==null) return false;
text.saveFile();
notepad.setTitle(text.Name+" - Notepad");
if(text.Name.endsWith("java")){//是java文件
text.menu.Build.setEnabled(true);
text.menu.Go.setEnabled(false);
text.toolbar.Build.setEnabled(true);
text.toolbar.Run.setEnabled(false);
}
return true;
}
public void saveAsFile(){//另存函数
String path=text.Path;
String name=text.Name;
dialog.setMode(FileDialog.SAVE);
dialog.setTitle("Save As...");
if(text.Name==null)
dialog.setFile("Untitled.txt");
else dialog.setFile(text.Name);
dialog.setVisible(true);
text.Path=dialog.getDirectory();
text.Name=dialog.getFile();
if(text.Name!=null){
text.saveFile();
notepad.setTitle(text.Name+" - Notepad");
}
else{
text.Name=name;
text.Path=path;
}
if(text.Name.endsWith("java")){//是java文件
text.menu.Build.setEnabled(true);
text.menu.Go.setEnabled(false);
text.toolbar.Build.setEnabled(true);
text.toolbar.Run.setEnabled(false);
}
}
public void openFile(){//打开函数
String path=text.Path;
String name=text.Name;
dialog.setTitle("Open...");
dialog.setMode(FileDialog.LOAD);
dialog.setVisible(true);
text.Path=dialog.getDirectory();
text.Name=dialog.getFile();
if(text.Name!=null){
text.openFile();
notepad.setTitle(text.Name+" - Notepad");
}
else{
text.Name=name;
text.Path=path;
}
if(text.Name.endsWith("java")){//是java文件
text.menu.Build.setEnabled(true);
text.menu.Go.setEnabled(false);
text.toolbar.Build.setEnabled(true);
text.toolbar.Run.setEnabled(false);
}
}
public void newFile(){//新建
text.Path=null;
text.Name=null;
text.setText(null);
notepad.setTitle("Notepad");
text.Saved=true;
text.Undo.setEnabled(false);
text.Redo.setEnabled(false);
text.menu.Undo.setEnabled(false);
text.menu.Redo.setEnabled(false);
text.menu.Build.setEnabled(false);
text.menu.Go.setEnabled(false);
text.toolbar.Build.setEnabled(false);
text.toolbar.Run.setEnabled(false);
}
public static void main(String s[]){
System.setProperty("java.awt.im.style","on-the-spot"); //去除输入中文时的浮动框
Notepad np=new Notepad();
Notepad.notepad.setVisible(true);
}
public void windowActivated(WindowEvent arg0){}
public void windowClosed(WindowEvent arg0){}
public void windowDeactivated(WindowEvent arg0){}
public void windowDeiconified(WindowEvent arg0){}
public void windowIconified(WindowEvent arg0){}
public void windowOpened(WindowEvent arg0){}
}
Notepad.java
toolBarTest包:
1、JToolBar类:主要是工具条的元件组合,监听在notepad类内实现。可单独运行查看效果:
package toolBarTest;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout; import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JToolBar; public class ToolBar extends JToolBar{
public FgButton New,Open,Save,Build,Run,Undo,Redo;
public ToolBar(){
super();
setBackground(new Color(255,255,255));//把条设成白色
addToolBar();
}
private void addToolBar() {
// 工具条
setLayout(new FlowLayout(FlowLayout.LEFT));
New=new FgButton(new ImageIcon(getClass().getResource("new.png")),"新建文件");
Open=new FgButton(new ImageIcon(getClass().getResource("open.png")),"打开文件");
Save=new FgButton(new ImageIcon(getClass().getResource("save.png")),"保存文件");
Build=new FgButton(new ImageIcon(getClass().getResource("build.png")),"编译");
Run=new FgButton(new ImageIcon(getClass().getResource("run.png")),"运行");
Undo=new FgButton(new ImageIcon(getClass().getResource("undo.png")),"返回");
Redo=new FgButton(new ImageIcon(getClass().getResource("redo.png")),"重做"); New.setBorder(BorderFactory.createEmptyBorder());
Open.setBorder(BorderFactory.createEmptyBorder());
Save.setBorder(BorderFactory.createEmptyBorder());
Build.setBorder(BorderFactory.createEmptyBorder());
Run.setBorder(BorderFactory.createEmptyBorder());
Undo.setBorder(BorderFactory.createEmptyBorder());
Redo.setBorder(BorderFactory.createEmptyBorder()); Build.setEnabled(false);
Run.setEnabled(false);
Undo.setEnabled(false);
Redo.setEnabled(false); add(New);
add(Open);
add(Save);
add(Build);
add(Run);
add(Undo);
add(Redo);
// 设置不可浮动
setFloatable(false);
} public static void main(String[] args) {
JFrame frame=new JFrame();
JTextArea text=new JTextArea();
frame.setLayout(new BorderLayout());
ToolBar bar=new ToolBar();
frame.add("Center",text);
frame.add("North",bar);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); } // 自定义button(带图片的和带提示的构造方法)
public class FgButton extends JButton {
public FgButton() {
super();
} public FgButton(Icon icon) {
super(icon);
} public FgButton(Icon icon, String strToolTipText) {
super(icon);
setToolTipText(strToolTipText);
} public FgButton(String text) {
super(text);
} public FgButton(String text, Icon icon, String strToolTipText) {
super(text, icon);
setToolTipText(strToolTipText);
}
} }
JToolBar.java
tongxunlu包:
主要是通讯录的各个功能实现:包括增加、删除、查找、替换....这个没怎么仔细加工,总之很水的,代码有点乱....
package tongxunlu; import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter; import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel; public class MyAddBook {
public JFrame frame;
public String Name;//文件保存名和路径
public String Path; public void changeRoad(String path,String name){//更改路径函数 //file2.renameTo(new File(path+name));
try {//更新文件路径
FileWriter file1 = new FileWriter(path+name, true);
PrintWriter write = new PrintWriter(file1);
FileReader file2 = new FileReader(Path+Name);
BufferedReader read = new BufferedReader(file2);
String str;
while((str=read.readLine())!=null){
write.println(str);
}
write.close();
file1.close();
read.close();
file2.close();
new File(Path+Name).delete();
} catch (IOException e) {
e.printStackTrace();
}
Name=name;Path=path;
try {//保存文件路径
new File("D://TXLData.txt").delete();//删除上次的
FileWriter file1 = new FileWriter("D://TXLData.txt", true);
PrintWriter write = new PrintWriter(file1);
write.println(Path);
write.println(Name);
write.close();
file1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Init(){//初始化路径
try {
BufferedReader read = new BufferedReader(new FileReader("D://TXLData.txt"));
FileWriter file1 = new FileWriter("D://TEMP.txt", true);
PrintWriter write = new PrintWriter(file1);
String str;int ok=0;
while((str=read.readLine())!=null){
Path=str;
Name=read.readLine();
ok=1;
}
if(ok==0){
Path="D:\\\\";
Name="TongXunLu.txt";
write.println(Path);
write.println(Name);
}
read.close();
write.close();
file1.close();
new File("D://TXLData.txt").delete();
File file2 = new File("D://TEMP.txt");
file2.renameTo(new File("D://TXLData.txt"));
}catch(FileNotFoundException e1){
}catch (IOException e1) {}
}
public MyAddBook(){
Init();
frame = new JFrame("TAO~TAO通讯录");//主窗口 JMenuBar menubar = new JMenuBar(); JMenu edit = new JMenu("编辑");
JMenuItem edit1 = new JMenuItem("录入");
JMenuItem edit2 = new JMenuItem("查询");
JMenuItem edit3 = new JMenuItem("删除");
JMenuItem edit4 = new JMenuItem("修改");
JMenuItem edit5 = new JMenuItem("排序");
edit1.addActionListener(new Typein(Path,Name));
JMenu show = new JMenu("显示信息");
JMenuItem show1 = new JMenuItem("classmates");
JMenuItem show2 = new JMenuItem("colleagues");
JMenuItem show3 = new JMenuItem("friends");
JMenuItem show4 = new JMenuItem("relatives");
JMenuItem show5 = new JMenuItem("all members");
Container c = frame.getContentPane();
JPanel pane = new JPanel();
c.add(pane);
pane.add(menubar);
menubar.add(edit);
edit.add(edit1);
edit.add(edit2);
edit.add(edit3);
edit.add(edit4);
edit.add(edit5);
menubar.add(show);
show.add(show1);
show.add(show2);
show.add(show3);
show.add(show4);
show.add(show5);
frame.setSize(300, 100); edit2.addActionListener(new ActionListener() // 监听查询
{
public void actionPerformed(ActionEvent e) {
new Search(frame,"查询", 2,Path,Name).dialog.setVisible(true);
}
});
edit3.addActionListener(new ActionListener() // 监听删除
{
public void actionPerformed(ActionEvent e) {
new Search(frame,"删除", 3,Path,Name).dialog.setVisible(true);
}
});
edit4.addActionListener(new ActionListener() // 监听修改
{
public void actionPerformed(ActionEvent e) {
new Search(frame,"修改", 4,Path,Name).dialog.setVisible(true);
}
});
edit5.addActionListener(new ActionListener() // 监听排序
{
public void actionPerformed(ActionEvent e) {
new Print("按姓名排序后", 2,Path,Name);
}
});
//------------------------------------------------------------
show1.addActionListener(new ActionListener() // 监听同学
{
public void actionPerformed(ActionEvent e) {
new Print("classmates", 1,Path,Name);
}
});
show2.addActionListener(new ActionListener() // 监听同事
{
public void actionPerformed(ActionEvent e) {
new Print("colleagues", 1,Path,Name);
}
});
show3.addActionListener(new ActionListener() // 监听朋友
{
public void actionPerformed(ActionEvent e) {
new Print("friends", 1,Path,Name);
}
});
show4.addActionListener(new ActionListener() // 监听亲戚
{
public void actionPerformed(ActionEvent e) {
new Print("relatives", 1,Path,Name);
}
});
show5.addActionListener(new ActionListener() // 监听全体人员
{
public void actionPerformed(ActionEvent e) {
new Print("all members", 0,Path,Name);
}
});
}
public static void main(String[] args) { }
}
MyAddBook.java
package tongxunlu; public class people {
//"序号"//"姓名","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","备注" public String People[]=new String[16];
public people(String args){
//把args转成people
String temp="";char c;
for(int i=0,j=1;i<args.length();i++){
c=args.charAt(i);
if(c!='|'){
temp+=c;
}else{
People[j]=new String(temp);
temp="";
j++;
}
}
}
public static String findName(String args){//查找人命
String temp="";char c;
for(int i=0,j=1;i<args.length();i++){
c=args.charAt(i);
if(c!='|'){
temp+=c;
}else{
break;
}
}
return temp;
}
}
people.java
package tongxunlu; import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector; import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel; // 输出类
public class Print { String[] firstList = new String[]{"序号","姓名","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","关系","备注"};
DefaultTableModel m_data;
JTable m_view;
people people1;
public String Name,Path;//文件保存名和路径 public Print(String st, int n,String path,String name){
Name=name;Path=path;
JFrame frame = new JFrame(st + "信息如下");
frame.setSize(800, 400);
// frame.setLocation(350, 150);
m_data = new DefaultTableModel(null,mb_getColumnNames(firstList)); // 创建一个空的数据表格
m_view = new JTable(m_data);
m_view.setPreferredScrollableViewportSize(new Dimension(800,400)); // 设置表格的显示区域大小
m_view.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
m_view.setEnabled(false);//设置不可编辑
JScrollPane sPane = new JScrollPane(m_view);
frame.add(sPane);
frame.setVisible(true);
if (n == 3){//查找某人
try {
BufferedReader read = new BufferedReader(new FileReader(Path+Name));
int z = 1;
while (z == 1) {
String str = read.readLine();
if (str != null){
people1=new people(str);
if(people1.People[1].equals(st)){
people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
m_data.addRow(mb_getColumnNames(people1.People));
}
}else z = 0;
}
read.close();
} catch (FileNotFoundException e1) {
} catch (IOException e2) {}
} if (n == 2){// 排序
try{
int i;
String[] all;
all = new String[10000];
BufferedReader read = new BufferedReader(new FileReader(Path+Name)); int z = 1,count = 0;
while (z == 1) {
for (i=0; i<10000;i++){
String str=read.readLine();
if(str!=null){
all[i] = str;
count++;
}else z=0;
}
}
String[] bll = new String[count];
for (i = 0; i < count; i++)
bll[i] = all[i];
getSortOfChinese(bll);
for (i = 0; i < count; i++){
people1=new people(bll[i]);
people1.People[0]=new String(Integer.toString(i+1));
m_data.addRow(mb_getColumnNames(people1.People));
}
read.close();
} catch (FileNotFoundException e1) {
} catch (IOException e2) {}
} if (n == 1){// 各类人员
try {
BufferedReader read = new BufferedReader(new FileReader(Path+Name));
int z = 1;
while (z == 1) {
String str = read.readLine();
if (str != null){
people1=new people(str);
if(people1.People[14].equals(st)){
people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
m_data.addRow(mb_getColumnNames(people1.People));
}
}else z = 0;
}
read.close();
} catch (FileNotFoundException e1) {
} catch (IOException e2) {}
} if(n == 0){// 全体人员信息
try {
BufferedReader read = new BufferedReader(new FileReader(Path+Name));
int z = 1;
while (z == 1) {
String str = read.readLine();
if (str != null){
//System.out.print(Integer.toString(m_data.getRowCount()+1));
people1=new people(str);
people1.People[0]=new String(Integer.toString(m_data.getRowCount()+1));
m_data.addRow(mb_getColumnNames(people1.People));
}
else
z = 0;
}
read.close();
} catch (FileNotFoundException e1) {
} catch (IOException e2) {}
}
} public Vector<String> mb_getColumnNames(String args[]) // 数组转向量
{
Vector<String> vs = new Vector<String>();
for (int i = 0; i <args.length; i++)
vs.add(args[i]);
return (vs);
} // 方法mb_getColumnNames结束 @SuppressWarnings("unchecked")
public static String[] getSortOfChinese(String[] a) {
// Collator 类是用来执行区分语言环境这里使用CHINA
Comparator cmp = Collator.getInstance(java.util.Locale.CHINA); // JDKz自带对数组进行排序。
Arrays.sort(a, cmp);
return a;
}
}
Print.java
package tongxunlu; import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField; //查询修改删除
public class Search { public JDialog dialog;
public String Name,Path;//文件保存名和路径
public Search(final JFrame frame,String str, int n,String path,String name) {
Path=path;Name=name;
dialog= new JDialog(frame, "查询对话框", true);
dialog.setSize(250, 200);
Container c = dialog.getContentPane();
dialog.setLayout(new GridLayout(2, 1, 5, 5));
JLabel Lsearch = new JLabel("请输入要" + str + "人员的名字:");
final JTextField Tname = new JTextField(10);
JButton certain = new JButton("确定");
JButton cancel = new JButton("取消");
// final String in=Tname.getText();
JPanel pane1 = new JPanel();
JPanel pane2 = new JPanel();
c.add(pane1);
c.add(pane2);
pane1.add(Lsearch);
pane1.add(Tname);
pane2.add(certain);
pane2.add(cancel);
dialog.setDefaultCloseOperation(dialog.DISPOSE_ON_CLOSE);
if (n == 2) {// 查询
certain.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
if(Tname.getText()=="")
JOptionPane.showMessageDialog(dialog,"请输入内容","警告",JOptionPane.WARNING_MESSAGE);
else{
dialog.dispose();//problem appearent
new Print(Tname.getText(),3,Path,Name);
}
}
});
}
if(n==3) {
certain.addActionListener(new ActionListener() // 删除
{
public void actionPerformed(ActionEvent e) {
try {
BufferedReader read = new BufferedReader(new FileReader(Path+Name));
FileWriter file1 = new FileWriter("D://TEMP.txt", true);
PrintWriter write = new PrintWriter(file1);
int z = 1,ok=0;
while (z==1) {
String str=read.readLine();
if (str!= null){
String s = people.findName(str);
if (!(s.equals(Tname.getText()))) {
write.println(str);
}else{
ok=1;//标记是否有被删除对象
}
}else z = 0;
}
// file.close();
read.close();
write.close();
file1.close();
new File(Path+Name).delete();
//System.out.println(Path+" "+Name);
File file2 = new File("D://TEMP.txt");
file2.renameTo(new File(Path+Name));
if(ok==1)JOptionPane.showMessageDialog(null,Tname.getText()+"被成功删除", "删除结果",JOptionPane.INFORMATION_MESSAGE);
else JOptionPane.showMessageDialog(null,"未找到"+Tname.getText(), "删除结果",JOptionPane.WARNING_MESSAGE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
JOptionPane.showMessageDialog(null, "未找到文件");
} catch (IOException e2) {
// TODO Auto-generated catch block
// e2.printStackTrace();
System.out.print("未找到该人员");
}
}
});
}
if(n == 4){
certain.addActionListener(new ActionListener() // 修改
{
public void actionPerformed(ActionEvent e) {
try {
BufferedReader read = new BufferedReader(new FileReader(Path+Name));
FileWriter file1 = new FileWriter("D://TEMP.txt", true);
PrintWriter write = new PrintWriter(file1);
int z = 1,ok=0;
while (z==1){
String str=read.readLine();
if (str!= null){
String s = people.findName(str);
if (!(s.equals(Tname.getText()))) {
write.println(str);
}else{
//dialog.dispose();
Typein a=new Typein(frame,str,write,Path,Name);
a.typein();
ok=1;//标记是否有这个人,0有
//System.out.print(1);
//a.frame.dispose();
}
}else z=0;
}
// file.close();
read.close();
write.close();
file1.close();
new File(Path+Name).delete();
File file2 = new File("D://TEMP.txt");
file2.renameTo(new File(Path+Name));
if(ok==1)JOptionPane.showMessageDialog(null,Tname.getText()+"被成功修改", "修改结果",JOptionPane.INFORMATION_MESSAGE);
else JOptionPane.showMessageDialog(null,"未找到"+Tname.getText(), "修改结果",JOptionPane.WARNING_MESSAGE);
}catch(FileNotFoundException e1){
}catch (IOException e1) {}
}
});
} /* if (Typein.z == 1) {
write.print(Tname.getText() + '\t');
write.print(s1 + '\t');
write.print(s2 + ' ');
write.print(s3 + ' ');
write.print(s4 + '\t');
write.print(s5 + '\t');
write.print(s6 + '\t');
write.println(s7);
Typein.z = 2; }
}
} } catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
System.out.print("未找到文件");
} catch (IOException e2) {
// TODO Auto-generated catch block
// e2.printStackTrace();
System.out.print("未找到该人员");
}
}
});
}*/
cancel.addActionListener(new ActionListener() // 取消
{
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
}
}
Search.java
package tongxunlu; import java.awt.Choice;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter; import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel; //输入类
public class Typein implements ActionListener {
String[] firstList = new String[]{"姓名*","性别","家庭住址","工作单位","邮政编码","家庭电话号码","办公室电话号码","传真号码","移动电话号码","Email","QQ","MSN","出生日期","关系","备注"};
public static int z = 2;
public static int y = 0;
public JLabel[] label=new JLabel[15];//15个label
public JTextField[] textfield=new JTextField[12];//12个文本编辑区
public Choice Cgroup = new Choice(),Cfimle = new Choice(), Cbirthyear = new Choice(),//5个选择组(单选)
Cbirthmonth = new Choice(), Cbirthday = new Choice();
public JButton certain1, cancel;//2个按钮
public JDialog frame;//主界面
public String Include="";
private PrintWriter write;
public String Name,Path;//文件保存名和路径
public Typein(String path,String name) {//1遍
Name=name;Path=path;//路径
frame=new JDialog();
frame.setTitle("查找界面");
Cgroup.addItem("null");//把单选按钮组组好
Cgroup.addItem("classmates");
Cgroup.addItem("colleagues");
Cgroup.addItem("friends");
Cgroup.addItem("relatives");
Cfimle.addItem("nan");
Cfimle.addItem("nv");
Cbirthyear.addItem("1985");
Cbirthyear.addItem("1986");
Cbirthyear.addItem("1987");
Cbirthyear.addItem("1988");
Cbirthyear.addItem("1989");
Cbirthyear.addItem("1990");
Cbirthyear.addItem("1991");
Cbirthyear.addItem("1992");
Cbirthyear.addItem("1993");
Cbirthyear.addItem("1994");
Cbirthyear.addItem("1995");
Cbirthyear.addItem("1996");
Cbirthyear.addItem("1997");
Cbirthyear.addItem("1998");
Cbirthyear.addItem("1999");
Cbirthyear.addItem("2000");
Cbirthmonth.addItem("01");
Cbirthmonth.addItem("02");
Cbirthmonth.addItem("03");
Cbirthmonth.addItem("04");
Cbirthmonth.addItem("05");
Cbirthmonth.addItem("06");
Cbirthmonth.addItem("07");
Cbirthmonth.addItem("08");
Cbirthmonth.addItem("09");
Cbirthmonth.addItem("10");
Cbirthmonth.addItem("11");
Cbirthmonth.addItem("12");
Cbirthday.addItem("01");
Cbirthday.addItem("02");
Cbirthday.addItem("03");
Cbirthday.addItem("04");
Cbirthday.addItem("05");
Cbirthday.addItem("06");
Cbirthday.addItem("07");
Cbirthday.addItem("08");
Cbirthday.addItem("09");
Cbirthday.addItem("10");
Cbirthday.addItem("11");
Cbirthday.addItem("12");
Cbirthday.addItem("13");
Cbirthday.addItem("14");
Cbirthday.addItem("15");
Cbirthday.addItem("16");
Cbirthday.addItem("17");
Cbirthday.addItem("18");
Cbirthday.addItem("19");
Cbirthday.addItem("20");
Cbirthday.addItem("21");
Cbirthday.addItem("22");
Cbirthday.addItem("23");
Cbirthday.addItem("24");
Cbirthday.addItem("25");
Cbirthday.addItem("26");
Cbirthday.addItem("27");
Cbirthday.addItem("28");
Cbirthday.addItem("29");
Cbirthday.addItem("30");
Cbirthday.addItem("31");
} public Typein(JFrame jframe,String include,PrintWriter printwriter,String path,String name) {//含参构造函数(内容)
frame=new JDialog(jframe,"修改界面",true);
Include=include;write=printwriter;
Name=name;Path=path;//路径
Cgroup.addItem("null");//把单选按钮组组好
Cgroup.addItem("classmates");
Cgroup.addItem("colleagues");
Cgroup.addItem("friends");
Cgroup.addItem("relatives");
Cfimle.addItem("nan");
Cfimle.addItem("nv");
Cbirthyear.addItem("1985");
Cbirthyear.addItem("1986");
Cbirthyear.addItem("1987");
Cbirthyear.addItem("1988");
Cbirthyear.addItem("1989");
Cbirthyear.addItem("1990");
Cbirthyear.addItem("1991");
Cbirthyear.addItem("1992");
Cbirthyear.addItem("1993");
Cbirthyear.addItem("1994");
Cbirthyear.addItem("1995");
Cbirthyear.addItem("1996");
Cbirthyear.addItem("1997");
Cbirthyear.addItem("1998");
Cbirthyear.addItem("1999");
Cbirthyear.addItem("2000");
Cbirthmonth.addItem("01");
Cbirthmonth.addItem("02");
Cbirthmonth.addItem("03");
Cbirthmonth.addItem("04");
Cbirthmonth.addItem("05");
Cbirthmonth.addItem("06");
Cbirthmonth.addItem("07");
Cbirthmonth.addItem("08");
Cbirthmonth.addItem("09");
Cbirthmonth.addItem("10");
Cbirthmonth.addItem("11");
Cbirthmonth.addItem("12");
Cbirthday.addItem("01");
Cbirthday.addItem("02");
Cbirthday.addItem("03");
Cbirthday.addItem("04");
Cbirthday.addItem("05");
Cbirthday.addItem("06");
Cbirthday.addItem("07");
Cbirthday.addItem("08");
Cbirthday.addItem("09");
Cbirthday.addItem("10");
Cbirthday.addItem("11");
Cbirthday.addItem("12");
Cbirthday.addItem("13");
Cbirthday.addItem("14");
Cbirthday.addItem("15");
Cbirthday.addItem("16");
Cbirthday.addItem("17");
Cbirthday.addItem("18");
Cbirthday.addItem("19");
Cbirthday.addItem("20");
Cbirthday.addItem("21");
Cbirthday.addItem("22");
Cbirthday.addItem("23");
Cbirthday.addItem("24");
Cbirthday.addItem("25");
Cbirthday.addItem("26");
Cbirthday.addItem("27");
Cbirthday.addItem("28");
Cbirthday.addItem("29");
Cbirthday.addItem("30");
Cbirthday.addItem("31");
} public void typein() {//多遍
Container c = frame.getContentPane();
frame.setSize(500,300);
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new GridLayout(8,2, 5, 5)); for(int i=0;i<firstList.length;i++){
label[i]=new JLabel(firstList[i]);
//label[i].setFont(new Font("微软雅黑",0,12));
} if(Include=="")for(int i=0;i<textfield.length;i++){
textfield[i]=new JTextField(10);
}else{
people Peo=new people(Include);
/*for(int i=1;i<Peo.People.length;i++){
System.out.println(i+Peo.People[i]);
}*/
for(int i=0,j=1;j<Peo.People.length;j++){
if(j==2||j==13||j==14)continue;
else{
textfield[i]=new JTextField(10);
textfield[i].setText(Peo.People[j]);
i++;
} }
} certain1 = new JButton("确定");
cancel = new JButton("取消"); JPanel[] panel = new JPanel[16];
for(int i=0;i<panel.length;i++){
panel[i]=new JPanel();
panel[i].setLayout(new GridLayout(1,2));
c.add(panel[i]);
} for(int i=0,j=0;i<panel.length-1;i++){
if(i==1){
panel[i].add(label[i]);
panel[i].add(Cfimle);
}else if(i==12){
panel[i].add(label[i]);
panel[i].add(Cbirthyear);
panel[i].add(Cbirthmonth);
panel[i].add(Cbirthday);
}else if(i==13){
panel[i].add(label[i]);
panel[i].add(Cgroup);
}else{
panel[i].add(label[i]);
panel[i].add(textfield[j++]);
}
}
if(Include!=""){//包含内容对选择框初始化
people Peo=new people(Include);
Cfimle.select(Peo.People[2]);
Cbirthyear.select(Peo.People[13].substring(0,4));
Cbirthmonth.select(Peo.People[13].substring(5,7));
Cbirthday.select(Peo.People[13].substring(8,10));
Cgroup.select(Peo.People[14]);
} panel[15].add(certain1);
panel[15].add(cancel); certain1.addActionListener(new ActionListener() // 设置监听器
{
public void actionPerformed(ActionEvent e) // 用匿名内部类实现监听器
{ if (textfield[0].getText().equals(""))
JOptionPane.showMessageDialog(null, "录入失败,姓名必须填写!", "录入结果",
JOptionPane.INFORMATION_MESSAGE);
else {
try {
String s="";
for(int i=0,j=0;i<label.length;i++){
if(i==1){
s+=(Cfimle.getSelectedItem()+"|");
}else if(i==12){
s+=(Cbirthyear.getSelectedItem()+'-'+Cbirthmonth.getSelectedItem()+'-'+Cbirthday.getSelectedItem()+"|");
}else if(i==13){
s+=(Cgroup.getSelectedItem()+"|");
}else{
if(textfield[j].getText().equals(""))s+=("null|");
else s+=(textfield[j].getText()+"|");
j++;
}
}//获取窗口数据转换成待存入的一行数据
if(Include==""){
FileWriter AddressBook = new FileWriter(Path+Name, true);
PrintWriter add = new PrintWriter(AddressBook);
add.println(s);
add.close();
AddressBook.close();
z = 1;
System.out.println(897);
}else{
//System.out.println(s);
write.println(s);
//write.close();
z=2;
y=1;
}
} catch (IOException e1) {}
if (y == 0) {
JOptionPane.showMessageDialog(null, "录入成功", "录入结果",
JOptionPane.INFORMATION_MESSAGE);
} else {
frame.dispose();
z = 0;
} for(int i=0,j=0;i<label.length;i++){
if(i==1){
Cfimle.select(0);
}else if(i==12){
Cbirthyear.select(0);
Cbirthmonth.select(0);
Cbirthday.select(0);
}else if(i==13){
Cgroup.select(0);
}else{
textfield[j].setText("");
j++;
}
Include="";
}
}
}
});
cancel.addActionListener(new ActionListener() // 设置监听器
{
public void actionPerformed(ActionEvent e) // 用匿名内部类实现监听器
{
frame.dispose();
z = 0;
}
});
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
new Typein(Path,Name).typein();
}
public static void main(String afd[]) throws IOException{
JFrame frame=new JFrame();
FileWriter file1 = new FileWriter("D:\\AddressBook.txt", true);
PrintWriter write = new PrintWriter(file1);
Typein a=new Typein(frame,"李涛|nan|安徽|zjut|123456|888888888|23423423|3242342342|32423423423423|953521476@qq.com|953521476|fasjosafj|1985-01-01|classmates|ta0|",write,"D:\\","AddressBook.txt");
a.typein();
//new Typein().typein();
}
}
Typein.java
BianYi包:
Commond类:主要负责调用DOS窗口,进行编译、运行java文件,同时向DOS内读写数据,包括错误流。更多介绍请看代码(可以直接运行):
package BianYi; import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea; public class Commond{
public static ResultShow show; //构造函数,显示窗口大小和位置
public Commond(int sX,int sY,int pX,int pY){
show=new ResultShow(sX,sY,pX,pY);
} //输入文件名,路径,是调试还是运行0-1,返回编译结果String
public String getInfoDOS(String name,String path,boolean TranslateOrRun) throws IOException, InterruptedException{
String result="",temp="",in;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
if(!TranslateOrRun){
in="cmd /c javac "+name;
result+="*********************************************************************************************************************\n";
result+=" ! Tao-Tao: "+df.format(new Date())+" "+"编译: "+path+name+" ^_^!\n";
result+="*********************************************************************************************************************\n";
}
else{
String preName=name.substring(0,name.lastIndexOf('.'));
in="cmd /c java "+preName;
result+="*********************************************************************************************************************\n";
result+=" ! Tao-Tao: "+df.format(new Date())+" "+"运行: "+path+name+" ^_^!\n";
result+="*********************************************************************************************************************\n";
}
Process process = Runtime.getRuntime().exec(in,null,new File(path)); int beginStrLength=result.length();
BufferedReader bufferedReaderErro = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((temp=bufferedReaderErro.readLine()) != null)
result+=(temp+'\n');
BufferedReader bufferedReaderCorr = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((temp=bufferedReaderCorr.readLine()) != null)
result+=(temp+'\n');
int endStrLength=result.length(); process.waitFor(); if(beginStrLength==endStrLength)result+="success!\n";
//JOptionPane.showConfirmDialog(null,result,"结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
return result;
} //内部类,显示窗口
public class ResultShow implements WindowListener{
public JTextArea text;//文本显示区
public JDialog Dialog;//面板 //构造函数窗口大小和位置
public ResultShow(int sX,int sY,int pX,int pY){
text=new JTextArea();
text.setLineWrap(false);//自动换行
text.setWrapStyleWord(false);//自动换行换单词
text.setEditable(false);
Dialog=new JDialog();
JScrollPane sp=new JScrollPane(text);//添加带滚动条(JScrollPane)的文本编辑框JTextArea
Dialog.add(sp);
Dialog.setSize(sX,sY);
Dialog.setLocation(pX,pY);
Dialog.setResizable(false);//大小不可变
Dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//关闭
Dialog.addWindowListener(this);//窗口监听%%%%%%%
} //导入结果并显示
public void addStr(String result){
//text.setText(result);
text.append(result);
Dialog.setVisible(true);
} //重定义窗口关闭
public void windowClosing(WindowEvent e) {
Dialog.setVisible(false);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
} //main测试
public static void main(String args[]) throws IOException, InterruptedException{
Commond C=new Commond(600,400,100,100);
String s=C.getInfoDOS("BB.java","D:\\",false);show.addStr(s);
s=C.getInfoDOS("BB.java","D:\\",true);show.addStr(s);
}
}
Commond.java
App包:
主要是一些简单的功能:如回文串判断、数字翻译成英文...没啥技术含量.....
package App; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Scanner; import javax.swing.JOptionPane; public class CountString{
private static String word[]=new String[10000];
private static int numWord; public static void main(String args[]) throws IOException{
CountString a=new CountString("D:/test.txt");
} public CountString(String path) throws IOException{
numWord=0;
Fread(path);
String s=new String(("|--以w开头的单词数量: "+countBeginWith('w'))+
("\n|--含有or的单词数量: "+countInclude("or"))+
("\n|--含有长为3的单词数量: "+countLength(3))
);
JOptionPane.showConfirmDialog(null,s,"回文数",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
}//构造函数 private static void Fread(String path) throws IOException{
int c;String temp = "";
RandomAccessFile f=new RandomAccessFile(path,"r");
while((c=f.read()) !=-1){
if((char)c==' ' || (char)c=='\n'){
if(temp!=""){//System.out.println(temp);
if(isWord(temp)==0) System.out.println(1);
word[numWord++]=temp.toLowerCase();//else
temp="";
}
while((char)c==' ' || (char)c=='\n'){c=f.read();}
}
if(c==13)continue;//System.out.print("->"+(char)c+"("+c+")");
temp+=(char)c;
}
//for(int j=0;j<numWord;j++)System.out.println(word[j]);
}//读取文件成 private static int isWord(String temp){
int len=temp.length();
for(int i=0;i<len;i++)
if(temp.charAt(i)<'A'||temp.charAt(i)>'z')
return 0;
return 1;
}//判断输入是否是合法单词 private static int countBeginWith(char c){
int count=0;
if(c>'z')c=(char)(c-('A'-'a'));
for(int i=0;i<numWord;i++)
if(word[i].charAt(0)==c)
count++;
return count;
}//统计单词中以char c开头的数目(不分大小写) private static int countInclude(String c){
int count=0;
for(int i=0;i<numWord;i++)
if(word[i].indexOf(c)!=-1)
count++;
return count;
}//统计单词中含有String c的单词数(不分大小写) private static int countLength(int c){
int count=0;
for(int i=0;i<numWord;i++)
if(word[i].length()==c)
count++;
return count;
}//统计单词中长为c的数量
}
CountString.java
package App;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JProgressBar; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.IOException;
import java.io.RandomAccessFile; public class FQiuHe{
static BarThread stepper;
static JProgressBar aJProgressBar;
String up=null,down=null;
static JLabel Lup;
static JLabel Ldown;
//---
static int sum=0;
static double sumpross=0.0;
public static String bianLiang[]=new String[20000];
public static double shuZhi[]=new double[20000];
//进度条线程
static class BarThread extends Thread{
private static int DELAY = 1;
JProgressBar progressBar;
//构造方法
public BarThread(JProgressBar bar) {
progressBar = bar;
}
//线程体
public void run(){
for(int i=0;i<sum;i++){
try {
if(sum-i-1<1000)Ldown.setText("正在计算......剩余 "+(sum-(i+1))+" ms");
else Ldown.setText("正在计算......剩余 "+(sum-(i+1))/1000+" s");
Thread.sleep(DELAY);
sumpross+=shuZhi[i];
Lup.setText("当前正在计算"+bianLiang[i]+"....."+(i+1)+"/"+sum+".....总和为: "+sumpross);
int value = progressBar.getValue();
progressBar.setValue(value +1);
} catch (InterruptedException e) {}
}
Ldown.setText("计算完成!");
int c;
if((c=JOptionPane.showConfirmDialog(null,"总和为: "+sumpross,"计算结果",
JOptionPane.YES_OPTION,JOptionPane.INFORMATION_MESSAGE))==0 || c==1){
stepper.stop();
return;
}
}
}
public FQiuHe(String path,JFrame parent){//界面构造函数
//if(Read(path)==false)
//JOptionPane.showMessageDialog(null,"发现文件数据有误...","错误提醒",JOptionPane.WARNING_MESSAGE);
//else{
Read(path);
JDialog frm= new JDialog(parent,"JFrame with JProgressBar",true);
frm.setLayout(null);
//frm.setFocusable(true);
//frm.setAlwaysOnTop(true);
//设置进度条属性
aJProgressBar = new JProgressBar(0,sum);//进度条从0-sum
aJProgressBar.setStringPainted(true);
aJProgressBar.setBackground(Color.white);
aJProgressBar.setForeground(Color.red);
aJProgressBar.setBounds(0,25, 600,110);
frm.add(aJProgressBar);
//2个label
Lup=new JLabel("up");
Lup.setBounds(0,0,600, 25);
frm.add(Lup);
Ldown=new JLabel(down);
Ldown.setBounds(0,135,600,35);
frm.add(Ldown);
//设置窗口属性
//frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setSize(600, 200);
centerWindow(frm);
frm.setResizable(false);
stepper=new BarThread(aJProgressBar);
stepper.start();
frm.setVisible(true);
//} }
private void centerWindow(Window f) {//设置窗口居中
Toolkit tk=f.getToolkit();//获得显示屏桌面窗口的大小
Dimension dm=tk.getScreenSize();
f.setLocation((int)(dm.getWidth()-f.getWidth())/2,(int)(dm.getHeight()-f.getHeight())/2);//让窗口居中显示
}
static boolean Read(String path){//读取文件函数
try{
sum=0;
sumpross=0.0;
//RandomAccessFile f=new RandomAccessFile(args[0],"r");
RandomAccessFile f=new RandomAccessFile(path,"rw");
String s,temp;
while((s=f.readLine())!=null){
s=s.trim();
int pos=s.indexOf("=");//System.out.println(s+" "+pos);
if(pos==-1||pos==0);//return false;
else{
shuZhi[sum]=Double.valueOf(s.substring(s.indexOf("=")+1));
bianLiang[sum++]=new String(s.substring(0,s.indexOf("=")));
}
}
}catch(IOException e){
System.out.println("raise problem");
e.printStackTrace();
return false;
}
return true;
}
public static void main(String args[]) {//main函数
JFrame v=new JFrame();
FQiuHe a=new FQiuHe("D:/test.txt",v);
} }
FQiuHe.java
package App; import javax.swing.JOptionPane; public class HuiWen{
public static void main(String args[]){
HuiWen a=new HuiWen();
}
public HuiWen(){
try{
String sa,sb;
StringBuffer SB;
do{
while(true){
sb=JOptionPane.showInputDialog(null,"请输入一个1~9999的整数","回文数",JOptionPane.INFORMATION_MESSAGE);
if(sb.isEmpty()){
JOptionPane.showMessageDialog(null,"还没输入呢...","回文数",JOptionPane.WARNING_MESSAGE);
continue;
}//输入是否为空
try{
if(Integer.parseInt(sb)<1 || Integer.parseInt(sb)>9999){
JOptionPane.showMessageDialog(null,"请输入1~9999之间的整数...","回文数",JOptionPane.WARNING_MESSAGE);
continue;
}//输入错误
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,"输入错误...","回文数",JOptionPane.WARNING_MESSAGE);
continue;
}//输入不合法控制
SB=new StringBuffer(sb);//调用reverse用StringBuffer
sa=SB.reverse().toString(); //调用equals要用String,这里需要类型转换1
if(true)break;
}
}while(JOptionPane.showConfirmDialog(null,sb.equals(sa),"回文数",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE)==0);
}catch(Exception e){}
}
}
HuiWen.java
package App; import java.io.InputStream;
import java.io.IOException; import javax.swing.JOptionPane;
public class NumExchangeEnglish
{
private static String x[]={"zero","one","two","three","four","five","six","seven","eight","nine"} ;
private static String y[]={"ten","eleven","twelve","thirteen","fourteen","fifteen", "sixteen","seventeen","eighteen","nineteen"};
private static String z[]={"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"}; //按Col+Z结束状态标记
private static boolean ok=true;
//错误类型变量
private static int ErrorState=0;
//输入错误种类
private static String ErrorKind[]={"其他错误输入.","数字应在0-99之间.","单词输入不合法."};
//检测是不是num
private static boolean CheckNum(StringBuffer a)
{
ErrorState=0;
String temp=a.toString();
temp=temp.trim(); //System.out.println(temp);
//判断是否全是数字
if(temp.charAt(0)=='0' && temp.length()!=1)return false;
for(int i=0;i<temp.length();i++)
{
if(temp.charAt(i)<'0'||temp.charAt(i)>'9')return false;
}
//长度要小于2的数字才满足在0-99之间
if(temp.length()>2){ErrorState=1;return false;}
//判断是否满足0-99
int num=Integer.parseInt(temp);
if(num<0 || num>99)
{
ErrorState=1;
return false;
}
//System.out.println(num);
return true;
}
//检测是不是标准英语
private static boolean CheckEnglish(StringBuffer a)
{
//如果已经是数字型的啦就不用考虑是英语转成数字问题啦
if(ErrorState!=0)return false; int i;
String temp=a.toString();
temp=temp.trim();
temp=temp.toLowerCase(); //System.out.println(temp);
//按空格拆分
int pos=temp.indexOf(' ');//System.out.println(pos);
if(pos==-1)
{
int yes=0;
for(i=0;i<10;i++)if(temp.equals(x[i]))return true;
for(i=0;i<10;i++)if(temp.equals(y[i]))return true;
for(i=0;i<8;i++)if(temp.equals(z[i]))return true;
ErrorState=2;
return false;
}
else
{
//拆分成两个单词
String ShiWei=temp.substring(0,pos);//System.out.println(ShiWei);
int lastpos=temp.lastIndexOf(' ');
if(lastpos==pos)//排除thirty one one情况
{
String GeWei=temp.substring(lastpos+1);//System.out.println(GeWei);
//检测第一个单词是否合法(十位)
int firstOk=0;
for(i=0;i<8;i++)if(ShiWei.equals(z[i])){firstOk=1;break;}
if(firstOk==0){ErrorState=2;return false;}
else
{
for(i=1;i<10;i++)if(GeWei.equals(x[i])){firstOk=2;break;}
if(firstOk==1){ErrorState=2;return false;}
}
return true;
}
else
{
ErrorState=2;
return false;
}
}
}
//数字转英语
private static void NumToEnglish(StringBuffer a)
{
String JieGuo;
//转成int类num
String temp=a.toString();
temp=temp.trim();
int num=Integer.parseInt(temp);
//一个单词可以搞定的直接输出
if(num<10)JieGuo=new String(x[num]);
else if(num<20)JieGuo=new String(y[num-10]);
else if(num==20)JieGuo=new String(z[0]);
else
{
//获取十位和个位数据
int ShiWei,GeWei;
ShiWei=num/10;GeWei=num%10;
//转化成英语
if(GeWei==0)JieGuo=new String(z[ShiWei-2]);
else JieGuo=new String(z[ShiWei-2]+" "+x[GeWei]);
}
JOptionPane.showConfirmDialog(null,a+"的翻译结果是: "+JieGuo,"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
}
//英语转数字
private static void EnglishToNum(StringBuffer a)
{ int i;
String temp=a.toString();
temp=temp.trim();
temp=temp.toLowerCase(); //System.out.println(temp);
//按空格拆分
int pos=temp.indexOf(' ');//System.out.println(pos);
if(pos==-1)
{
for(i=0;i<10;i++)if(temp.equals(x[i])){
//System.out.println(i);
JOptionPane.showConfirmDialog(null,a+"的翻译结果是: "+(i),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
return;
}
for(i=0;i<10;i++)if(temp.equals(y[i])){
//System.out.println(i+10);
JOptionPane.showConfirmDialog(null,a+"的翻译结果是: "+(i+10),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
return;
}
for(i=0;i<8;i++)if(temp.equals(z[i])){
//System.out.println((i+2)*10);
JOptionPane.showConfirmDialog(null,a+"的翻译结果是: "+((i+2)*10),"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
return;
}
}
else
{
//拆分成两个单词
String ShiWei=temp.substring(0,pos);//System.out.println(ShiWei);
int lastpos=temp.lastIndexOf(' ');
String GeWei=temp.substring(lastpos+1);//System.out.println(GeWei);
int sum=0;
for(i=0;i<8;i++)if(ShiWei.equals(z[i])){sum+=(i+2)*10;break;}
for(i=0;i<10;i++)if(GeWei.equals(x[i])){sum+=i;break;}
//System.out.println(sum);
JOptionPane.showConfirmDialog(null,a+"的翻译结果是: "+sum,"翻译结果",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
}
}
//读入一行返回String
private static StringBuffer ReadLine(InputStream in){
StringBuffer SB=new StringBuffer();
try {
while(true){ int i=in.read();
while(i!='\n' && i!=-1)
{
SB.append((char)i);
i=in.read();
}
System.out.println(i);
if(i==-1)
{
ok=false;
return SB;
}
String data=SB.toString();
data=data.trim();
if(data.length()==0)continue;//System.out.println(data.length());
return SB;
}
}
catch(IOException e)
{
System.err.println("发生异常:"+e);
e.printStackTrace();
return SB;
}
}
public NumExchangeEnglish(){
StringBuffer data;
String s;
try{
while(ok){
s=JOptionPane.showInputDialog(null,"请输入待翻译的数","中英互译",JOptionPane.INFORMATION_MESSAGE);
if(s.isEmpty()){
JOptionPane.showMessageDialog(null,"还没输入呢...","回文数",JOptionPane.WARNING_MESSAGE);
continue;
}
data=new StringBuffer(s);
if(ok==false)return;
if(CheckNum(data)==true)NumToEnglish(data);
else if(CheckEnglish(data)==true)EnglishToNum(data);
else{
JOptionPane.showMessageDialog(null,ErrorKind[ErrorState],"回文数",JOptionPane.WARNING_MESSAGE);
}
}
}catch(Exception e){}
}
public static void main(String args[]){
NumExchangeEnglish a=new NumExchangeEnglish();
}
}
NumExchangeEnglish.java