JAVA实现简单笔记本-新手

最近开始做JAVA项目 先从小的开始练手吧
第一个是计算器 感觉有点无聊
第二个是记事本 倒是蛮有趣的
参考了@WANGHA_1的代码 但是觉得他写的不是很适合新手来看 所以稍微改动了一下 就算是记录一个开发流程 希望能给大家带来启发
这是他的代码 对我帮助很大 谢谢
https://blog.csdn.net/wangha_1/article/details/78937248

OK 进入正题

1.JAVA中的第一步一定是先画出界面 先设想一下画面的样子
大概是这样子的
先声明我们需要的东西

public class NoteBook extends JFrame{
	//主窗口
	JFrame frame=new JFrame("记事本");
	//主菜单
	JMenuBar menuBar=new JMenuBar();
	JMenu fileMenu=new JMenu("文件");
	JMenu editMenu=new JMenu("编辑");
	JMenu formatMenu=new JMenu("格式");
	JMenu viewMenu=new JMenu("查看");
	JMenu helpMenu=new JMenu("帮助");
	//文本框和滚动条
	JTextArea jTextArea=new JTextArea(10,40);
	JScrollPane jScrollPane=new JScrollPane(jTextArea);
	//子菜单
	JMenuItem newItem=new JMenuItem("新建");
	JMenuItem openItem=new JMenuItem("打开");
	JMenuItem saveItem=new JMenuItem("保存");
	JMenuItem savetoItem=new JMenuItem("另存为");
	JMenuItem closeItem=new JMenuItem("关闭");
	
	JMenuItem editUndo=new JMenuItem("撤销");
	JMenuItem editCut=new JMenuItem("剪切");
	JMenuItem editCopy=new JMenuItem("复制");
	JMenuItem editPaste=new JMenuItem("粘贴");
	JMenuItem editDelete=new JMenuItem("删除");
	JMenuItem editFind=new JMenuItem("查找");
	JMenuItem editReplace=new JMenuItem("替换");
	JMenuItem editGoto=new JMenuItem("转到");
	JMenuItem editAll=new JMenuItem("全选");
	JMenuItem editDates=new JMenuItem("时间");
	
	JMenuItem formatFont=new JMenuItem("字体");
	JCheckBoxMenuItem formatLinewrap=new JCheckBoxMenuItem("自动换行");
	
	JCheckBoxMenuItem Status=new JCheckBoxMenuItem("状态栏");
	
	JMenuItem aboutItem=new JMenuItem("关于");
	//状态栏
	protected Component statusLabel=new JLabel(" 按F1获取帮助");
	
	//需要的一些全局变量
	File file;
	String fileName;
	
	//保存和打开文件时调用的窗口
	FileDialog open=new FileDialog(frame,"打开文档",FileDialog.LOAD);
	FileDialog save=new FileDialog(frame,"保存文档",FileDialog.SAVE);
	
	//撤销的一个调用 必须写在全局变量里
	protected UndoManager undo=new UndoManager();
	class UndoHandler implements UndoableEditListener{
		@Override
		public void undoableEditHappened(UndoableEditEvent e) {
			// TODO Auto-generated method stub
			undo.addEdit(e.getEdit());
		}
	}
	protected UndoableEditListener undoHandler=new UndoHandler();
	//菜单根据响应的操作的变化
	public void removeUpdate(DocumentEvent e) {
		editUndo.setEnabled(true);
	}
	public void insertUpdate(DocumentEvent e) {
		editUndo.setEnabled(true);
	}
	public void changeUpdate(DocumentEvent e) {
		editUndo.setEnabled(true);
	}
	//系统剪贴板调用
	Toolkit toolkit=Toolkit.getDefaultToolkit();//获取默认工具包
	java.awt.datatransfer.Clipboard clipBoard=toolkit.getSystemClipboard();

上文前面的好理解,后面的撤销和剪切板调用就认为是个默认写法 需要记住

然后进行组合 放在构造器里画出

public NoteBook() {
		//加入菜单
		menuBar.add(fileMenu);
		menuBar.add(editMenu);
		menuBar.add(formatMenu);
		menuBar.add(viewMenu);
		menuBar.add(helpMenu);
		
		fileMenu.add(newItem);
		fileMenu.add(openItem);
		fileMenu.add(saveItem);
		fileMenu.add(savetoItem);
		fileMenu.add(closeItem);
		
		editMenu.add(editUndo);
		editMenu.add(editCut);
		editMenu.add(editCopy);
		editMenu.add(editPaste);
		editMenu.add(editFind);
		editMenu.add(editDelete);
		editMenu.add(editReplace);
		editMenu.add(editGoto);
		editMenu.add(editAll);
		editMenu.add(editDates);
		
		formatMenu.add(formatLinewrap);
		formatMenu.add(formatFont);
		
		viewMenu.add(Status);
		
		helpMenu.add(aboutItem);
		//文字区域
		Font x=new Font("Monospaced",1,20);
		jTextArea.setFont(x);
		jTextArea.setLineWrap(true);
		//滚动条
		jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);//横向自动出现
		jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);//纵向自动出现
		jScrollPane.setViewportView(jTextArea);
		//撤销
		jTextArea.getDocument().addUndoableEditListener(undo);
		//窗口总体设置
		frame.setBounds(300,300,700,450);
		frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
		frame.setResizable(true);
		frame.setVisible(true);
		frame.add(menuBar,BorderLayout.NORTH);
		frame.add(jScrollPane, BorderLayout.CENTER);
		frame.add(statusLabel, BorderLayout.SOUTH);
		statusLabel.setVisible(false);
		
		Event();
	}

其实我觉得画窗口这个过程就很好的揭示了一个JAVA的面向对象的特性 先拆分 拆分为一个一个的小对象,逐个击破,最后再组合,我觉得按照这样的顺序来写会好很多。
当然了 不要忘记了写函数入口

public static void main(String[] args) {
		new NoteBook();
	}

2.第二步就是要扩充功能了 按照菜单上的功能来 用一个主函数Event()来触发
先在函数里面写完菜单要求的所有功能 都是增加监听器然后重载即可
简单的可以直接写 复杂的就另外写函数来调用
比如字体 ,替换,转到,查找这几个函数比较复杂 所以留在后面扩充
font() turnTo() Replace() Find()
还是比较复杂的 用到了文件读写还有异常处理的相关知识

有几个函数是一致都要用的 所以写在前面 用来控制文本框以及菜单项的

	//控制文本框
	public JTextArea getTa() {
		return jTextArea;
	}
	
	//菜单可选项设置  这个函数有点问题 达不到预期效果
	public void checkMenuItemEnabled() {
		String selectText=jTextArea.getSelectedText();
		if(selectText==null) {
			editCut.setEnabled(true);
			editCopy.setEnabled(true);
			editDelete.setEnabled(true);
		}else {
			editCut.setEnabled(true);
			editCopy.setEnabled(true);
			editDelete.setEnabled(true);
		}
	}

Event()函数 触发函数 重要

public void Event() {
		//新建
		newItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					if(e.getSource()==newItem) {
						if(!(getTa().getText()).equals("")) {//假如记事本内不空
							Object[] options={"确定","取消"};//设置选择对象
							int response=JOptionPane.showOptionDialog(null,"你是否保存","提示", JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
							if(response==0) {//选择保存
								FileDialog d=new FileDialog(frame,"保存文件",FileDialog.SAVE);
								d.setVisible(true);
								fileName=d.getDirectory()+d.getFile();
								FileOutputStream fout=new FileOutputStream(fileName+".txt");//用于新建一个文件的
								
								byte[] bb=getTa().getText().getBytes();
								fout.write(bb);
								fout.close();
								JOptionPane.showMessageDialog(null, "已保存");
								getTa().setText("");
							}else if(response==1) {
								JOptionPane.showMessageDialog(null, "你选择了取消");
							}
						}
					}
				}catch(Exception e2) {
					System.out.println(e2.getMessage());//打印错误的原因
				}
			}
		});
		//打开
		openItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				open.setVisible(true);
				String dirPath=open.getDirectory();
				String filrName=open.getFile();
				if(dirPath==null||fileName==null)
					return;
				jTextArea.setText("");
				file=new File(dirPath,fileName);//文件打开操作 路径+名字
				//文件流知识  一行一行的读出文件
				try {
					BufferedReader br=new BufferedReader(new FileReader(file));//用于打开一个文件的
					String line=null;
					while((line=br.readLine())!=null) {
						jTextArea.append(line+"\r\n");
					}
				}catch(IOException e1) {
					throw new RuntimeException("读取失败");
				}
			}
		});
		//保存
		saveItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e){
				// TODO Auto-generated method stub
				if(file==null) {//前一个文件的事情结束了
					save.setVisible(true);
					String dirPath=save.getDirectory();
					String fileName=save.getFile();
					if(dirPath==null||fileName==null)
						return;
					file=new File(dirPath,fileName);
				}
				try {//文件流 整个写入文件
					BufferedWriter bw=new BufferedWriter(new FileWriter(file));
					String text=jTextArea.getText();
					bw.write(text);
					bw.close();
				}catch(IOException e2) {
					throw new RuntimeException();
				}
			}
		});
		//保存至
		savetoItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(e.getSource()==savetoItem) {
					try {
						FileDialog d=new FileDialog(frame,"另存为",FileDialog.SAVE);
						d.setVisible(true);
						fileName=d.getDirectory()+d.getFile();
						FileOutputStream fout=new FileOutputStream(fileName+".txt");
						byte[] bb=getTa().getText().getBytes();
						fout.write(bb);
						fout.close();
					}catch(Exception e2) {
						System.out.println(e2.getMessage());
					}
				}
			}
		});
		//关闭
		closeItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		});	
		//关于
		aboutItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				JOptionPane.showMessageDialog(null, "这是自己编写的记事本\n");
			}
			
		});
		//撤销
		editUndo.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				jTextArea.requestFocus();
				
				if(undo.canUndo()) {
					try {
						undo.undo();
					}catch(CannotUndoException e2) {
						System.out.println("Unable to undo:"+e2);
					}
				}
				if(!undo.canUndo()) {
					editUndo.setEnabled(false);
				}
			}
			
		});
		//剪切
		editCut.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editCut) {
					jTextArea.requestFocus();
					String text=jTextArea.getSelectedText();
					StringSelection selection=new StringSelection(text);//为了配合剪切板调用的
					clipBoard.setContents(selection, null);
					checkMenuItemEnabled();
				}
			}
		});
		//粘贴
		editPaste.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editPaste) {
					jTextArea.requestFocus();
					Transferable contents=Clipboard.getSystemClipboard(this);//配合剪切板调用
					if(contents==null) return;
					String text="";
					try {
						text=(String)contents.getTransferData(DataFlavor.stringFlavor);
					}catch(Exception e2){	
					}
					jTextArea.replaceRange(text, jTextArea.getSelectionStart(),jTextArea.getSelectionEnd());
					checkMenuItemEnabled();
				}
			}
		});
		
		//删除
		editDelete.addActionListener( new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editDelete) {
					jTextArea.requestFocus();
					jTextArea.replaceRange("", jTextArea.getSelectionStart(), jTextArea.getSelectionEnd());
					checkMenuItemEnabled();
				}
			}
		});
		
		//查找
		editFind.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editFind) {
					jTextArea.requestFocus();
					find();
				}
			}
		});
		//替换
		editReplace.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editReplace) {
					jTextArea.requestFocus();
					Replace();
				}
			}
		});
		//转到
		editGoto.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editGoto) {
					jTextArea.selectAll();
				}
			}
		});
		//全选
		editAll.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editGoto) {
					jTextArea.requestFocus();
					turnTo();
				}
			}
		});
		//日期时间
		editDates.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(e.getSource()==editDates) {
					Date date=new Date();
					SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					JOptionPane.showMessageDialog(null, "现在是北京时间"+df.format(date));
				}
			}
		});
		//自动换行
		formatLinewrap.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(formatLinewrap.getState())
					jTextArea.setLineWrap(true);
				else
					jTextArea.setLineWrap(false);
			}
		});
		//字体
		formatFont.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				jTextArea.requestFocus();
				font();
			}
		});
		//查看状态栏
		Status.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(Status.getState()) {
					statusLabel.setVisible(true);
				}else
					statusLabel.setVisible(false);
			}
		});
		
	}

3.写剩下的几个复杂函数

这几个函数的共有特点都是要弹出新的可操作的弹窗
因此都是先声明需要的组件 然后给各个组件赋予逻辑 最后通过框架组合起来
里面的逻辑基本是照搬@WANGHA_1的,写的挺好的 最开始学习还是思想很重要

	//查找
	public void find() {
		//页面布局
		final JDialog findDialog=new JDialog(this,"查找",true);//JDialog从一个窗体中弹出另一个窗体  true表示上下锁定 false则可以自由切换
		Container con=findDialog.getContentPane();//用于实现弹出窗口的布局
		con.setLayout(new FlowLayout(FlowLayout.LEFT));//流失布局,组件按照关系从左到右排列,一行排满到下一行
		JLabel findContentLabel =new JLabel("查找内容(N)");
		final JTextField findText=new JTextField(30);//文本框
		JButton findNextButton=new JButton("查找下一个");
		final JCheckBox matchCheckBox=new JCheckBox("区分大小写(c)");
		ButtonGroup bGroup=new ButtonGroup();
		final JRadioButton upButton=new JRadioButton("向上(U)");
		final JRadioButton downButton=new JRadioButton("向下(U)");
		downButton.setSelected(true);
		bGroup.add(upButton);
		bGroup.add(downButton);
		JButton cancel=new JButton("取消");
		
		//为各个按钮增加监听
		cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				findDialog.dispose();
			}
		});
		findNextButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				int k=0,m=0;
				final String str1,str2,str3,str4,strA,strB;//A B是查找的
				str1=jTextArea.getText();//整个文本
				str2=findText.getText();//查找的
				str3=str1.toUpperCase();//转换为大写字符
				str4=str2.toUpperCase();
				if(matchCheckBox.isSelected()) {//假如区分大小写
					strA=str1;
					strB=str2;
				}else {
					strA=str3;
					strB=str4;
				}
				if(upButton.isSelected()) {//向前查找
					if(jTextArea.getSelectedText()==null)//未选择区域
						k=strA.lastIndexOf(strB,jTextArea.getCaretPosition()-1);
					else
						k=strA.lastIndexOf(strB,jTextArea.getCaretPosition()-findText.getText().length()-1);
					if(k>-1) {
						jTextArea.setCaretPosition(k);//定位光标
						jTextArea.select(k,k+strB.length());//选中
					}else {//JOption对话框的渐变形式
						JOptionPane.showMessageDialog(null, "找不到您查找的内容", "查找", JOptionPane.INFORMATION_MESSAGE);//表示叹号
					}
				}else if(downButton.isSelected()) {
					if(jTextArea.getSelectedText()==null)
						 k=strA.indexOf(strB,jTextArea.getCaretPosition()+1);//index 返回第一个索引的位置,从这个位置开始搜索
					else
						 k=strA.indexOf(strB, jTextArea.getCaretPosition()-findText.getText().length()+1); 
					if(k>-1){ 
						 jTextArea.setCaretPosition(k);
						 jTextArea.select(k,k+strB.length());
					}else{ JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);
					}
				}
			}
		});
		
		//画窗口
		JPanel panel1=new JPanel();
		JPanel panel2=new JPanel();
		JPanel panel3=new JPanel();
		JPanel directionPanel=new JPanel();//方向面板
		directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));//设置边界 并且设置边界Panel的标题
		directionPanel.add(upButton);
		directionPanel.add(downButton);
		panel1.setLayout(new GridLayout(2,1));
		panel1.add(findNextButton);
		panel1.add(cancel);
		
		panel2.add(findContentLabel);
		panel2.add(findText);
		panel2.add(panel1);
		
		panel3.add(matchCheckBox);
		panel3.add(directionPanel);
		
		con.add(panel2);
		con.add(panel3);
		
		findDialog.setSize(410,180);
		findDialog.setResizable(false);//不可调整大小
		findDialog.setLocation(230,280);
		findDialog.setVisible(true);

	}
	
	public void replace() {
		
		final JDialog replaceDialog=new JDialog(this,"替换",false);
		Container con=replaceDialog.getContentPane();
		con.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel replaceLabel=new JLabel("查找内容(N)");
		final JTextField replaceText=new JTextField(20);
		JLabel replacetoLabel=new JLabel("替换为(P)");
		final JTextField replacetoText=new JTextField(20);
		JButton replaceNextButton=new JButton("查找下一个(F)");
		JButton replaceButton=new JButton("替换(R)");
		JButton replaceAllButton=new JButton("全部替换(A)");
		JButton replacecancelButton=new JButton("取消");
		final JCheckBox checkButton=new JCheckBox("区分大小写(C)");
		
		replacecancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				replaceDialog.dispose();
				
			}
			
		}); 
		
		replaceNextButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int k=0,m=0;
				final String str1,str2,str3,str4,strA,strB;
				str1=jTextArea.getText();
				str2=replaceText.getText();
				str3=str1.toUpperCase();
				str4=str2.toUpperCase();
				if(checkButton.isSelected()) {
					strA=str1;
					strB=str2;
				}else {
					strA=str3;
					strB=str4;
				}
				
				if(jTextArea.getSelectedText()==null) {
					k=strA.indexOf(strB);
				}else {
					k=strA.indexOf(strB, jTextArea.getCaretPosition()-replaceText.getText().length()+1);
				}
				if(k>-1) {
					jTextArea.setCaretPosition(k);
					jTextArea.select(k, k+strB.length());
				}else {
					JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		
		
		replaceButton.addActionListener(new ActionListener(){ 
			public void actionPerformed(ActionEvent e){ 
				if(replaceText.getText().length()==0 && jTextArea.getSelectedText()!=null) //假如替换为空格
					jTextArea.replaceSelection(""); 
				if(replaceText.getText().length()>0 && jTextArea.getSelectedText()!=null) //假如替换为别的
					jTextArea.replaceSelection(replaceText.getText());
				}
		});
		
		
		replaceAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jTextArea.setCaretPosition(0);
				int k=0,m=0,replaceCount=0;
				if(replaceText.getText().length()==0) {
					JOptionPane.showMessageDialog(replaceDialog, "请填写查找内容!","提示",JOptionPane.WARNING_MESSAGE);
					replaceText.requestFocus(true);//把输入光标放入这个框
					return;
				}
				while(k>-1) {//全部替换
					final String str1,str2,str3,str4,strA,strB;
					str1=jTextArea.getText();
					str2=replaceText.getText();
					str3=str1.toUpperCase();
					str4=str2.toUpperCase();
					if(checkButton.isSelected()) {
						strA=str1;
						strB=str2;
					}else {
						strA=str3;
						strB=str4;
					}
					if(jTextArea.getSelectedText()==null) {
						k=strA.indexOf(strB);
					}else {
						k=strA.indexOf(strB, jTextArea.getCaretPosition()-replaceText.getText().length()-1);
					}
					
					if(k>-1) {
						jTextArea.setCaretPosition(k);
						jTextArea.select(k, k+strB.length());
					}else {
						if(replaceCount==0)
							JOptionPane.showMessageDialog(replaceDialog,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE);
						else 
							JOptionPane.showMessageDialog(replaceDialog,"成功替换"+replaceCount+"个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE);
					}
					
					if(replaceText.getText().length()>0&&jTextArea.getSelectedText()!=null) {
						jTextArea.replaceSelection(replaceText.getText());//执行替换
						replaceCount++;//记录替换次数
					}
				}//while结束
			}
		});
		
		JPanel panel1=new JPanel();
		JPanel panel2=new JPanel();
		JPanel panel3=new JPanel();
		panel1.setLayout(new GridLayout(4,1));
		panel1.add(replaceNextButton);
		panel1.add(replaceButton);
		panel1.add(replaceAllButton);
		panel1.add(replacecancelButton);
		
		panel2.setLayout(new GridLayout(2,2,0,4));
		panel2.add(replaceLabel);
		panel2.add(replaceText);
		panel2.add(replacetoLabel);
		panel2.add(replacetoText);

		
		panel3.add(checkButton);
		
		con.add(panel2);
		con.add(panel1);
		con.add(panel3);
		
		replaceDialog.setSize(410, 180);
		replaceDialog.setResizable(false);
		replaceDialog.setLocation(230,280);
		replaceDialog.setVisible(true);
	}
	
	private void turnTo() {
		final JDialog gotoDialog=new JDialog(this,"转到指定行",false);
		Container con=gotoDialog.getContentPane();
		con.setLayout(new FlowLayout(FlowLayout.CENTER));
		JLabel LineLabel=new JLabel("行号(L)");
		final JTextField linenum=new JTextField(25);
		JButton turnToButton=new JButton("转到");
		JButton cancelButton=new JButton("取消");
	
		turnToButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int totalLine=jTextArea.getLineCount();
				int[] lineNumber=new int[totalLine+1];//java的数组写法
				String s=jTextArea.getText();
				int pos=0,t=0;
				while(true) {
					pos=s.indexOf('\12',pos);//表示换行
					if(pos==-1) break;
					lineNumber[t++]=pos++;//得到每一行的结尾的字符号
				}
				
				int gt=1;
				
				try {
					gt=Integer.parseInt(linenum.getText());//放入可能出现的异常  字符转int
				}catch(NumberFormatException e1) {
					JOptionPane.showMessageDialog(null, "请输入行数!", "提示", JOptionPane.WARNING_MESSAGE);
					linenum.requestFocus(true);
					return;
				}
				
				if(gt<2||gt>=totalLine) {
					if(gt<2)//第一行
						jTextArea.setCaretPosition(0);
					else//最后一行
						jTextArea.setCaretPosition(s.length());
				}else
					jTextArea.setCaretPosition(lineNumber[gt-2]+1);
				gotoDialog.dispose();
			}
		});
		
		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
					gotoDialog.dispose();
			}
		});
		
		JPanel panel1=new JPanel();
		JPanel panel2=new JPanel();
		
		panel1.add(LineLabel);
		panel1.add(linenum);
		
		panel2.setLayout(new GridLayout(1,2));
		panel2.add(turnToButton);
		panel2.add(cancelButton);
	
		con.add(panel1);
		con.add(panel2);
		
		gotoDialog.setSize(420, 220);
		gotoDialog.setResizable(false);
		gotoDialog.setLocation(230,280);
		gotoDialog.setVisible(true);
	}

	public void font() {
		final JDialog fontDialog=new JDialog(this,"字体设置",true);
		Container con=fontDialog.getContentPane();
		con.setLayout(new FlowLayout(FlowLayout.LEFT));
		
		JLabel fontLabel=new JLabel("字体(F)");
		fontLabel.setPreferredSize(new Dimension(100,20));
		JLabel styleLabel=new JLabel("字形(Y)");
		styleLabel.setPreferredSize(new Dimension(100,20));
		JLabel sizeLabel=new JLabel("大小(S)");
		sizeLabel.setPreferredSize(new Dimension(100,20));
		
		final JLabel sample=new JLabel("示例");
		
		final JTextField fontText=new JTextField(9);
		fontText.setPreferredSize(new Dimension(200,20));
		//样式
		final JTextField styleText=new JTextField(8);
		styleText.setPreferredSize(new Dimension(200,20));
		final int style[]= {Font.PLAIN,Font.BOLD,Font.ITALIC,Font.BOLD+Font.ITALIC};
		//大小
		final JTextField sizeText=new JTextField(5);
		sizeText.setPreferredSize(new Dimension(200,20));
		
		JButton okButton=new JButton("确定");
		JButton cancel=new JButton("取消");
		//显示当前字体
		Font currentFont=jTextArea.getFont();
		fontText.setText(currentFont.getFontName());
		fontText.selectAll();
		//当前风格
		if(currentFont.getStyle()==Font.PLAIN)
			styleText.setText("常规");
		else if(currentFont.getStyle()==Font.BOLD)
			styleText.setText("粗体");
		else if(currentFont.getStyle()==Font.ITALIC)
			styleText.setText("斜体");
		else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))
			styleText.setText("粗斜体");
		styleText.selectAll();
		//显示当前大小
		String str=String.valueOf(currentFont.getSize());
		sizeText.setText(str);
		sizeText.selectAll();
		
		final JList fontList,styleList,sizeList;
		//字体
		GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
		final String fontName[]=ge.getAvailableFontFamilyNames();//得到字体的名称列表
		fontList=new JList(fontName);
		fontList.setFixedCellWidth(86);
		fontList.setFixedCellHeight(20);
		fontList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		//风格
		final String fontStyle[]= {"常规","粗体","斜体","粗斜体"};
		styleList=new JList(fontStyle);
		styleList.setFixedCellWidth(86);
		styleList.setFixedCellHeight(20);
		fontList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		if(currentFont.getStyle()==Font.PLAIN)
			styleList.setSelectedIndex(0);
		else if(currentFont.getStyle()==Font.BOLD)
			styleList.setSelectedIndex(1);
		else if(currentFont.getStyle()==Font.ITALIC)
			styleList.setSelectedIndex(2);
		else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))
			styleList.setSelectedIndex(3);
		//大小
		final String fontSize[]={"8","9","10","11","12","14","16","18","20","22","24","26","28","36","48","72"};
		sizeList=new JList(fontSize);
		sizeList.setFixedCellWidth(43);
		sizeList.setFixedCellHeight(20);
		sizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		
		cancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				fontDialog.dispose();
			}
			
		});
		
		fontList.addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				// TODO Auto-generated method stub
				int s=style[styleList.getSelectedIndex()];
				styleText.setText(fontStyle[s]);//框里显示的字
				styleText.selectAll();
				Font sampleFont2=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
				sample.setFont(sampleFont2);
			}
		});
		styleList.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent event){ 
				int s=style[styleList.getSelectedIndex()];
				styleText.setText(fontStyle[s]);
				styleText.selectAll();
				Font sampleFont2=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
				sample.setFont(sampleFont2);
			}
		});
		sizeList.addListSelectionListener(new ListSelectionListener(){ 
			public void valueChanged(ListSelectionEvent event){ 
				sizeText.setText(fontSize[sizeList.getSelectedIndex()]);
				//sizeText.requestFocus();
				sizeText.selectAll(); 
				Font sampleFont3=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
				sample.setFont(sampleFont3);
			}
		});
		
		
		okButton.addActionListener(new ActionListener(){ 
			public void actionPerformed(ActionEvent e){ 
				Font okFont=new Font(fontText.getText(),style[styleList.getSelectedIndex()],Integer.parseInt(sizeText.getText()));
				jTextArea.setFont(okFont);
				fontDialog.dispose();
			}
		});	
		
		JPanel samplePanel =new JPanel();
		samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));
		samplePanel.add(sample);
		
		JPanel panel2=new JPanel();
		JPanel panel3=new JPanel();
		panel2.add(fontText);
		panel2.add(styleText);
		panel2.add(sizeText);
		panel2.add(okButton);
		panel2.add(cancel);
		
		panel3.add(new JScrollPane(fontList));
		panel3.add(new JScrollPane(styleList));
		panel3.add(new JScrollPane(sizeList));
		
		con.add(panel2);
		con.add(panel3);
		con.add(samplePanel);
		
		fontDialog.setSize(550, 300);
		fontDialog.setLocation(200,200);
		fontDialog.setResizable(false);
		fontDialog.setVisible(true);
}

**4.结束啦 一个记事本程序就写出来了 **

代码基本上是1000行左右 我就不粘了 就是把上面的放在一起就行
多动手多搜索多思考 一起加油

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值