javaGUI记事本(含源程序)
作者:互联网
javaGUI记事本(含源程序)
view(核心代码)
package com.whj.view;
import com.whj.util.Clock;
import com.whj.util.MQFontChooser;
import com.whj.util.SystemParam;
import com.whj.util.TestLine;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
@SuppressWarnings("ALL")
public class NotepadMainFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = 8585210209467333480L;
private JPanel contentPane;
private JTextArea textArea;
private JMenuItem itemOpen;
private JMenuItem itemSave;
//1.新建
//2.修改过的
//3.保存过的
int flag = 0;
//当前文件的名
String currenFileName = null;
PrintJob p = null;
Graphics g = null;
String currentPath = null;
//背景颜色
JColorChooser jcc1 = null;
Color color = Color.BLACK;
//文本的行数和列数
int linenum = 1;
int columnnum = 1;
//撤销管理器
public UndoManager undoMgr = new UndoManager();
//剪切板
public Clipboard clipboard = new Clipboard("系统剪切板");
private JMenuItem itemSaveAs;
private JMenuItem itemNew;
private JMenuItem itemPage;
private JSeparator separator;
private JMenuItem itemPrint;
private JMenuItem itemExit;
private JSeparator separator_1;
private JMenu itemEdit;
private JMenu itFormat;
private JMenu itemCheck;
private JMenu itemHelp;
private JMenuItem itemSearchForHelp;
private JMenuItem itemAboutNotepad;
private JMenuItem itemUndo;
private JMenuItem itemCut;
private JMenuItem itemCopy;
private JMenuItem itemPaste;
private JMenuItem itemDelete;
private JMenuItem itemFind;
private JMenuItem itemFindNext;
private JMenuItem itemReplace;
private JMenuItem itemTurnTo;
private JMenuItem itemSelectAll;
private JMenuItem itemTime;
private JMenuItem itemFont;
private JMenuItem itemColor;
private JMenuItem itemFontColor;
private JCheckBoxMenuItem itemNextLine;
private JScrollPane scrollPane;
private JCheckBoxMenuItem itemStatement;
private JToolBar toolState;
public static JLabel label_1;
private JLabel label_2;
private JLabel label_3;
int length = 0;
int sum = 0;
/**
* @param args application main start run
*/
public static void main (String []args){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
NotepadMainFrame frame = new NotepadMainFrame();
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
GregorianCalendar c =new GregorianCalendar();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
private JPopupMenu popupMenu;
private JMenuItem popM_Undo;
private JMenuItem popM_Cut;
private JMenuItem popM_Copy;
private JMenuItem popM_Paste;
private JMenuItem popM_Delete;
private JMenuItem popM_SelectAll;
private JMenuItem popM_toLeft;
private JMenuItem popM_showUnicode;
private JMenuItem popM_closeIMe;
private JMenuItem popM_InsertUnicode;
private JMenuItem popM_RestartSelect;
private JSeparator separator_2;
private JSeparator separator_3;
private JSeparator separator_4;
private JSeparator separator_5;
private JMenuItem itemRedo;
private JSeparator separator_6;
private JSeparator separator_7;
private JSeparator separator_8;
private JMenuItem popM_Redo;
/**
* create the frame
*/
//下面开始创建窗口
public NotepadMainFrame(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
setTitle("无标题");
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setBounds(100,100,521,572);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu itemFile = new JMenu("文件F");
itemFile.setMnemonic('f');
menuBar.add(itemFile);
itemNew = new JMenuItem("新建(n)",'n');
itemNew.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, Event.CTRL_MASK));
itemNew.addActionListener(this);
itemFile.add(itemNew);
itemOpen = new JMenuItem("打开(0)",'0');
itemOpen.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O,Event.CTRL_MASK));
itemOpen.addActionListener(this);
itemFile.add(itemOpen);
itemSave = new JMenuItem("保存(s)",'s');
itemSave.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,Event.CTRL_MASK));
itemSave.addActionListener(this);
itemFile.add(itemSave);
itemSaveAs = new JMenuItem("另存为(A)");
itemSaveAs.addActionListener(this);
itemFile.add(itemSaveAs);
separator = new JSeparator();
itemFile.add(separator);
itemPage = new JMenuItem("页面设置(U)",'U');
itemPage.addActionListener(this);
itemFile.add(itemPage);
itemPrint = new JMenuItem("打印(p)...",'p');
itemPrint.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.Event.CTRL_MASK));
itemPrint.addActionListener(this);
itemFile.add(itemPrint);
separator_1 = new JSeparator();
itemFile.add(separator_1);
itemExit = new JMenuItem("退出(X)",'x');
itemExit.addActionListener(this);
itemFile.add(itemExit);
itemEdit = new JMenu("编辑(E)");
itemEdit.setMnemonic('E');
menuBar.add(itemEdit);
itemRedo = new JMenuItem("恢复(R)");
itemRedo.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, Event.CTRL_MASK));
itemRedo.addActionListener(this);
itemEdit.add(itemRedo);
itemCut = new JMenuItem("剪切(X)");
itemCut.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X,Event.CTRL_MASK));
itemEdit.addActionListener(this);
separator_6 = new JSeparator();
itemEdit.add(separator_6);
itemEdit.add(itemCut);
itemCopy = new JMenuItem("复制(C)",'C');
itemCopy.addActionListener(this);
itemCopy.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C,Event.CTRL_MASK));
itemEdit.add(itemCopy);
itemDelete = new JMenuItem("删除(L)",'L');
itemDelete.addActionListener(this);
itemDelete.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L,Event.CTRL_MASK));
itemEdit.add(itemDelete);
separator_7 = new JSeparator();
itemEdit.add(separator_7);
itemFind = new JMenuItem("查找(F)",'F');
itemFind.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F,Event.CTRL_MASK));
itemFind.addActionListener(this);
itemEdit.add(itemFind);
itemFindNext = new JMenuItem("查找下一个(N)",'N');
itemFindNext.setAccelerator(KeyStroke.getKeyStroke("F3"));
itemFind.addActionListener(this);
itemEdit.add(itemFindNext);
itemReplace = new JMenuItem("替换(R)",'R');
itemReplace.addActionListener(this);
itemReplace.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,Event.CTRL_MASK));
itemEdit.add(itemReplace);
itemTurnTo = new JMenuItem("转到(G)",'G');
itemTurnTo.addActionListener(this);
itemTurnTo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, Event.CTRL_MASK));
itemEdit.add(itemTurnTo);
itemSelectAll = new JMenuItem("全选(A)",'A');
itemSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK));
itemSelectAll.addActionListener(this);
separator_8 = new JSeparator();
itemEdit.add(separator_8);
itemEdit.add(itemSelectAll);
itemTime = new JMenuItem("时间/日期(D)",'D');
itemTime.addActionListener(this);
itemTime.setAccelerator(KeyStroke.getKeyStroke("F5"));
itemEdit.add(itemTime);
itFormat = new JMenu("格式(O)");
itFormat.setMnemonic('O');
menuBar.add(itFormat);
itemNextLine = new JCheckBoxMenuItem("自动换行(W)");
itemNextLine.addActionListener( this);
itFormat.add(itemNextLine);
itemFont = new JMenuItem("字体大小(F)...");
itemFont.addActionListener(this);
itFormat.add(itemFont);
itemColor = new JMenuItem("背景颜色(C)...");
itemColor.addActionListener(this);
itFormat.add(itemColor);
itemFontColor = new JMenuItem("字体颜色(I)...");
itemFontColor.addActionListener(this);
itFormat.add(itemFontColor);
itemCheck = new JMenu("查看(V)");
itemCheck.setMnemonic('V');
menuBar.add(itemCheck);
itemStatement = new JCheckBoxMenuItem("状态栏(S)");
itemStatement.addActionListener(this);
itemCheck.add(itemStatement);
itemHelp = new JMenu("帮助(H)");
itemHelp.setMnemonic('H');
menuBar.add(itemHelp);
itemSearchForHelp = new JMenuItem("查看帮助(H)",'H');
itemSearchForHelp.addActionListener(this);
itemHelp.add(itemSearchForHelp);
itemAboutNotepad = new JMenuItem("关于记事本(A)",'A');
itemAboutNotepad.addActionListener(this);
itemHelp.add(itemAboutNotepad);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5,5,5,5));
//设置边框布局
contentPane.setLayout(new BorderLayout(0,0));
setContentPane(contentPane);
textArea = new JTextArea();
//VERICAL垂直 HORIZNTAL水平
scrollPane = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
TestLine view = new TestLine();
scrollPane.setRowHeaderView(view);
popupMenu = new JPopupMenu();
addPopup(textArea,popupMenu);
popM_Undo = new JMenuItem("撤销(U)");
popM_Undo.addActionListener(this);
popupMenu.add(popM_Undo);
popM_Redo = new JMenuItem("恢复(R)");
popM_Redo.addActionListener(this);
popupMenu.add(popM_Redo);
separator_2 = new JSeparator();
popupMenu.add(separator_2);
popM_Cut = new JMenuItem("剪切(T)");
popM_Cut.addActionListener(this);
popupMenu.add(popM_Cut);
popM_Copy = new JMenuItem("复制(C)");
popM_Copy.addActionListener(this);
popupMenu.add(popM_Copy);
popM_Paste = new JMenuItem("粘贴(P)");
popM_Paste.addActionListener(this);
popupMenu.add(popM_Paste);
popM_Delete = new JMenuItem("删除(D)");
popM_Delete.addActionListener(this);
popupMenu.add(popM_Delete);
separator_3 = new JSeparator();
popupMenu.add(separator_3);
popM_SelectAll = new JMenuItem("全选(A)");
popM_SelectAll.addActionListener(this);
popupMenu.add(popM_SelectAll);
separator_4 = new JSeparator();
popupMenu.add(separator_4);
popM_toLeft = new JMenuItem("从左到右阅读顺序(R)");
popM_toLeft.addActionListener(this);
popupMenu.add(popM_toLeft);
popM_showUnicode = new JMenuItem("显示Unicode控制字符串(S)");
popM_showUnicode.addActionListener(this);
popupMenu.add(popM_showUnicode);
popM_InsertUnicode = new JMenuItem("插入Unicode控制字符(I)");
popM_InsertUnicode.addActionListener(this);
popupMenu.add(popM_InsertUnicode);
separator_5 = new JSeparator();
popupMenu.add(separator_5);
popM_closeIMe = new JMenuItem("关闭IME(L)");
popM_closeIMe.addActionListener(this);
popupMenu.add(popM_closeIMe);
popM_RestartSelect = new JMenuItem("汉字重选(R)");
popM_RestartSelect.addActionListener(this);
popupMenu.add(popM_RestartSelect);
//添加到面板中【中间】
contentPane.add(scrollPane,BorderLayout.CENTER);
//添加撤销管理器
textArea.getDocument().addUndoableEditListener(undoMgr);
toolState = new JToolBar();
toolState.setSize(textArea.getSize().width,10);
label_1 = new JLabel("当前系统时间 : "+hour + ":"+min+ ":"+second + " ");
toolState.add(label_1);
toolState.addSeparator();
label_2 = new JLabel("第" + linenum + "行,第" + columnnum + "列");
toolState.add(label_2);
toolState.addSeparator();
label_3 = new JLabel("一共" + length + "字");
toolState.add(label_3);
textArea.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
JTextArea editArea = (JTextArea)e.getSource();
try {
int caretpos = editArea.getCaretPosition();
linenum = editArea.getLineOfOffset(caretpos);
columnnum = caretpos -textArea.getLineEndOffset(linenum);
linenum += 1;
label_2.setText("第"+linenum+"行,第"+(columnnum+1)+"列");
length = NotepadMainFrame.this.textArea.getText().toString().length();
label_3.setText("一共" + length +"字");
} catch (BadLocationException ex) { ex.printStackTrace(); }
}});
contentPane.add(toolState,BorderLayout.SOUTH);
toolState.setVisible(false);
toolState.setFloatable(false);
Clock Clock = new Clock();
Clock.start();
//创建弹出菜单
final JPopupMenu jp = new JPopupMenu();
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton()==MouseEvent.BUTTON3){
jp.show(e.getComponent(),e.getX(),e.getY());//在鼠标位置显示弹出式菜单
}
}
});
isChanged();
this.MainFrameWidowListene();
}
///------------------------------------------------------------------------------------------------------------
/**
* 是否变化
*/
private void isChanged(){
textArea.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
Character c = e.getKeyChar();
if (c != null && !textArea.getText().toString().equals("")) {
flag = 2;
}
}
});
}
/**
* 新建的或保存退出只有两个选择
* */
private void MainFrameWidowListene() {
this.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if(flag==2 && currentPath==null){
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否将更改保存到无标题?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if (result ==JOptionPane.OK_OPTION){
NotepadMainFrame.this.savAs();
}else if(result==JOptionPane.NO_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}else if(flag==2 && currentPath!=null){
//1.弹出小窗口
//2.(刚启动记事本为0,刚新建文档为1)条件下修改后
int result =JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否更将改保存到无标题"+currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result==JOptionPane.OK_OPTION){
NotepadMainFrame.this.savAs();
}else if(result==JOptionPane.NO_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}else if(flag==2 && currentPath !=null){
//1.这是弹出小窗口
//2.刚开始启动记事本为0,刚新建文档为1,条件修改后
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否将更改保存到"+currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result==JOptionPane.OK_OPTION){
NotepadMainFrame.this.save();
}else if(result==JOptionPane.NO_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}else{
//这是小弹窗口
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"确定要关闭?","系统提示",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if (result==JOptionPane.OK_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
}
});
}
/**
* 行为动作
* */
public void actionPerformed(ActionEvent e){
if (e.getSource()==itemOpen){//打开
OpenFile();
}else if(e.getSource()==itemSave){//保存
save();
}else if(e.getSource()==itemSaveAs){//另存为
savAs();
}else if(e.getSource()==itemNew){//新建
newFile();
}else if(e.getSource()==itemExit){//退出
exit();
}else if(e.getSource()==itemPage){//页面设置
//这个方法 百度找的 具体用法不知道
PageFormat pf = new PageFormat();
PrinterJob.getPrinterJob().pageDialog(pf);
}else if(e.getSource()==itemPrint) {//打印
Print();
}else if(e.getSource()==itemUndo && e.getSource()==popM_Undo) {//撤销
if(undoMgr.canRedo()){
undoMgr.redo();
}
}else if(e.getSource()==itemRedo || e.getSource()==popM_Redo){//恢复
if(undoMgr.canRedo()){
undoMgr.redo();
}
}else if(e.getSource()==itemCut || e.getSource()==popM_Cut){//剪切
cut();
}else if(e.getSource()==itemCopy || e.getSource()==popM_Copy){//复制
copy();
}else if(e.getSource()==itemPaste || e.getSource()==popM_Paste){//粘贴
paste();
}else if(e.getSource()==itemDelete || e.getSource()==popM_Delete){//删除
String tem = textArea.getText().toString();
textArea.setText(tem.substring(0,textArea.getSelectionStart()));
}else if(e.getSource()==itemFind) {//查找
mySearch();
}else if(e.getSource()==itemFindNext){//查找下一个
mySearch();
}else if(e.getSource()==itemReplace){//替换
mySearch();
}else if(e.getSource()==itemTurnTo){
turnTo();
}else if(e.getSource()==itemSelectAll || e.getSource()==popM_SelectAll){
textArea.selectAll();
}else if(e.getSource()==itemTime){//日期时间
textArea.append(hour+":"+min+":"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH));
}else if(e.getSource()==itemNextLine){//自动换行
//设置文本区的换行策略。如果设置为true ,则当行的长度大于所分配的宽度时,让他自己动换行。此属性默认值为false
if(itemNextLine.isSelected()){
textArea.setLineWrap(true);
}else {
textArea.setLineWrap(false);
}
}else if (e.getSource()==itemFont){//设置字体大小
//将字体选择器,参数字体预设值
MQFontChooser fontChooser = new MQFontChooser(textArea.getFont());
fontChooser.showFontDialog(this);
Font font = fontChooser.getSelectFont();
//将字体设置textArea中
textArea.setFont(font);
}else if (e.getSource()==itemColor){//设置背景颜色
JColorChooser jcc1 = new JColorChooser();
JOptionPane.showMessageDialog(this,jcc1,"选择字体颜色",-1);
color = jcc1.getColor();
textArea.setBackground(color);
}else if(e.getSource()==itemFontColor){
JColorChooser jcc1 = new JColorChooser();
JOptionPane.showMessageDialog(this,jcc1,"选择字体颜色",-1);
color = jcc1.getColor();
textArea.setBackground(color);
}else if(e.getSource()==itemStatement){//设置状态
if(itemStatement.isSelected()){
toolState.setVisible(true);
}else {
toolState.setVisible(false);
}
}else if(e.getSource()==itemSearchForHelp){
JOptionPane.showMessageDialog(this,"程序员压力其实也没有那么大,不就是时不时加加班,","产品经理来一句明天休息带个电脑吧",+1);
}else if (e.getSource()==itemAboutNotepad){
JOptionPane.showMessageDialog(this,"记事本v1.0【javaSE【吴海军】【面向对象】制作","软件书说明",+1);
}
}
// ----------------------------------------------------------------------------------------------------------
private void turnTo() {
final JDialog gotoDialog = new JDialog(this,"转到下列行");
JLabel gotoLabel = new JLabel("行数(L)");
final JTextField linenum = new JTextField(5);
linenum.setText("1");
linenum.selectAll();
JButton okButton = new JButton("确定");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int totalLine = textArea.getLineCount();
int[] lineNumber = new int[totalLine + 1];
String s = textArea.getText();
int pos = 0,t = 0;
while (true){
pos = s.indexOf("\12",pos);
System.out.println("pos索引"+ pos);
if(pos == -1){
lineNumber[t++] = pos++;
break;
}
}
int gt = 1;
try {
gt = Integer.parseInt(linenum.getText());
}catch (NumberFormatException efe){
JOptionPane.showMessageDialog(null,"请输入行数","提示",JOptionPane.PLAIN_MESSAGE);
linenum.requestFocus(true);
return;
}
if (gt<2|| gt>=totalLine) {
if (gt < 2)
textArea.setCaretPosition(0);
else
textArea.setCaretPosition(s.length());
}else
textArea.setCaretPosition(lineNumber[gt - 2]+1);
gotoDialog.dispose();
}
});
JButton calncelButton = new JButton("取消");
calncelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gotoDialog.dispose();
}
});
Container con = gotoDialog.getContentPane();
con.setLayout(new FlowLayout());
con.add(gotoLabel);
con.add(linenum);
con.add(okButton);
con.add(calncelButton);
gotoDialog.setSize(200,100);
gotoDialog.setResizable(false);
gotoDialog.setLocation(300,280);
gotoDialog.setVisible(true);
}
private void mySearch() {
final JDialog finaldDailog = new JDialog(this,"替换与查找",true);
Container con = finaldDailog.getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel searchContentLabel = new JLabel("查找内容(N) :");
JLabel replaceContentLabel = new JLabel("替换为(P) :");
final JTextField finalText = new JTextField(22);
final JTextField replaceText = new JTextField(22);
final JCheckBox matchase = new JCheckBox("区分大小写");
ButtonGroup bGroup = new ButtonGroup();
final JRadioButton up = new JRadioButton("向上(U)");
final JRadioButton down = new JRadioButton("向下(D)");
down.setSelected(true);
bGroup.add(up);
bGroup.add(down);
JButton searchNext = new JButton("查找下一个(F)");
JButton replace = new JButton("替换(R)");
final JButton replaceAll = new JButton("全部替换(A)");
searchNext.setPreferredSize(new Dimension(110,22));
replace.setPreferredSize(new Dimension(110,22));
replaceAll.setPreferredSize(new Dimension(110,22));
//替换按钮事件处理
replace.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (replaceText.getText().length()==0 && textArea.getSelectedText()!=null)
textArea.replaceSelection("");
if (replaceText.getText().length() >0 && textArea.getSelectedText()!=null)
textArea.replaceSelection(replaceText.getText());
}
});
replaceAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setCaretPosition(0);//将光标放到编码区开头
int a = 0, b = 0, replaceCount = 0;
if (finalText.getText().length()==0){
JOptionPane.showMessageDialog(finaldDailog,"请填写查找内容","提示",JOptionPane.WARNING_MESSAGE);
finalText.requestFocus(true);
return;
}
while (a > -1){
int FindStartPos = textArea.getCaretPosition();
String str1,str2,str3,str4,strA,strB;
str1 = textArea.getText();
str2 = str1.toLowerCase();
str3 = finalText.getText();
str4 = str3.toLowerCase();
if(matchase.isSelected()){
strA = str1;
strB = str3;
}else {
strA = str2;
strB = strA;
}
}
if(a>1){
if (up.isSelected()){
textArea.setCaretPosition(a);
b = finalText.getText().length();
textArea.select(a,a + b);
}else if(down.isSelected()){
textArea.setCaretPosition(a);
b = finalText.getText().length();
textArea.select(a,a + b);
}
else {
if (replaceCount ==0){
JOptionPane.showMessageDialog(finaldDailog,"找不到你查找的内容!","记事本",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(finaldDailog,"成功替换"+replaceCount + "个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE);
}
}
if(replaceText.getText().length() == 0 && textArea.getSelectedText() != null){
textArea.replaceSelection("");
replaceCount++;
}
if (replaceText.getText().length() > 0 && textArea.getSelectedText() != null){
textArea.replaceSelection(replaceText.getText());
replaceCount++;
}
if (replaceText.getText().length() > 0 && textArea.getSelectedText() != null){
textArea.replaceSelection(replaceText.getText());
replaceCount++;
}
}//end while
}
});//"替换全部"按钮的事件处理结束
//查找下一个 按钮事件处理
searchNext.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int a = 0,b = 0;
int FindStartPos = textArea.getCaretPosition();
String str1,str2,str3,str4,strA,strB;
str1 = textArea.getText();
str2 = str1.toLowerCase();
str3 = finalText.getText();
str4 = str3.toLowerCase();
//区分大小写 checkBox 被选中
if(matchase.isSelected()){
strA = str1;
strB = str3;
}else {
strA = str2;
strB = strA;
}
if (up.isSelected()){
if (textArea.getSelectedText()==null){
a = strA.lastIndexOf(strB,FindStartPos - 1);
}else{
a = strA.lastIndexOf(strB,FindStartPos -finalText.getText().length() - 1);
}
}else if(down.isSelected()){
if (textArea.getSelectedText()==null){
a = strA.indexOf(strB,FindStartPos);
}else {
a = strA.indexOf(strB,FindStartPos - finalText.getText().length() + 1);
}
}if (a > 1){
if (up.isSelected()){
textArea.setCaretPosition(a);
b = finalText.getText().length();
textArea.select(a,a + b);
}else if(down.isSelected()){
textArea.setCaretPosition(a);
b = finalText.getText().length();
textArea.select(a,a + b);
}
}else {
JOptionPane.showMessageDialog(null,"找不到你查找的内容!","记事本",JOptionPane.INFORMATION_MESSAGE);
}
}
});/*查找下一个“按钮事件处理结果”*/
//“取消”按钮事件处理
JButton cancel = new JButton("取消");
cancel.setPreferredSize(new Dimension(110,22));
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
finaldDailog.dispose();
}
});
//创建"查找替换"对话框的界面
JPanel bottomPanlel = new JPanel();
JPanel centerPanlel = new JPanel();
JPanel topPanle = new JPanel();
JPanel direction = new JPanel();
direction.setBorder(BorderFactory.createTitledBorder("方向"));
direction.add(up);
direction.add(down);
direction.setPreferredSize(new Dimension(170,60));
JPanel replacePanel = new JPanel();
replacePanel.setLayout(new GridLayout(2, 1));
replacePanel.add(replace);
replacePanel.add(replaceAll);
topPanle.add(searchContentLabel);
topPanle.add(finalText);
topPanle.add(searchNext);
centerPanlel.add(replaceContentLabel);
centerPanlel.add(replaceText);
centerPanlel.add(replacePanel);
bottomPanlel.add(matchase);
bottomPanlel.add(direction);
bottomPanlel.add(bottomPanlel);
con.add(topPanle);
con.add(centerPanlel);
con.add(bottomPanlel);
// 设置"查找替换"对话框的大小。可更改大小否,位置和可见性
finaldDailog.setSize(410,210);
finaldDailog.setResizable(false);
finaldDailog.setLocation(230,280);
finaldDailog.setResizable(true);
}
/**
* 粘贴
*/
private void paste() {
//pransferable 接口,把剪贴板的内容转换成数据
Transferable contents = this.clipboard.getContents(this);
//dataFalvor 类判断是否能剪贴板的内容转换成所需数据类型
DataFlavor flavor = DataFlavor.stringFlavor;
//如果可以转换
if(contents.isDataFlavorSupported(flavor)){
String str;
try {//开始转换
str = (String)contents.getTransferData(flavor);
//如果粘贴时,鼠标已经选中了一些字符
if(this.textArea.getSelectedText()!=null){
//定位被选中的字符的开始位置
int start = this.textArea.getSelectionStart();
//把粘贴的内容替换成被选中的内容
int end = this.textArea.getSelectionEnd();
this.textArea.replaceRange(str,start,end);
}else {
int mouse = this.textArea.getCaretPosition();
//鼠标所在的位置粘贴内容
this.textArea.insert(str,mouse);
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 复制
* */
private void copy() {
//拖动选取文本
String temp = this.textArea.getToolTipText();
//把获取的内容复制到连续的字符器,这个类继承了剪切板接口
StringSelection text = new StringSelection(temp);
//内容放在剪粘板
this.clipboard.setContents(text,null);
}
/**
*
* */
private void cut() {
copy();
int start = this.textArea.getSelectionStart();
//标记结束位置
int end = this.textArea.getSelectionEnd();
//删除选中段
this.textArea.replaceRange("",start,end);
}
/**
* 写
*/
private void Print() {
{
p = getToolkit().getPrintJob(this,"ok",null);
g = p.getGraphics();//p 获取一个用于打印的Graphics 的对象
g.translate(120,200);
this.textArea.printAll(g);
p.end();//释放一下对象
}
}
/**
* 推出按钮,和窗口的红叉实现功能一样的功能
*/
private void exit() {
if(flag==2&& currentPath==null){
//这是弹出小窗口
//1.刚启动记事本为0,刚新建文档为1,条件下修改后
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否将更改保存到"+currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if (result==JOptionPane.OK_OPTION){
NotepadMainFrame.this.save();
}else if(result ==JOptionPane.NO_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}else{
//这是弹出小窗口
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this, JOptionPane.PLAIN_MESSAGE, "确定要关闭?", JOptionPane.YES_NO_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
NotepadMainFrame.this.dispose();
NotepadMainFrame.this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
}
/**
* 新建文件,只有保存过的和改过的需要处理
* privateprivateprivate abc
*/
private void newFile() {
if(flag==0||flag==1){
return;
}else if(flag==2 && this.currentPath==null){
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否将更改保存到无标题?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if (result==JOptionPane.OK_OPTION){
this.savAs();//另存为
}else if(result==JOptionPane.NO_OPTION){
this.textArea.setText("");
this.setTitle("无标题");
flag=1;
}
return;
}else if (flag==2 && this.currentPath!=null){
//2.保存的文件为3 条件下修改后
int result = JOptionPane.showConfirmDialog(NotepadMainFrame.this,"石否将更保存到"+this.currentPath+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result ==JOptionPane.OK_OPTION){
this.save();//直接保存
}else if(result==JOptionPane.NO_OPTION){
this.textArea.setText("");
this.setTitle("无标题");
flag=1;
}
}else if (flag==3){//保存的文件
this.textArea.setText("");
flag=1;
this.setTitle("无标题");
}
}
/**
* 打开文件
*/
private void OpenFile() {
if(flag==2&& this.currentPath==null){
//1.刚刚启动记事本为0,刚新建文件为1 条件下修改后
int result =JOptionPane.showConfirmDialog(NotepadMainFrame.this,"是否将更改的保存到无标题?","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result==JOptionPane.OK_OPTION){
this.save();
}
}
//打开选择框
JFileChooser chooser = new JFileChooser();
//选择文件
int result = chooser.showOpenDialog(this);
if(result==JFileChooser.APPROVE_OPTION){
//取得选取的文件、
File file = chooser.getSelectedFile();
//打开已存在的文件,提前将文件名存起来
currentPath = file.getAbsolutePath();
flag=3;
this.setTitle(this.currentPath);
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"GBK");
br = new BufferedReader(isr);//动态绑定
//读取内容
StringBuffer sb = new StringBuffer();
String line = null;
while ((line=br.readLine())!=null){
sb.append(line+ SystemParam.LINE_SEPARATOP);
}
textArea.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (br!=null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**-----------------------------------------------------------------------------------------------------------------------------------------*/
private void save() {
if (this.currentPath==null){
this.savAs();
if (this.currentPath==null){
return;
}
}
FileWriter fw = null;
//保存
try{
fw = new FileWriter(new File(currentPath));
fw.write(textArea.getText());
fw.flush();
flag=3;
this.setTitle(this.currentPath);
}catch (IOException e1){
e1.printStackTrace();
}finally {
if (fw!=null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 另存为
*/
private void savAs() {
//打开保存边框
JFileChooser chooser = new JFileChooser();
//选择文件
int result = chooser.showSaveDialog(this);
if(result==JFileChooser.APPROVE_OPTION){
//取得选择的文件【文件名是我们自己输入的】
File file = chooser.getSelectedFile();
FileWriter fwNew = null;
//保存
try {
fwNew = new FileWriter(file);
fwNew.write(textArea.getText());
currenFileName = file.getName();
currentPath = file.getAbsolutePath();
//如果比较少,需要写
fwNew.flush();
this.flag=3;
this.setTitle(currentPath);
} catch (IOException e1) {
e1.printStackTrace();
}finally {
try{
if (fwNew!=null){
fwNew.close();
}
}catch (IOException e1){
e1.printStackTrace();
}
}
}
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger()){
showMenu(e);
}
}
public void mouseReleased(MouseEvent e){
if(e.isPopupTrigger()){
showMenu(e);
}
}
private void showMenu(MouseEvent e){
popup.show(e.getComponent(),e.getX(),e.getY());
}
});
}
}
四个工具类
color类
package com.whj.util;
import com.whj.view.NotepadMainFrame;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Clock extends Thread {
@Override
public void run() {
while(true){
GregorianCalendar time = new GregorianCalendar();
int hour = time.get(Calendar.HOUR_OF_DAY);
int min = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
NotepadMainFrame.label_1.setText(" 当前时间:" + hour + ":" + min + ":"+":"+second);
try{
Thread.sleep(1000);
}catch (InterruptedException exception){
}
}
}
}
MQFontChooser类
package com.whj.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* 这是自己找的一份字体选择器的资料
* @author Taylor
*
*/
public class MQFontChooser extends JDialog {
/**
* 选择取消按钮的返回值
*/
public static final int CANCEL_OPTION = 0;
/**
* 选择确定按钮的返回值
*/
public static final int APPROVE_OPTION = 1;
/**
* 中文预览的字符串
*/
private static final String CHINA_STRING = "神马都是浮云!";
/**
* 英文预览的字符串
*/
private static final String ENGLISH_STRING = "Hello Kitty!";
/**
* 数字预览的字符串
*/
private static final String NUMBER_STRING = "0123456789";
// 预设字体,也是将来要返回的字体
private Font font = null;
// 字体选择器组件容器
private Box box = null;
// 字体文本框
private JTextField fontText = null;
// 样式文本框
private JTextField styleText = null;
// 文字大小文本框
private JTextField sizeText = null;
// 预览文本框
private JTextField previewText = null;
// 中文预览
private JRadioButton chinaButton = null;
// 英文预览
private JRadioButton englishButton = null;
// 数字预览
private JRadioButton numberButton = null;
// 字体选择框
private JList fontList = null;
// 样式选择器
private JList styleList = null;
// 文字大小选择器
private JList sizeList = null;
// 确定按钮
private JButton approveButton = null;
// 取消按钮
private JButton cancelButton = null;
// 所有字体
private String [] fontArray = null;
// 所有样式
private String [] styleArray = {"常规", "粗体", "斜体", "粗斜体"};
// 所有预设字体大小
private String [] sizeArray = {"8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "初号", "小初", "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号", "小五", "六号", "小六", "七号", "八号"};
// 上面数组中对应的字体大小
private int [] sizeIntArray = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 42, 36, 26, 24, 22, 18, 16, 15, 14, 12, 10, 9, 8, 7, 6, 5};
// 返回的数值,默认取消
private int returnValue = CANCEL_OPTION;
/**
* 体构造一个字体选择器
*/
public MQFontChooser() {
this(new Font("宋体", Font.PLAIN, 12));
}
/**
* 使用给定的预设字体构造一个字体选择器
* @param font 字体
*/
public MQFontChooser(Font font) {
setTitle("字体选择器");
this.font = font;
// 初始化UI组件
init();
// 添加监听器
addListener();
// 按照预设字体显示
setup();
// 基本设置
setModal(true);
setResizable(false);
// 自适应大小
pack();
}
/**
* 初始化组件
*/
private void init(){
// 获得系统字体
GraphicsEnvironment eq = GraphicsEnvironment.getLocalGraphicsEnvironment();
fontArray = eq.getAvailableFontFamilyNames();
// 主容器
box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
fontText = new JTextField();
fontText.setEditable(false);
fontText.setBackground(Color.WHITE);
styleText = new JTextField();
styleText.setEditable(false);
styleText.setBackground(Color.WHITE);
sizeText = new JTextField("12");
// 给文字大小文本框使用的Document文档,制定了一些输入字符的规则
Document doc = new PlainDocument(){
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
if (getLength() >= 3) {
return;
}
if (!str.matches("[0-9]+") && !str.equals("初号") && !str.equals("小初") && !str.equals("一号") && !str.equals("小一") && !str.equals("二号") && !str.equals("小二") && !str.equals("三号") && !str.equals("小三") && !str.equals("四号") && !str.equals("小四") && !str.equals("五号") && !str.equals("小五") && !str.equals("六号") && !str.equals("小六") && !str.equals("七号") && !str.equals("八号")) {
return;
}
super.insertString(offs, str, a);
sizeList.setSelectedValue(sizeText.getText(), true);
}
};
sizeText.setDocument(doc);
previewText = new JTextField(20);
previewText.setHorizontalAlignment(JTextField.CENTER);
previewText.setEditable(false);
previewText.setBackground(Color.WHITE);
chinaButton = new JRadioButton("中文预览", true);
englishButton = new JRadioButton("英文预览");
numberButton = new JRadioButton("数字预览");
ButtonGroup bg = new ButtonGroup();
bg.add(chinaButton);
bg.add(englishButton);
bg.add(numberButton);
fontList = new JList(fontArray);
styleList = new JList(styleArray);
sizeList = new JList(sizeArray);
approveButton = new JButton("确定");
cancelButton = new JButton("取消");
Box box1 = Box.createHorizontalBox();
JLabel l1 = new JLabel("字体:");
JLabel l2 = new JLabel("字形:");
JLabel l3 = new JLabel("大小:");
l1.setPreferredSize(new Dimension(165, 14));
l1.setMaximumSize(new Dimension(165, 14));
l1.setMinimumSize(new Dimension(165, 14));
l2.setPreferredSize(new Dimension(95, 14));
l2.setMaximumSize(new Dimension(95, 14));
l2.setMinimumSize(new Dimension(95, 14));
l3.setPreferredSize(new Dimension(80, 14));
l3.setMaximumSize(new Dimension(80, 14));
l3.setMinimumSize(new Dimension(80, 14));
box1.add(l1);
box1.add(l2);
box1.add(l3);
Box box2 = Box.createHorizontalBox();
fontText.setPreferredSize(new Dimension(160, 20));
fontText.setMaximumSize(new Dimension(160, 20));
fontText.setMinimumSize(new Dimension(160, 20));
box2.add(fontText);
box2.add(Box.createHorizontalStrut(5));
styleText.setPreferredSize(new Dimension(90, 20));
styleText.setMaximumSize(new Dimension(90, 20));
styleText.setMinimumSize(new Dimension(90, 20));
box2.add(styleText);
box2.add(Box.createHorizontalStrut(5));
sizeText.setPreferredSize(new Dimension(80, 20));
sizeText.setMaximumSize(new Dimension(80, 20));
sizeText.setMinimumSize(new Dimension(80, 20));
box2.add(sizeText);
Box box3 = Box.createHorizontalBox();
JScrollPane sp1 = new JScrollPane(fontList);
sp1.setPreferredSize(new Dimension(160, 100));
sp1.setMaximumSize(new Dimension(160, 100));
sp1.setMaximumSize(new Dimension(160, 100));
box3.add(sp1);
box3.add(Box.createHorizontalStrut(5));
JScrollPane sp2 = new JScrollPane(styleList);
sp2.setPreferredSize(new Dimension(90, 100));
sp2.setMaximumSize(new Dimension(90, 100));
sp2.setMinimumSize(new Dimension(90, 100));
box3.add(sp2);
box3.add(Box.createHorizontalStrut(5));
JScrollPane sp3 = new JScrollPane(sizeList);
sp3.setPreferredSize(new Dimension(80, 100));
sp3.setMaximumSize(new Dimension(80, 100));
sp3.setMinimumSize(new Dimension(80, 100));
box3.add(sp3);
Box box4 = Box.createHorizontalBox();
Box box5 = Box.createVerticalBox();
JPanel box6 = new JPanel(new BorderLayout());
box5.setBorder(BorderFactory.createTitledBorder("字符集"));
box6.setBorder(BorderFactory.createTitledBorder("示例"));
box5.add(chinaButton);
box5.add(englishButton);
box5.add(numberButton);
box5.setPreferredSize(new Dimension(90, 95));
box5.setMaximumSize(new Dimension(90, 95));
box5.setMinimumSize(new Dimension(90, 95));
box6.add(previewText);
box6.setPreferredSize(new Dimension(250, 95));
box6.setMaximumSize(new Dimension(250, 95));
box6.setMinimumSize(new Dimension(250, 95));
box4.add(box5);
box4.add(Box.createHorizontalStrut(4));
box4.add(box6);
Box box7 = Box.createHorizontalBox();
box7.add(Box.createHorizontalGlue());
box7.add(approveButton);
box7.add(Box.createHorizontalStrut(5));
box7.add(cancelButton);
box.add(box1);
box.add(box2);
box.add(box3);
box.add(Box.createVerticalStrut(5));
box.add(box4);
box.add(Box.createVerticalStrut(5));
box.add(box7);
getContentPane().add(box);
}
/**
* 按照预设字体显示
*/
private void setup() {
String fontName = font.getFamily();
int fontStyle = font.getStyle();
int fontSize = font.getSize();
/*
* 如果预设的文字大小在选择列表中,则通过选择该列表中的某项进行设值,否则直接将预设文字大小写入文本框
*/
boolean b = false;
for (int i = 0; i < sizeArray.length; i++) {
if (sizeArray[i].equals(String.valueOf(fontSize))) {
b = true;
break;
}
}
if(b){
// 选择文字大小列表中的某项
sizeList.setSelectedValue(String.valueOf(fontSize), true);
}else{
sizeText.setText(String.valueOf(fontSize));
}
// 选择字体列表中的某项
fontList.setSelectedValue(fontName, true);
// 选择样式列表中的某项
styleList.setSelectedIndex(fontStyle);
// 预览默认显示中文字符
chinaButton.doClick();
// 显示预览
setPreview();
}
/**
* 添加所需的事件监听器
*/
private void addListener() {
sizeText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
setPreview();
}
public void focusGained(FocusEvent e) {
sizeText.selectAll();
}
});
// 字体列表发生选择事件的监听器
fontList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
fontText.setText(String.valueOf(fontList.getSelectedValue()));
// 设置预览
setPreview();
}
}
});
styleList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
styleText.setText(String.valueOf(styleList.getSelectedValue()));
// 设置预览
setPreview();
}
}
});
sizeList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
if(!sizeText.isFocusOwner()){
sizeText.setText(String.valueOf(sizeList.getSelectedValue()));
}
// 设置预览
setPreview();
}
}
});
// 编码监听器
EncodeAction ea = new EncodeAction();
chinaButton.addActionListener(ea);
englishButton.addActionListener(ea);
numberButton.addActionListener(ea);
// 确定按钮的事件监听
approveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 组合字体
font = groupFont();
// 设置返回值
returnValue = APPROVE_OPTION;
// 关闭窗口
disposeDialog();
}
});
// 取消按钮事件监听
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disposeDialog();
}
});
}
/**
* 显示字体选择器
* @param owner 上层所有者
* @return 该整形返回值表示用户点击了字体选择器的确定按钮或取消按钮,参考本类常量字段APPROVE_OPTION和CANCEL_OPTION
*/
public final int showFontDialog(JFrame owner) {
setLocationRelativeTo(owner);
setVisible(true);
return returnValue;
}
/**
* 返回选择的字体对象
* @return 字体对象
*/
public final Font getSelectFont() {
return font;
}
/**
* 关闭窗口
*/
private void disposeDialog() {
MQFontChooser.this.removeAll();
MQFontChooser.this.dispose();
}
/**
* 显示错误消息
* @param errorMessage 错误消息
*/
private void showErrorDialog(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage, "错误", JOptionPane.ERROR_MESSAGE);
}
/**
* 设置预览
*/
private void setPreview() {
Font f = groupFont();
previewText.setFont(f);
}
/**
* 按照选择组合字体
* @return 字体
*/
private Font groupFont() {
String fontName = fontText.getText();
int fontStyle = styleList.getSelectedIndex();
String sizeStr = sizeText.getText().trim();
// 如果没有输入
if(sizeStr.length() == 0) {
showErrorDialog("字体(大小)必须是有效“数值!");
return null;
}
int fontSize = 0;
// 通过循环对比文字大小输入是否在现有列表内
for (int i = 0; i < sizeArray.length; i++) {
if(sizeStr.equals(sizeArray[i])){
fontSize = sizeIntArray[i];
break;
}
}
// 没有在列表内
if (fontSize == 0) {
try{
fontSize = Integer.parseInt(sizeStr);
if(fontSize < 1){
showErrorDialog("字体(大小)必须是有效“数值”!");
return null;
}
}catch (NumberFormatException nfe) {
showErrorDialog("字体(大小)必须是有效“数值”!");
return null;
}
}
return new Font(fontName, fontStyle, fontSize);
}
/**
* 编码选择事件的监听动作
*
*/
class EncodeAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(chinaButton)) {
previewText.setText(CHINA_STRING);
} else if (e.getSource().equals(englishButton)) {
previewText.setText(ENGLISH_STRING);
} else {
previewText.setText(NUMBER_STRING);
}
}
}
}
SystemParam类
package com.whj.util;
/**
* 系统参数
* @authour Taylor
*/
public class SystemParam {
/**
* 当前系统换换行符号
*/
public static final String LINE_SEPARATOP = System.getProperty("line.separator");
}
TestLine类
package com.whj.util;
import java.awt.*;
import static javax.swing.text.html.CSS.Attribute.MARGIN;
public class TestLine extends javax.swing.JComponent {
private final Font DEFAULT_FONT = new Font(Font.MONOSPACED,Font.PLAIN,13);
public final Color DEFAULT_BACKGROUD = new Color(228,228,228);
public final Color DEFAULT_FOREGROUD = Color.red;
public final int nHEIGHT = Integer.MAX_VALUE - 1000000;
private int lineHeight;
private int fontLineHeight;
private int currentRowWidth;
private FontMetrics fontMetrics;
public TestLine(){
setFont(DEFAULT_FONT);
setForeground(DEFAULT_BACKGROUD);
setForeground(DEFAULT_FOREGROUD);
setPreferredSize(9999);
}
public void setPreferredSize(int row) {
int width = fontMetrics.stringWidth(String.valueOf(row));
if (currentRowWidth < width){
currentRowWidth = width;
// setPreferredSize(new Dimension(2 * MARGIN + width + 1, nHEIGHT));
}
}
@Override
public void setFont(Font font){
super.setFont(font);
fontMetrics = getFontMetrics(getFont());
fontLineHeight = fontMetrics.getHeight();
}
public int getLineHeight(){
if (lineHeight == 0){
return fontLineHeight;
}
return lineHeight;
}
public void setLineHeight(int lineHeight){
if (lineHeight > 0){
this.lineHeight = lineHeight;
}
}
public int getStartOffset(){
return 4;
}
@Override
protected void paintComponent(Graphics g){
int nlineHeight = getLineHeight();
int startOffset = getStartOffset();
Rectangle drawHere = g.getClipBounds();
g.setColor(getBackground());
g.fillRect(drawHere.x,drawHere.y,drawHere.width,drawHere.height);
g.setColor(getForeground());
int starLineNum = (drawHere.y / nlineHeight) + 1;
int endlineNum = starLineNum + (drawHere.height / nlineHeight);
int start = (drawHere.y / nlineHeight) * nlineHeight + nlineHeight - startOffset;
for (int i = starLineNum; i <=endlineNum;i++){
String lineNum = String.valueOf(i);
int width = fontMetrics.stringWidth(lineNum);
// g.drawString(lineNum + " ", MARGIN + currentRowWidth - width - 1,start);
start+=nlineHeight;
}
setPreferredSize(endlineNum);
}
}
联系方式
NewEoor 发布了1 篇原创文章 · 获赞 0 · 访问量 49 私信 关注标签:textArea,int,private,add,javaGUI,JMenuItem,new,源程序,记事本 来源: https://blog.csdn.net/user1033161981/article/details/104064778