Java Notepad Development

Source: Internet
Author: User
Tags getmessage gettext



What I want to share today is a Notepad program written in Java. I know there are all kinds of notepad on the market now, but I found that some of the functions are not perfect, or the code hierarchy is not clear enough, and some even looked after the foggy, some also have a very obvious bug, I now share this Notepad program basically to the code level are drawn out, And fixed some known bugs. First look at the interface, shortcut keys I have all added, but not on the interface marked only, the general use of the few shortcuts are directly used!






The main functions of this program are: Open, save, Save As, exit, new, Paste, copy, select All, cut, delete, find, replace, go to, modify fonts, wrap, see Help and other functions. Currently imperfect features have auto-display titles.



First I used the SWT plugin developed in Eclipse, which is slightly different when used across platforms! Install SWT here will not repeat the instructions, we directly to the new project!






First, a new SWT project, named note, this time we say the need to rely on the SWT jar package will be imported automatically, if you have the problem of importing jar, you can also manually import the jar package.



Then set up 3 packages to store our class: dialog (mainly the implementation of some pop-up windows), Noteui (storage of the main implementation class), Utils (grab yo to store some public tool files).



Second, in the Noteui package to create a new living class, we named Note1.java Good, the amount, forget to say, this note1.java is a SWT of the new appliction Windows class, in which you can design to create the layout of this window, The main is the menu bar, and so on, the specific layout can see this diagram:






Once the layout is written, we can add a variety of events.



Third, add shortcut keys





// shortcut key part
open.setAccelerator (SWT.CTRL | 'o');
save_file.setAccelerator (SWT.CTRL | 's');
quit.setAccelerator (SWT.CTRL | 'p');
select_all.setAccelerator (SWT.CTRL + 'a');
new_file.setAccelerator (SWT.CTRL | 'n');
new_file.setAccelerator (SWT.CTRL + 'N'); // New file shortcut
         undo.setAccelerator (SWT.CTRL + 'Z'); // Undo shortcut
         cut.setAccelerator (SWT.CTRL + 'T'); // cut shortcut
         copy.setAccelerator (SWT.CTRL + 'C'); // Copy shortcut
         paste.setAccelerator (SWT.CTRL + 'V'); // Paste shortcut
         delete.setAccelerator (SWT.DEL); // Delete shortcut
         find.setAccelerator (SWT.CTRL + 'F'); // Find shortcuts
         find_next.setAccelerator (SWT.F3); // Find the next shortcut
         replace.setAccelerator (SWT.CTRL + 'H'); // Replace shortcut
         go_to.setAccelerator (SWT.CTRL + 'G'); // Go to shortcut

Four, we start from the simple! , write to see Help first!







MenuItem look_help = new MenuItem (menu_5, SWT.NONE);
look_help.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
UiUtils.showMessageDialog (shell, "Help", "Welcome to my blog: http://blog.csdn.net/sdksdk0!");
}
});
look_help.setText ("View help");
Of course, for this "about us" can use a pop window to write, create a new SWT window file, then we can call: This interface is a concrete implementation across to see the source of my text.







MenuItem menuItem_15 = new MenuItem(menu_6, SWT.NONE);
		menuItem_15.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				About_us as=new About_us();
				as.open();
			}
		});

Five, then we can look at a font settings, mainly call the system itself API on it, call this form and then use! Change the color of the section I only added three colors, other colors you can add yourself,







// font settings
font.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
FontDialog fd = new FontDialog (shell, SWT.None);
Font oldFont = getText (). GetFont ();
if (oldFont! = null) {
fd.setFontList (oldFont.getFontData ());
}
FontData fontData = fd.open ();
if (fontData == null) {
return;
}
Ranch
Color c = new Color (shell.getDisplay (), fd.getRGB (). Red, fd.getRGB (). Green, fd.getRGB (). Blue);
text.setForeground (c);
final Display display = Display.getDefault ();
Font newFont = new Font (display, fontData);
getText (). setFont (newFont);
if (oldFont! = null) {
oldFont.dispose ();
}
}
});
Six, in the bottom line of this notepad has a can record the current time, we can use data to write, and then through the SimpleDateFormat to format the display date time.







Label lblNewLabel = new Label (sashForm, SWT.NONE);
SimpleDateFormat sdf = new SimpleDateFormat ("MMYddyHy: mm: ss");

lblNewLabel.setText ("Instruction Technology welcomes you, now it is:" + sdf.format (new Date ()));
sashForm.setWeights (new int [] {309, 24});

Seven, we can look at copy, paste, cut, select all the writing, the other this should be the simplest, because this can be called directly the following methods. Select all to use Text.selectall directly ();







MenuItem cut = new MenuItem (menu_2, SWT.NONE);
cut.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
getText (). cut ();
}
});
cut.setText ("Cut");

MenuItem copy = new MenuItem (menu_2, SWT.NONE);
copy.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
text.copy ();
}
});
copy.setText ("Copy");

MenuItem paste = new MenuItem (menu_2, SWT.NONE);
paste.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
getText (). paste ();
}
});
paste.setText ("Paste");

Eight, this time we write a search and replace, etc., this time to create a new pop-up method is better,







/ **
* Create contents of the dialog.
* /
private void createContents () {
shell = new Shell (getParent (), getStyle ());
shell.setSize (445, 137);
shell.setLocation (780, 300);
shell.setText ("\ u67E5 \ u627E");
Ranch
textContent = new Text (shell, SWT.BORDER);
textContent.addKeyListener (new KeyAdapter () {
/ **
* Add event to find edit box to synchronize update of find button
* Search if there is content, otherwise it is not clickable
* /
public void keyReleased (KeyEvent e) {
if (textContent.getText ()! = "") {
find_next.setEnabled (true);
chazhao = true;
} else {
find_next.setEnabled (false);
chazhao = false;
}
}
});
textContent.setBounds (99, 10, 204, 22);
Ranch
find_next = new Button (shell, SWT.NONE);
find_next.setEnabled (false);
find_next.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
pareStr = Util.shell.getText_1 (); // Get main window text box content true
index = pareStr.indexOf (textContent.getText (), index); // Get the position of the search string in the parent string starting from index
if (index == -1) {
JOptionPane.showMessageDialog (null, "Not found \" "+ textContent.getText () +" \ "", "Notepad", JOptionPane.ERROR_MESSAGE);
}
int end = index + textContent.getText (). length (); // Get the end position of rendering
Util.shell.selectContent (index, end);
index = index + textContent.getText (). length ();
}
});
find_next.setBounds (329, 6, 99, 27);
find_next.setText ("\ u67E5 \ u627E \ u4E0B \ u4E00 \ u5904 (F)");
Ranch
Label lblNewLabel = new Label (shell, SWT.NONE);
lblNewLabel.setBounds (10, 10, 85, 22);
lblNewLabel.setText ("\ u67E5 \ u627E \ u5185 \ u5BB9 (& N):");
Ranch
Button quxiao = new Button (shell, SWT.NONE);
quxiao.addSelectionListener (new SelectionAdapter () {
/ **
* Set event for cancel button
* /
public void widgetSelected (SelectionEvent e) {
shell.setVisible (false);
}
});
quxiao.setBounds (329, 65, 100, 27);
quxiao.setText ("\ u53D6 \ u6D88");
Ranch
Button qufen = new Button (shell, SWT.CHECK);
qufen.addSelectionListener (new SelectionAdapter () {
/ **
* Determine if it is case sensitive, and if so, change
* /
public void widgetSelected (SelectionEvent e) {
qf = qufen.getSelection ();
}
});
qufen.setBounds (10, 65, 149, 27);
qufen.setText ("\ u533A \ u5206 \ u5927 \ u5C0F \ u5199 (& C)");
Ranch
Label label1 = new Label (shell, SWT.NONE);
label1.setText ("\ u66FF \ u6362 \ u4E3A (& F):");
label1.setBounds (10, 38, 72, 22);
Ranch
replaceText = new Text (shell, SWT.BORDER);
replaceText.addKeyListener (new KeyAdapter () {
/ **
* Add event for replace edit box to synchronize update of replace button
* Replace if there is content, otherwise it is not clickable
* /
public void keyReleased (KeyEvent e) {
if (replaceText.getText ()! = "") {
replaceBtn.setEnabled (true);
} else {
find_next.setEnabled (false);
}
}
});
replaceText.setBounds (99, 38, 204, 22);
Ranch
replaceBtn = new Button (shell, SWT.NONE);
replaceBtn.addSelectionListener (new SelectionAdapter () {
/ **
* Replace button event
* /
public void widgetSelected (SelectionEvent e) {
pareStr = Util.shell.getText_1 (); // Get main window text box content true
pareStr = pareStr.replaceFirst (textContent.getText (), replaceText.getText ());
Util.shell.showText (pareStr);
}
});
replaceBtn.setText ("\ u66FF \ u6362 (& R):");
replaceBtn.setEnabled (false);
replaceBtn.setBounds (329, 32, 99, 27);

We can add the appropriate calls to the previous main class, the Note1, for example:
replace.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				FindWindow fw = new FindWindow(shell,SWT.DIALOG_TRIM);
				fw.open();
			}
		});
Find replacements and so on are the same, there is no repetition of the explanation.





Nine, as for the jump words so that you can:


queding.addSelectionListener (new SelectionAdapter () {
/ **
* OK to jump to a certain line
* /
public void widgetSelected (SelectionEvent e) {
int n = Integer.parseInt (goto_line.getText ());
goto_line.setText ("" + n + "");
Util.shell.gotoOneLine (1);
}
});


Ten, the next is the most important file open and save operations, generally this place the most bugs



Let's take a look at the open file operation, I use the GBK encoding to read the file, I found that if the default encoding read file is garbled, so I directly add gbk, simple rough





// turn on
open.addSelectionListener (new SelectionAdapter () {
@Override
public void widgetSelected (SelectionEvent e) {
FileDialog fd = new FileDialog (shell, SWT.None);
String file = fd.open ();
File f = new File (file);
BufferedInputStream bis = null;
if (f.exists () && f.isFile ()) {
try {
bis = new BufferedInputStream (new FileInputStream (f));
byte [] bs = new byte [1024];
int length = 0;
StringBuffer sb = new StringBuffer ();
while ((length = bis.read (bs, 0, bs.length))! = -1) {
sb.append (new String (bs, 0, length, "gbk"));
}
text.setText (sb.toString ());
} catch (Exception e1) {
e1.printStackTrace ();
UiUtils.showMessageDialog (shell, "There was an error", e1.getMessage ());
} finally {
if (bis! = null) {
try {
bis.close ();
} catch (IOException e1) {
UiUtils.showMessageDialog (shell, "There was an error", e1.getMessage ());
}
}
}

} else {
UiUtils.showMessageDialog (shell, "An error has occurred",
"File" + f.getName () + "does not exist");
}
}
});


Xi, then is to write the code to save the file, there are two ways to save, one is to save directly, the other is saved as. We use FileOutputStream to write from the program to the file.





public class SaveMethod {
/ **
* Divide the two saved methods into classes for easy invocation
* Save   * Save as
* /
public void Save () {
Ranch
/ **   * save document
* /
if (Util.shell.fileDir! = null) {// Indicates that the file has a directory, it is saved directly when saved, no popup window is required
Util.shell.shell.setText ((new File (Util.shell.fileDir.trim ())). GetName ()); // Get the file name (without path) for setting the title
FileOutputStream fileWriter;
try {
fileWriter = new FileOutputStream (Util.shell.fileDir);
BufferedWriter out = new BufferedWriter (new OutputStreamWriter (fileWriter, "gbk"));
out.write (Util.shell.getText (). getText ());
out.close ();
fileWriter.close ();
} catch (IOException e1) {
e1.printStackTrace ();
}
}
else {// Otherwise it has never been saved, then call Save As window
SaveAs ();
}
}
Ranch
public void SaveAs () {
/ **
* Save as this method to encapsulate, easy to call
* /
FileDialog dialog = new FileDialog (Util.shell.shell, SWT.SAVE);
dialog.setFilterPath (System.getProperty ("C: \\ Documents and Settings")); // Set the default path to open
dialog.setFilterExtensions (new String [] {"*. txt", "*. sql", "*. java", "*. doc"});
String file = dialog.open (); // Open the window and return the file directory selected by the user
if (file! = null) {
Util.shell.fileDir = file; // Save the file directory for future use
}
if (file! = null)
{
Util.shell.shell.setText ((new File (file.trim ())). GetName ()); // Get the file name (without path) for setting the title
FileOutputStream fileWriter;
try {
fileWriter = new FileOutputStream (file);
BufferedWriter out = new BufferedWriter (new OutputStreamWriter (fileWriter, "gbk"));
out.write (Util.shell.getText (). getText ());
out.close ();
fileWriter.close ();
} catch (IOException e1) {
e1.printStackTrace ();
}
}
}
}

12, finally we write out, if you want to lazy words directly with system.exit (0), but also can achieve this function, but I think! It's not so friendly to quit! So I wrote the following optimization of the Exit Method!





If the save means that there is filedir, call the saved function directly, if there is no Filedir the file is open, the path has not been determined, so jump save as a form.
First, define a global variable, string filedir = null, assign it null, default all files are not saved
Then, whether the file is opened or saved as a file, the directory in which the file is located (including file name and suffix name) is recorded in Filedir, and finally in the Save event to determine whether Filedir is empty.





public void quit () {
/ **
* Determine if saving is required when the exit function exits
* /
String tips;
if (Util.shell.fileDir! = null || Util.shell.getText (). getText ()! = "") {// The file directory is not empty, indicating that there are open files, you need to ask whether to save them
if (Util.shell.fileDir == null) {
tips = "File untitled text has changed. \ n" + "Do you want to save the file";
} else {
tips = "File" + Util.shell.fileDir + "The text has changed. \ n" + "Do you want to save the file";
}
int n = JOptionPane.showConfirmDialog (null, tips, "Notepad", JOptionPane.YES_NO_CANCEL_OPTION);
if (n == 0) {// yes return 0 no return 1 cancel return 2
SaveMethod savemethod = new SaveMethod ();
savemethod.Save (); // Click Yes, save the file and then open the file
} else if (n == 1) {// return no
System.exit (0);
} else if (n == 2) {// Return to cancel
return;
}
System.exit (0);
} else {
if (Util.shell.getText (). getText ()! = "") {// If the directory is empty, but the content is not empty, it means there is content but it is not saved, it prompts
tips = "File untitled text has changed! \ n" + "Want to save the file?";
int n = JOptionPane.showConfirmDialog (null, tips, "Notepad", JOptionPane.YES_NO_CANCEL_OPTION);
if (n == 0) {// yes return 0 no return 1 cancel return 2
SaveMethod savemethod = new SaveMethod ();
savemethod.Save (); // Click Yes, save the file and then open the file
} else if (n == 1) {// return no
System.exit (0);
} else if (n == 2) {// Return to cancel
return;
}
System.exit (0);
} else {
Ranch
}
}
System.exit (0);
}






Written in the end, we also encapsulate a pop-up window Utils class





public class UiUtils {

/ **
* Tools for displaying common dialog boxes
* @param shell
* @param title
* @param message
* /
public static void showMessageDialog (Shell shell, String title, String message) {
MessageBox mb = new MessageBox (shell, SWT.None);
mb.setText (title);
mb.setMessage (message);
mb.open ();
}
} 
Summary: Technology from the thinking, I think first in the programming or to have a whole idea of the concept, do not come up directly to write code, the first thing you should think about what you want to do, how to achieve! Try to encapsulate the reusable code so that the overall code looks more concise and straightforward. Insist on learning, persist in sharing!











Source: Click Open Link http://download.csdn.net/detail/sdksdk0/9501286












Java Notepad Development


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.