Java实现记事本功能

Januaryten 2010-01-11 10:35:13
java怎么实现记事本查找功能??????代码是什么?????
...全文
476 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Inhibitory 2010-01-31
  • 打赏
  • 举报
回复
给你个查找字符串, 并把所有找到的结果都高亮显示的.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;

// 高亮:
// 1. text area 先设置setHighlighter为hilit
// 2. 添加要高亮字符的下标到hilit里

@SuppressWarnings("serial")
public final class Finder extends JFrame implements DocumentListener, CaretListener {
private JLabel status;
private JTextField entry;
private JTextArea textArea;
private JScrollPane scroller;

private Highlighter hilit;
private HighlightPainter painter;
private final Color NO_FOUND_COLOR = Color.PINK;
private final Color HILIT_COLOR = Color.YELLOW;

public Finder() {
initComponents();
entry.getDocument().addDocumentListener(this);

try {
FileReader reader = new FileReader("Finder.java");
textArea.read(reader, null);
} catch (IOException e) {
e.printStackTrace();
}
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setTabSize(4);
textArea.addCaretListener(this);

hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
textArea.setHighlighter(hilit);
}

private void initComponents() {
status = new JLabel("");
entry = new JTextField();
textArea = new JTextArea();
scroller = new JScrollPane(textArea);

JLabel label1 = new JLabel("Enter text to search:");
// Layouts components using group layout
GroupLayout layout = new GroupLayout(getContentPane());
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
getContentPane().setLayout(layout);

// Horizontal axis
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
GroupLayout.SequentialGroup topSGroup = layout.createSequentialGroup();
topSGroup.addComponent(label1).addComponent(entry);
hGroup.addGroup(layout.createParallelGroup().addGroup(topSGroup).addComponent(scroller)
.addComponent(status));
layout.setHorizontalGroup(hGroup);

// Vertical axis
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
GroupLayout.ParallelGroup topPGroup = layout.createParallelGroup(GroupLayout.Alignment.BASELINE);
topPGroup.addComponent(label1).addComponent(entry);
vGroup.addGroup(topPGroup).addComponent(scroller).addComponent(status);
layout.setVerticalGroup(vGroup);

// Setting frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int width = 600;
int height = 700;
int x, y;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = (screenSize.width - width) / 2;
y = (screenSize.height - height) / 2 - 600;
x = x > 0 ? x : 0;
y = y > 0 ? y : 0;
setLocation(x, y);
setSize(width, height);
}

public void search(String s) {
if (s == null) {
return;
}

hilit.removeAllHighlights();

if (s.length() <= 0) {
status.setText("No text to search.");
return;
}

// 高亮:
// 1. text area 先设置setHighlighter为hilit
// 2. 添加要高亮字符的下标到hilit里

String content = textArea.getText();
int start = content.indexOf(s);
if (start >= 0) {
entry.setBackground(Color.WHITE);
while (start >= 0) {
int end = start + s.length();
try {
hilit.addHighlight(start, end, painter);
} catch (BadLocationException e) {
e.printStackTrace();
}

start = content.indexOf(s, end);
}
status.setText(s + " found.");
} else {
status.setText(s + " not found.");
entry.setBackground(NO_FOUND_COLOR);
}
}

public void changedUpdate(DocumentEvent e) {
}

public void insertUpdate(DocumentEvent e) {
search(entry.getText());
}

public void removeUpdate(DocumentEvent e) {
search(entry.getText());
}

public void caretUpdate(CaretEvent e) {
search(textArea.getSelectedText());
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Finder().setVisible(true);
}
});
}
}
liwis521125 2010-01-31
  • 打赏
  • 举报
回复
累的要死
liwis521125 2010-01-31
  • 打赏
  • 举报
回复
package java;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.datatransfer.*;

class MyMenuBar extends MenuBar{
public MyMenuBar(Frame parent){
parent.setMenuBar(this);
}
public void addMenus(String [] menus){
for(int i=0;i<menus.length;i++)
add(new Menu(menus[i]));
}
public void addMenuItems(int menuNumber,String[] items){
for(int i=0;i<items.length;i++){
if(items[i]!=null)
getMenu(menuNumber).add(new MenuItem(items[i]));
else getMenu(menuNumber).addSeparator();
}
}
public void addActionListener(ActionListener al){
for(int i=0;i<getMenuCount();i++)
for(int j=0;j<getMenu(i).getItemCount();j++)
getMenu(i).getItem(j).addActionListener(al);
}
}

class MyFile{
private FileDialog fDlg;
public MyFile(Frame parent){
fDlg=new FileDialog(parent,"",FileDialog.LOAD);
}
private String getPath(){
return fDlg.getDirectory()+"\\"+fDlg.getFile();
}
public String getData() throws IOException{
fDlg.setTitle("打开");
fDlg.setMode(FileDialog.LOAD);
fDlg.setVisible(true);
BufferedReader br=new BufferedReader(new FileReader(getPath()));
StringBuffer sb=new StringBuffer();
String aline;
while((aline=br.readLine())!=null)
sb.append(aline+'\n');
br.close();
return sb.toString();
}
public void setData(String data) throws IOException{
fDlg.setTitle("保存");
fDlg.setMode(FileDialog.SAVE);
fDlg.setVisible(true);
BufferedWriter bw=new BufferedWriter(new FileWriter(getPath()));
bw.write(data);
bw.close();
}
}

class MyClipboard{
private Clipboard cb;
public MyClipboard(){
cb=Toolkit.getDefaultToolkit().getSystemClipboard();
}
public void setData(String data){
cb.setContents(new StringSelection(data),null);
}
public String getData(){
Transferable content=cb.getContents(null);
try{
return (String) content.getTransferData(DataFlavor.stringFlavor);
//DataFlavor.stringFlavor会将剪贴板中的字符串转换成Unicode码形式的String对象。
//DataFlavor类是与存储在剪贴板上的数据的形式有关的类。
}catch(Exception ue){}
return null;
}
}

class MyFindDialog extends Dialog implements ActionListener{
private Label lFind=new Label("查找字符串");
private Label lReplace=new Label("替换字符串");
private TextField tFind=new TextField(10);
private TextField tReplace=new TextField(10);
private Button bFind=new Button("查找");
private Button bReplace=new Button("替换");
private TextArea ta;
public MyFindDialog(Frame owner,TextArea ta){
super(owner,"查找",false);
this.ta=ta;
setLayout(null);
lFind.setBounds(10,30,80,20);
lReplace.setBounds(10,70,80,20);
tFind.setBounds(90,30,90,20);
tReplace.setBounds(90,70,90,20);
bFind.setBounds(190,30,80,20);
bReplace.setBounds(190,70,80,20);
add(lFind);
add(tFind);
add(bFind);
add(lReplace);
add(tReplace);
add(bReplace);
setResizable(false);
bFind.addActionListener(this);
bReplace.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyFindDialog.this.dispose();
}
});
}//构造函数结束
public void showFind(){
setTitle("查找");
setSize(280,60);
setVisible(true);
}
public void showReplace(){
setTitle("查找替换");
setSize(280,110);
setVisible(true);
}
private void find(){
String text=ta.getText();
String str=tFind.getText();
int end=text.length();
int len=str.length();
int start=ta.getSelectionEnd();
if(start==end) start=0;
for(;start<=end-len;start++){
if(text.substring(start,start+len).equals(str)){
ta.setSelectionStart(start);
ta.setSelectionEnd(start+len);
return;
}
}
//若找不到待查字符串,则将光标置于末尾
ta.setSelectionStart(end);
ta.setSelectionEnd(end);
}

public Button getBFind() {
return bFind;
}
private void replace(){
String str=tReplace.getText();
if(ta.getSelectedText().equals(tFind.getText()))
ta.replaceRange(str,ta.getSelectionStart(),ta.getSelectionEnd());
else find();
}

public void actionPerformed(ActionEvent e) {
if(e.getSource()==bFind)
find();
else if(e.getSource()==bReplace)
replace();
}
}

public class MyMemo extends Frame implements ActionListener{
private TextArea editor=new TextArea(); //可编辑的TextArea
private MyFile mf=new MyFile(this);//MyFile对象
private MyClipboard cb=new MyClipboard();
private MyFindDialog findDlg=new MyFindDialog(this,editor);

public MyMemo(String title){ //构造函数
super(title);
MyMenuBar mb=new MyMenuBar(this);
//添加需要的菜单及菜单项
mb.addMenus(new String[]{"文件","编辑","查找","帮助"});
mb.addMenuItems(0,new String[]{"新建","打开","保存",null,"全选"});
mb.addMenuItems(1,new String[]{"剪贴","复制","粘贴","清除",null,"全选"});
mb.addMenuItems(2,new String[]{"查找",null,"查找替换"});
mb.addMenuItems(3,new String[]{"我的记事本信息"});

add(editor); //为菜单项注册动作时间监听器
mb.addActionListener(this);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyMemo.this.dispose();
}
}); //分号不能忘了
} //构造函数完

public void actionPerformed(ActionEvent e){
String selected=e.getActionCommand(); //获取菜单项标题
if(selected.equals("新建"))
editor.setText("");
else if(selected.equals("打开")){
try{
editor.setText(mf.getData());
}catch(IOException ie){}
}
else if(selected.equals("保存")){
try{
mf.setData(editor.getText());
}catch(IOException ie){}
}
else if(selected.equals("退出")){
dispose();
}
else if(selected.equals("剪贴")){
//将选中的字符串复制到剪贴板中并清除字符串
cb.setData(editor.getSelectedText());
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("复制")){
cb.setData(editor.getSelectedText());
}
else if(selected.equals("粘贴")){
String str=cb.getData();
editor.replaceRange(str,editor.getSelectionStart(),editor.getSelectionEnd());
//粘贴在光标位置
}
else if(selected.equals("清除")){
editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
}
else if(selected.equals("全选")){
editor.setSelectionStart(0);
editor.setSelectionEnd(editor.getText().length());
}
else if(selected.equals("查找")){
findDlg.showFind();
}
else if(selected.equals("查找替换")){
findDlg.showReplace();
}
}

public static void main(String[] args){
MyMemo memo=new MyMemo("记事本");
memo.setSize(650,450);
memo.setVisible(true);
}
}
nj_dobetter 2010-01-18
  • 打赏
  • 举报
回复
用经典的KMP算法
y11111494 2010-01-18
  • 打赏
  • 举报
回复
帮顶
healer_kx 2010-01-12
  • 打赏
  • 举报
回复
IndexOf就行了。
tianyulei111256 2010-01-12
  • 打赏
  • 举报
回复
public void chaZhaoM()
{
String s = JOptionPane.showInputDialog(null, "Please input what you want to find ", "find dialog", -1);
String wenBen = wenZiYu.getText();
int start = wenBen.indexOf(s);
if (start == -1)
{
JOptionPane.showMessageDialog(this, "no result", "message dialog", 2);
} else
{
int end = start + s.length();
wenZiYu.select(start, end);
}
}

这个是查找功能的函数,你可以调用
huntor 2010-01-11
  • 打赏
  • 举报
回复
Swing Hacks Hack 48. Make Text Components Searchable
psyuhen 2010-01-11
  • 打赏
  • 举报
回复
LS的,不错。。方法同LS。

LZ,凡事都要先想想,
maer56 2010-01-11
  • 打赏
  • 举报
回复
需要了解正则表达式的知识。将内容与正则表达式比较,匹配成功就说明找到了,继续判断还有没有下个
stsw2046 2010-01-11
  • 打赏
  • 举报
回复
这个有难度~

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧