本文编写的编辑器模仿的是windows底下的记事本功能,并增加了高亮和自动保存的功能.


该编辑器功能如下:

  • 复制粘贴
  • 查找替换
  • 自动保存
  • 代码高亮

这次只搭建简单的框架,搭建出基本样子

2016/03/12 更新
基本实现windows记事本功能,查找有错。
(参考别人代码,所以随意转载)

import java.awt.*;
import java.awt.event.*;
import java.awt.AWTEvent;
import java.awt.Font;
import java.text.*;
import java.util.*;
import java.io.*;
import java.io.IOException;
import java.io.File;
import javax.swing.undo.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.datatransfer.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.lang.reflect.Method;
import javax.swing.text.BadLocationException;public class Editor extends JFrame{Container container = getContentPane();public ImageIcon icon = new ImageIcon("./lovexw.jpg");public Image image = icon.getImage();public JMenuBar menubar = new JMenuBar();public JMenu fileMenu,editMenu,formatMenu,viewMenu,helpMenu;public JMenuItem fileMenu_New,fileMenu_Open,fileMenu_Save,fileMenu_SaveAs,fileMenu_PageSetup,fileMenu_Print,fileMenu_Exit;public JMenuItem editMenu_Undo,editMenu_Redo,editMenu_Cut,editMenu_Copy,editMenu_Paste,editMenu_Delete,editMenu_Find,editMenu_GoTo,editMenu_SelectAll,editMenu_TimeDate;public JCheckBoxMenuItem formatMenu_LineWrap;public JMenuItem formatMenu_Font;public JCheckBoxMenuItem viewMenu_Status;public JMenuItem helpMenu_Help,helpMenu_About;public JTextArea editArea;public JLabel statusLabel = new JLabel("Current Location is 1 row, 1 line",JLabel.RIGHT);public JPopupMenu popupMenu;public JMenuItem popupMenu_Undo,popupMenu_Redo,popupMenu_Cut,popupMenu_Copy,popupMenu_Paste,popupMenu_Delete,popupMenu_SelectAll;public JList list;   public String currentValue,oldValue;    public String oldpath = null;public boolean isNewFile = true;public Toolkit toolKit=Toolkit.getDefaultToolkit();protected UndoManager undo = new UndoManager();public Font newfont;//protected UndoableEditListener undoHandler = new UndoHandler();public Editor(){super("windows notepad");JMenu fileMenu = new JMenu("File(F)",true);fileMenu.setMnemonic('F');fileMenu_New = new JMenuItem("New(N)", 'N');fileMenu_New.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));fileMenu_New.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){currentValue = editArea.getText();if(currentValue.equals(oldValue)){editArea.setText("");}else{int result = JOptionPane.showConfirmDialog(null,"No Saved,Sure to create a new File?","Warning",JOptionPane.YES_NO_OPTION);if(result == JOptionPane.YES_OPTION){editArea.setText("");}}}});fileMenu_Open = new JMenuItem("Open(O)", 'O');fileMenu_Open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));fileMenu_Open.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JFileChooser fileChooser = new JFileChooser(oldpath);//java file onlyFileNameExtensionFilter filter = new FileNameExtensionFilter("JAVA File","java");fileChooser.setFileFilter(filter);//fileChooser's titlefileChooser.setDialogTitle("Open File");int result = fileChooser.showOpenDialog(getParent());  //showOpenDialog(this) isn't rightif(result == JFileChooser.APPROVE_OPTION){String name = fileChooser.getSelectedFile().getName();String path = fileChooser.getSelectedFile().getPath();oldpath = path;int line = 1;File file = new File(path);BufferedReader reader = null;try{reader = new BufferedReader(new FileReader(file));String temstring = null;while((temstring = reader.readLine())!=null){editArea.append(line + " " + temstring);editArea.append("\n");line ++;}reader.close();}catch(IOException c){c.printStackTrace();}finally{if(reader != null){try{reader.close();}catch(IOException d){}}}statusLabel.setText("Current Location is " + line + " row, 1 line");oldValue = editArea.getText();resetTitle(name);}}});fileMenu_Save = new JMenuItem("Save(S)", 'S');fileMenu_Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));fileMenu_Save.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(isNewFile){String str = null;JFileChooser fileChooser = new JFileChooser();fileChooser.setDialogTitle("Save File");int result = fileChooser.showSaveDialog(getParent());File saveFileName = fileChooser.getSelectedFile();if(result == JFileChooser.APPROVE_OPTION){try{FileWriter fw = new FileWriter(saveFileName + ".java");oldpath = saveFileName.getPath();BufferedWriter bfw = new BufferedWriter(fw);bfw.write(editArea.getText(),0,editArea.getText().length());bfw.flush();isNewFile = false;fw.close();oldValue = editArea.getText();}catch(IOException c){}}}if(!oldValue.equals(editArea.getText())){try{FileWriter fw = new FileWriter(oldpath + ".java");BufferedWriter bfw = new BufferedWriter(fw);bfw.write(editArea.getText(),0,editArea.getText().length());bfw.flush();fw.close();oldValue = editArea.getText();}catch(IOException c){}}}});fileMenu_SaveAs = new JMenuItem("Save As(A)...", 'A');fileMenu_SaveAs.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JFileChooser fileChooser = new JFileChooser("Save As");FileNameExtensionFilter filter = new FileNameExtensionFilter("JAVA File","java");fileChooser.setFileFilter(filter);int result = fileChooser.showSaveDialog(getParent());if(result == JFileChooser.APPROVE_OPTION){File saveasfile = fileChooser.getSelectedFile();try{FileWriter fw = new FileWriter(saveasfile+".java");BufferedWriter bfw = new BufferedWriter(fw);bfw.write(editArea.getText(),0,editArea.getText().length());bfw.flush();isNewFile = false;fw.close();oldValue = editArea.getText();}catch(IOException c){}}}});fileMenu_PageSetup = new JMenuItem("Page Setup(U)...",'U');fileMenu_PageSetup.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){dialogShow();}});fileMenu_Exit = new JMenuItem("Exit(X)",'X');fileMenu_Exit.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if((isNewFile)||(!oldValue.equals(editArea.getText()))){int result = JOptionPane.showConfirmDialog(null,"No Saved,Sure to Exit?","Warning",JOptionPane.YES_NO_OPTION);if(result == JOptionPane.YES_OPTION){System.exit(0);}}}});JMenu editMenu = new JMenu("Edit(E)",true);editMenu.setMnemonic('E');editMenu_Undo = new JMenuItem("Undo(U)",'U');editMenu_Undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK));editMenu_Undo.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(undo.canUndo()){try{undo.undo();}catch(CannotUndoException ex){ex.printStackTrace();}}}});editMenu_Redo = new JMenuItem("Redo(R)",'R');editMenu_Redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y,InputEvent.CTRL_MASK));editMenu_Redo.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(undo.canRedo()){try{undo.redo();}catch(CannotRedoException ex){ex.printStackTrace();}}}});editMenu_Cut = new JMenuItem("Cut(T)",'T');editMenu_Cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));editMenu_Cut.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.cut();}});editMenu_Copy = new JMenuItem("Copy(C)",'C');editMenu_Copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));editMenu_Copy.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.copy();}});editMenu_Paste = new JMenuItem("Paste(P)",'P');editMenu_Paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));editMenu_Paste.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.paste();}});editMenu_Delete = new JMenuItem("Delete(L)",'L');editMenu_Delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));editMenu_Delete.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.replaceSelection(null);}});editMenu_Find = new JMenuItem("Find(F)...",'F');editMenu_Find.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK));editMenu_Find.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){search();}});editMenu_GoTo = new JMenuItem("Go(G)...",'G');editMenu_GoTo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK));editMenu_GoTo.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JOptionPane pane = new JOptionPane();String s = pane.showInputDialog(null,"Go to","Please input the line number",JOptionPane.YES_OPTION);if(s!=null){int result = Integer.valueOf(s).intValue();try{int position = editArea.getLineStartOffset(result) - 1;editArea.setCaretPosition(position);}catch(Exception ex){ex.printStackTrace();}}}});editMenu_SelectAll = new JMenuItem("Select All",'A');editMenu_SelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));editMenu_SelectAll.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.selectAll();}});editMenu_TimeDate = new JMenuItem("Time/Date(D)",'D');editMenu_TimeDate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));editMenu_TimeDate.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int y,m,d,h,mi,s;    Calendar cal=Calendar.getInstance();    y=cal.get(Calendar.YEAR);m=cal.get(Calendar.MONTH);d=cal.get(Calendar.DATE);h=cal.get(Calendar.HOUR_OF_DAY);mi=cal.get(Calendar.MINUTE);s=cal.get(Calendar.SECOND);//Date date=new Date();//DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//String time=format.format(date);editArea.insert(y+" year "+m+" mouth "+d+" day "+h+":"+mi+":"+s,editArea.getCaretPosition());}});JMenu formatMenu = new JMenu("Format(O)", true);formatMenu.setMnemonic('O');formatMenu_LineWrap = new JCheckBoxMenuItem("Line Wrap(W)");formatMenu_LineWrap.setMnemonic('W');formatMenu_LineWrap.setState(true);formatMenu_LineWrap.addItemListener(new ItemListener(){public void itemStateChanged(ItemEvent e){if(formatMenu_LineWrap.getState()){editArea.setLineWrap(true);}else{editArea.setLineWrap(false);}}});formatMenu_Font = new JMenuItem("Font(F)...",'F');formatMenu_Font.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){dialogforfont();}});JMenu viewMenu = new JMenu("View(V)", true);viewMenu.setMnemonic('V');viewMenu_Status = new JCheckBoxMenuItem("Status Bar(S)");viewMenu_Status.setMnemonic('S');viewMenu_Status.setState(false);viewMenu_Status.addItemListener(new ItemListener(){public void itemStateChanged(ItemEvent e){if(viewMenu_Status.getState()){status();fresh();statusLabel.setVisible(true);}else{statusLabel.setVisible(false);}}});JMenu helpMenu = new JMenu("Help(H)", true);helpMenu.setMnemonic('H');helpMenu_Help = new JMenuItem("Help(H)",'H');helpMenu_Help.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1,0));helpMenu_Help.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){String helpTopicsStr=new String("<center><br>lalalal<br><a href=http:// target=_blank>"+"http://</a><br><br><br>"+"demo</center>");JEditorPane editPane=new JEditorPane("text/html",helpTopicsStr);editPane.setEditable(false);try{java.net.URI uri = java.net.URI.create("http://www.baidu.com/");  java.awt.Desktop dp = java.awt.Desktop.getDesktop() ;    if (dp.isSupported(java.awt.Desktop.Action.BROWSE))dp.browse(uri);}catch(Exception c){c.printStackTrace();}}});helpMenu_About = new JMenuItem("About(A)",'A');helpMenu_About.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"          demo    \n" + "          fo      \n" + "          java    \n","About",JOptionPane.INFORMATION_MESSAGE);}});menubar.add(fileMenu);fileMenu.add(fileMenu_New);fileMenu.add(fileMenu_Open);fileMenu.add(fileMenu_Save);fileMenu.add(fileMenu_SaveAs);fileMenu.addSeparator();  fileMenu.add(fileMenu_PageSetup);fileMenu.addSeparator();  fileMenu.add(fileMenu_Exit);menubar.add(editMenu);editMenu.add(editMenu_Undo);editMenu.add(editMenu_Redo);editMenu.addSeparator();  editMenu.add(editMenu_Cut);editMenu.add(editMenu_Copy);editMenu.add(editMenu_Paste);editMenu.add(editMenu_Delete);editMenu.addSeparator();   editMenu.add(editMenu_Find);editMenu.add(editMenu_GoTo);editMenu.addSeparator();    editMenu.add(editMenu_SelectAll);editMenu.add(editMenu_TimeDate);menubar.add(formatMenu);formatMenu.add(formatMenu_LineWrap);formatMenu.addSeparator(); formatMenu.add(formatMenu_Font);menubar.add(viewMenu);viewMenu.add(viewMenu_Status);menubar.add(helpMenu);helpMenu.add(helpMenu_Help);helpMenu.addSeparator();helpMenu.add(helpMenu_About);editArea = new JTextArea();JScrollPane scroller = new JScrollPane(editArea);scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);container.add(scroller,BorderLayout.CENTER);editArea.setWrapStyleWord(true);editArea.setLineWrap(true);Font font = new Font("TimesRoman",Font.PLAIN,17);editArea.setFont(font);editArea.setBackground(Color.white);  editArea.setForeground(Color.black);editArea.getDocument().addUndoableEditListener(new UndoableEditListener(){public void undoableEditHappened(UndoableEditEvent e) {undo.addEdit(e.getEdit());}  });popupMenu=new JPopupMenu();popupMenu_Undo=new JMenuItem("Undo(U)",'U');popupMenu_Redo=new JMenuItem("Redo(R)",'R');popupMenu_Cut =new JMenuItem("Cut(T)",'T');popupMenu_Copy=new JMenuItem("Copy(C)",'C');popupMenu_Paste=new JMenuItem("Paset(P)",'P');popupMenu_Delete=new JMenuItem("Delete(D)",'D');popupMenu_SelectAll=new JMenuItem("Select all(A)",'A');     popupMenu.add(popupMenu_Undo);popupMenu.add(popupMenu_Redo);popupMenu.addSeparator();popupMenu.add(popupMenu_Cut);popupMenu.add(popupMenu_Copy);  popupMenu.add(popupMenu_Paste); popupMenu.add(popupMenu_Delete);popupMenu.addSeparator();editArea.addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){int mods = e.getModifiers();if(mods == InputEvent.BUTTON3_MASK)popupMenu.show(e.getComponent(),e.getX(),e.getY());}//两个方法都可以的/*public void mousePressed(MouseEvent e){triggerEvent(e);}  public void triggerEvent(MouseEvent e){if(e.isPopupTrigger())popupMenu.show(e.getComponent(),e.getX(),e.getY());}*/             });try{String lookAndFeel = UIManager.getSystemLookAndFeelClassName();UIManager.setLookAndFeel(lookAndFeel);SwingUtilities.updateComponentTreeUI(this);}catch(Exception e){e.printStackTrace();}this.setJMenuBar(menubar);this.setSize(1050,650);this.setLocation(100,50);this.setTitle("XW");this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setIconImage(image);this.setVisible(true);}public void search(){final JDialog searchDialog = new JDialog();Container con = searchDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchlabel = new JLabel("Search:");JLabel replacelabel = new JLabel("Replace by");final JTextField searchtext = new JTextField(15);final JTextField replacetext = new JTextField(15);final JCheckBox matchcase = new JCheckBox("Seperated by big characters");ButtonGroup bgroup = new ButtonGroup();final JRadioButton up = new JRadioButton("Up");final JRadioButton down = new JRadioButton("Down");down.setSelected(true);bgroup.add(up);bgroup.add(down);JButton next = new JButton("Find Next");JButton replace = new JButton("Replace");final JButton replaceall = new JButton("Replace All");next.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(searchtext.getText().equals("")){JOptionPane.showMessageDialog(searchDialog,"Search Field can't be empty'!","Warning",JOptionPane.WARNING_MESSAGE);}else{String a;String b;if(matchcase.isSelected()){a = editArea.getText();b = searchtext.getText();}else{a = editArea.getText().toLowerCase();b = searchtext.getText().toLowerCase();}if(down.isSelected()){int l = a.indexOf(b,l0);if(l > 0){l0 = l + 1;editArea.select(l,l + searchtext.getText().length());}else{JOptionPane.showMessageDialog(searchDialog,"No next","Warning",JOptionPane.WARNING_MESSAGE);}}if(up.isSelected()){}}}});replace.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){if(replacetext.getText()== null && editArea.getSelectedText()!= null){System.out.println("kong succeed!");editArea.replaceSelection("");}else if(replacetext.getText()!= null && editArea.getSelectedText()!= null){System.out.println("fei kong succeed!");editArea.replaceSelection(replacetext.getText());}}});replaceall.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.setCaretPosition(0);int a = 0;int b = 0;int replaceCount = 0;if(searchtext.getText()==null){JOptionPane.showMessageDialog(searchDialog,"Please Input the Search String!","Warning",JOptionPane.WARNING_MESSAGE);searchtext.requestFocus(true);return ;}while(a > -1){int startpos = editArea.getCaretPosition();String sa,sb;String s1 = editArea.getText();String s2 = s1.toLowerCase();String s3 = searchtext.getText();String s4 = s3.toLowerCase();if(matchcase.isSelected()) {sa = s1;sb = s3;}else{sa = s2;sb = s4;}if(up.isSelected()){if(editArea.getSelectedText() == null){a = sa.lastIndexOf(sb,startpos - 1);}else{a = sa.lastIndexOf(sb,startpos - searchtext.getText().length() - 1);}}else if(down.isSelected()){if(editArea.getSelectedText() == null){a = sa.indexOf(sb,startpos);}else{a = sa.indexOf(sb,startpos - searchtext.getText().length() + 1);}}}}});JPanel bottomPanel=new JPanel();JPanel centerPanel=new JPanel();JPanel topPanel=new JPanel();JPanel direction=new JPanel();direction.setBorder(BorderFactory.createTitledBorder("direction:"));direction.add(up);direction.add(down);JPanel replacePanel=new JPanel();replacePanel.setLayout(new GridLayout(2,1));replacePanel.add(replace);replacePanel.add(replaceall);topPanel.add(searchlabel);topPanel.add(searchtext);topPanel.add(next);centerPanel.add(replacelabel);centerPanel.add(replacetext);centerPanel.add(replacePanel);bottomPanel.add(matchcase);bottomPanel.add(direction);//bottomPanel.add(cancelbutton);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);searchDialog.setTitle("Search");searchDialog.setSize(400,350);searchDialog.setLocation(450,200);searchDialog.setResizable(false);searchDialog.setVisible(true);}public void dialogforfont(){final JDialog fontDialog = new JDialog();final JLabel example = new JLabel("demo for font");example.setHorizontalAlignment(SwingConstants.CENTER);example.setPreferredSize(new Dimension(200,30));fontDialog.setTitle("Font Setup");Container con=fontDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));final Font currentFont=editArea.getFont();newfont = currentFont;JLabel font = new JLabel("Font:");font.setPreferredSize(new Dimension(100,20));JLabel style = new JLabel("style");style.setPreferredSize(new Dimension(100,20));JLabel size = new JLabel("size");size.setPreferredSize(new Dimension(100,20));final JTextField nfont = new JTextField(10);nfont.setPreferredSize(new Dimension(30,30));final JTextField nstyle = new JTextField(8);nstyle.setPreferredSize(new Dimension(30,30));final JTextField nsize = new JTextField(3);nsize.setPreferredSize(new Dimension(30,30));nfont.setText(currentFont.getFontName());nfont.selectAll();if(currentFont.getStyle()==Font.PLAIN)nstyle.setText("chang gui");else if(currentFont.getStyle()==Font.BOLD)nstyle.setText("cu ti");else if(currentFont.getStyle()==Font.ITALIC)nstyle.setText("xie ti");else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))nstyle.setText("cu xie ti");nstyle.requestFocus();nstyle.selectAll();nsize.setText(currentFont.getSize()+"");nsize.requestFocus();nsize.selectAll();GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();final String fontname[] = ge.getAvailableFontFamilyNames();int defaultFontIndex = 0;for(int i = 0;i < fontname.length;i ++){if(fontname[i].equals(currentFont.getFontName())){defaultFontIndex = i;break;}}final JList listfont = new JList(fontname);listfont.setSelectedIndex(defaultFontIndex);listfont.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);listfont.setVisibleRowCount(7);listfont.setFixedCellWidth(82);listfont.setFixedCellHeight(20);listfont.addListSelectionListener(new ListSelectionListener(){public void valueChanged(ListSelectionEvent event){nfont.setText(fontname[listfont.getSelectedIndex()]);nfont.requestFocus();nfont.selectAll();Font newFont = new Font(nfont.getText(),newfont.getStyle(),newfont.getSize());example.setFont(newFont);newfont = newFont;}});final String fontstyle[] = {"chang gui","cu ti","xie ti","cu xie ti"};final JList liststyle = new JList(fontstyle);liststyle.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);if(currentFont.getStyle()==Font.PLAIN)liststyle.setSelectedIndex(0);else if(currentFont.getStyle()==Font.BOLD)liststyle.setSelectedIndex(1);else if(currentFont.getStyle()==Font.ITALIC)liststyle.setSelectedIndex(2);else if(currentFont.getStyle()==(Font.BOLD+Font.ITALIC))liststyle.setSelectedIndex(3);liststyle.setVisibleRowCount(7);liststyle.setVisibleRowCount(7);liststyle.setFixedCellWidth(99);liststyle.setFixedCellHeight(20);liststyle.addListSelectionListener(new ListSelectionListener(){public void valueChanged(ListSelectionEvent e){nstyle.setText(fontstyle[liststyle.getSelectedIndex()]);nstyle.requestFocus();nstyle.selectAll();int newstyle = 0;if(nstyle.getText().equals("chang gui")){newstyle = Font.PLAIN;}else if(nstyle.getText().equals("cu ti")){newstyle = Font.BOLD;}else if(nstyle.getText().equals("xie ti")){newstyle = Font.ITALIC;}else{newstyle = Font.BOLD + Font.ITALIC;}Font newFont = new Font(nfont.getText(),newstyle,newfont.getSize());example.setFont(newFont);newfont = newFont;}});final String fontsize[] = {"11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30"};final JList listsize = new JList(fontsize);int defaultFontSizeIndex = 0;for(int i = 0;i < fontsize.length;i ++){if(fontsize[i].equals(currentFont.getSize() + "")){defaultFontSizeIndex = i;break;}}listsize.setSelectedIndex(defaultFontSizeIndex);listsize.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);listsize.setVisibleRowCount(7);listsize.setFixedCellWidth(39);listsize.setFixedCellHeight(20);listsize.addListSelectionListener(new ListSelectionListener(){public void valueChanged(ListSelectionEvent e){nsize.setText(fontsize[listsize.getSelectedIndex()]);nsize.requestFocus();nsize.selectAll();Font newFont = new Font(nfont.getText(),newfont.getStyle(),Integer.valueOf(nsize.getText()));example.setFont(newFont);newfont = newFont;}});JButton fontokbutton = new JButton("OK");fontokbutton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){editArea.setFont(newfont);fontDialog.dispose();}});JButton fontcancelbutton = new JButton("Cancel");fontcancelbutton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){fontDialog.dispose();  }});JPanel samplePanel=new JPanel();samplePanel.setBorder(BorderFactory.createTitledBorder("示例"));samplePanel.add(example);con.add(font);con.add(style);con.add(size);con.add(nfont);con.add(nstyle);con.add(nsize);con.add(new JScrollPane(listfont));con.add(new JScrollPane(liststyle));con.add(new JScrollPane(listsize));con.add(samplePanel);con.add(fontokbutton);con.add(fontcancelbutton);fontDialog.setSize(350,340);fontDialog.setLocation(200,200);fontDialog.setResizable(false);fontDialog.setVisible(true);}public void fresh(){this.validate();}public void status(){editArea.addCaretListener(new CaretListener(){public void caretUpdate(CaretEvent e){ try{ int pos = editArea.getCaretPosition(); int lineOfC = editArea.getLineOfOffset(pos) + 1; int col = pos - editArea.getLineStartOffset(lineOfC - 1) + 1;statusLabel.setText("Current Location is " + lineOfC + " row, " + col + " line");}catch(Exception ex) {statusLabel.setText("No Location");} } });container.add(statusLabel,BorderLayout.SOUTH);}public void resetTitle(String s){String str = s.substring(0,s.length()-5);this.setTitle(str + " - XW");}public void dialogShow(){JDialog dialog = new JDialog(this,"Page Setup");dialog.setSize(400,300);dialog.setLocationRelativeTo(this);dialog.setVisible(true);}public static void main(String[] args){Editor example = new Editor();}
}

java-编写简单的编辑器相关推荐

  1. 用Java编写简单的扑克牌游戏

    昨天我帮助一位朋友解决了这个问题,今天我即兴想写一篇详细的关于用Java编写扑克牌游戏的文章. 当然我这里只是实现一些简单的功能. 关于扑克牌游戏的特征,想必大家都有所接触过,有扑克牌,玩扑克牌游戏的 ...

  2. 用JAVA编写简单呼叫器餐厅,使用Java编写Palm OS程序的解决方案之一

    现在,使用Java语言为 Palm OS编写程序的领域还没有完全统一,并且也有许多程度上的差异,目前,市面上有好几种不同的可用的应用程序接口,每种应用程序接口都给出了一个到当前的Palm OS应用程序 ...

  3. 利用Java编写简单的猜拳游戏

    猜拳游戏要求用Java编写一个人机对战并判断输赢,记录输赢情况. 其中,1代表石头,2代表剪刀,3代表布,110表示结束游戏. 思路:首先定义输入函数,并提示用户输入猜拳数值,定义一个随机数代表电脑数 ...

  4. 用JAVA编写简单呼叫器餐厅,使用Java编写Palm OS程序的解决方案1

    使用Java语言为 Palm OS编写程序的领域还没有完全统一,并且也有许多程度上的差异,目前,市面上有好几种不同的可用的应用程序接口,每种应用程序接口都给出了一个到当前的Palm OS应用程序不同程 ...

  5. 使用Java编写简单的老虎机游戏

    无论游戏多么简单或复杂 ,Java都能胜任! 在这篇文章中,让我们看一下Java编程的初学者如何制作一个简单而功能齐全的老虎机. 老虎机已经存在很长时间了,但是它的娱乐价值似乎并没有减弱. Inter ...

  6. Java编写简单密码问题

    package three;/** 简单密码* Julius Caesar曾经使用过一种很简单的密码,对于明文中的每个字符,* 用字母表中的后5位所对应的字符代替* 就得到了密文,例如,字符A用F代替 ...

  7. 原生JS编写简单的编辑器

    使用vue编写的,没有任何依赖,可改写其它形式 轻量级编辑器只是在document.execCommand()方法做了包装,不兼容的浏览器器生成的标签是一致的,所以的富文本的选择要根据项目决定 实现了 ...

  8. java简单的记事本程序_如何用JAVA编写简单的记事本程序?

    展开全部 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; i ...

  9. 关于自己编写简单游戏编辑器的介绍

    该编辑器编写的初衷是为了帮助游戏一些功能的开发比如新手引导,成就等等.现在编写的是一个框架,具体功能需要自行扩展. 目录 一.编辑器结构(原始数据+触发器) 1.编辑器总体结构 2.原始数据 3.触发 ...

  10. Java编写简单五子棋游戏

    编写15*15的棋盘,其中第15行和第15列表示坐标. 详细代码实现如下: import java.util.Scanner; /** 五子棋*/ public class WZQ {static S ...

最新文章

  1. 网络中常见的互通与不通—Vecloud微云
  2. python一年收入_你的年收入过5万了吗?数据科学家的Python模块和包
  3. Windows7旗舰版磁盘分区详解—附分区步骤截图
  4. 给文章中重复标签排序
  5. fedora 23 vlc 以root运行的方法
  6. 什么是ARP协议,如何查看ARP表项、如何配置静态ARP?
  7. 禧龙字王 v1.0 beta 4 工作站版 是什么
  8. 吴恩达---机器学习的流程(持续更新)
  9. python爬取站酷海洛图片_站酷海洛图片爬取
  10. sqlmap 注入教程 常用命令大全
  11. Delphi ActionList详解
  12. 小程序上传文件报错uploadFile:fail url scheme is invalid,uploadFile:fail createUploadTask:fail Error: Invalid
  13. 宝塔linux面板什么原理,宝塔Linux面板是什么
  14. 用程序员计算机算进制,一文带你读懂计算机进制
  15. 用Latex写毕业论文-- 用 ctexset 重定义标题(如:第一章)
  16. MDX基本概念和语法
  17. CefSharp高版本问题
  18. java图片转二进制
  19. 松下FPXH自动螺丝机程序 昆仑通态触摸屏控触摸
  20. 工业路由器下的智慧园林监测解决方案

热门文章

  1. JS获取扫码设备扫描到的值
  2. JAVA源码系列-ArrayList
  3. Spring+SpringMVC+Mybatis简单整合 图书管理项目 实现增删改查
  4. 这五件事,二次SaaS创业的老炮儿都在做
  5. 软件测试工程师如何优雅的“甩锅”
  6. 高质量=高成本?优思学院告诉你并非必然!
  7. 点餐系统-C++实现
  8. FAQ(43): com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL sy
  9. 迪士尼和李宁合作推出“李宁复古运动米奇系列”服饰
  10. 《MVC》——ViewData、ViewBag、TempData、model