Một chương trình Notepad đơn giản với java
Trong bài này, tôi sẽ hướng dẫn cho chúng ta cách tạo ra 1 chương trình soạn thảo đơn giản với java.
Trước hết chúng ta xem qua giao diện của chương trình

Code cho các chức năng:
- Tạo tập tin mới chẳng qua chúng ta cho textbox mang giá trị rỗng. Ở đây chúng ta không xét đến trường hợp nếu có thay đổi trong quá trình mở thì ta sẽ hởi lưu hay không. Bạn có thể hiện thực nó bằng cách thêm vào 1 biến boolean kiểm tra tình hình. Khi Text có sự thay đổi thì bật biến này thành true. Nếu người dùng nhấn nút new, kiểm tra biến này và có hành động thích đáng.
- Mở 1 tập tin: Ta dùng code đọc file text chuẩn để đọc từng dòng sau đó xuất lên textpane
| …
try { |
-Lưu tập tin: Ta cũng dùng code ghi văn bản chứa đụng trong textpane ra file
| …
try { … |
- Nút print: In nội dung của textpane ra máy in
| void PrintFunction() { try { MessageFormat header = new MessageFormat(“http;//vovanhai.wordpress.com”); MessageFormat footer = new MessageFormat(“Best java tutorial website”); tpContent.print(header, footer, true, null, null, true); } catch (Exception e) { e.printStackTrace(); } } |

Code cho các chức năng Cut, Copy, Paste thì rất dễ dàng bằng cách gọi tương ứng từng method có sẵn trong đối tượng JTextPane.
Sau đây là code hoàn chỉnh của chương trình
tập tin MySimpleNotepad.java
|
package mynotepad.vovanhai.wordpress.com;
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.Scanner;
import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.KeyStroke;
public class MySimpleNotepad extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;
private JMenuBar menubar; private JMenu mFile,mEdit,mHelp; private JMenuItem itemNew,itemOpen,itemSave,itemPrint,itemExit; private JMenuItem itemCut,itemCopy,itemPaste,itemAbout;
private JTextPane tpContent; private JLabel lblStatus;
public MySimpleNotepad() { super(“T? tèo simple Notepad”); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(500,500); createGUI(); createMenu(); }
void createGUI() { tpContent=new JTextPane(); this.add(new JScrollPane(tpContent),BorderLayout.CENTER); lblStatus=new JLabel(“Ready…”); this.add(lblStatus,BorderLayout.SOUTH); } void createMenu() { menubar=new JMenuBar();this.setJMenuBar(menubar); menubar.add(mFile=new JMenu(“File”)); menubar.add(mEdit=new JMenu(“Edit”)); menubar.add(mHelp=new JMenu(“Help”));
mFile.add(itemNew=new JMenuItem(“Tập tin mới”,‘T’));mFile.addSeparator(); mFile.add(itemOpen=new JMenuItem(“Mở tập tin”,‘M’)); mFile.add(itemSave=new JMenuItem(“Lưu tập tin”,‘L’));mFile.addSeparator(); mFile.add(itemPrint=new JMenuItem(“In ra máy in”,‘I’));mFile.addSeparator(); mFile.add(itemExit=new JMenuItem(“Thoát”,‘T’)); itemNew.setAccelerator(KeyStroke.getKeyStroke(‘N’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemOpen.setAccelerator(KeyStroke.getKeyStroke(‘O’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemSave.setAccelerator(KeyStroke.getKeyStroke(‘S’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemPrint.setAccelerator(KeyStroke.getKeyStroke(‘P’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemExit.setAccelerator(KeyStroke.getKeyStroke(‘X’,java.awt.event.InputEvent.ALT_DOWN_MASK)); itemNew.addActionListener(this);itemOpen.addActionListener(this); itemSave.addActionListener(this);itemPrint.addActionListener(this); itemExit.addActionListener(this);
mEdit.add(itemCopy=new JMenuItem(“Copy”,‘C’)); mEdit.add(itemCut=new JMenuItem(“Cut”,‘u’)); mEdit.add(itemPaste=new JMenuItem(“Paste”,‘P’)); itemCut.addActionListener(this); itemCopy.addActionListener(this);itemPaste.addActionListener(this); itemCopy.setAccelerator(KeyStroke.getKeyStroke(‘C’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemCut.setAccelerator(KeyStroke.getKeyStroke(‘X’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); itemPaste.setAccelerator(KeyStroke.getKeyStroke(‘V’,java.awt.event.InputEvent.CTRL_DOWN_MASK)); mHelp.add(itemAbout= new JMenuItem(“About”)); itemAbout.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { Object o=e.getSource(); if(o.equals(itemExit)) { System.exit(1); } else if(o.equals(itemNew)) tpContent.setText(“”); else if(o.equals(itemOpen)) OpenFunction(); else if(o.equals(itemSave)) SaveFunction(); else if(o.equals(itemPrint)) PrintFunction(); else if(o.equals(itemCopy)) tpContent.copy(); else if(o.equals(itemPaste)) tpContent.paste(); else if(o.equals(itemCut)) tpContent.cut(); else if(o.equals(itemAbout)) About(); } /*** Dùng cho menu mở tập tin*/ void OpenFunction() { JFileChooser fc=new JFileChooser(); if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) { try { String selFile=fc.getSelectedFile().getAbsolutePath();//lấy đường dẫn của file được chọn Scanner sc=new Scanner(new FileInputStream(selFile),”UTF-8″); lblStatus.setText(“Opened: “+selFile); String line=“”; while(sc.hasNextLine()) line+=sc.nextLine()+“\n”; tpContent.setText(line); sc.close(); } catch (Exception e) { e.printStackTrace(); } } } /*** Dùng cho menu lưu tập tin*/ void SaveFunction() { JFileChooser fc=new JFileChooser(); if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION) { try { String selFile=fc.getSelectedFile().getAbsolutePath(); lblStatus.setText(“Saved: “+selFile); PrintWriter out=new PrintWriter(new FileOutputStream(selFile),true); out.print(tpContent.getText()); out.close(); } catch (Exception e) { e.printStackTrace(); } } } //In ấn void PrintFunction() { try { MessageFormat header = new MessageFormat(“http;//vovanhai.wordpress.com”); MessageFormat footer = new MessageFormat(“Best java tutorial website”); tpContent.print(header, footer, true, null, null, true); } catch (Exception e) { e.printStackTrace(); } } //About void About() { JDialog dlg=new JDialog(this);dlg.setLayout(new BorderLayout()); dlg.setTitle(“About”);dlg.setSize(350,100); final String URL=“http://vovanhai.wordpress.com”; JLabel l1=new JLabel(URL,JLabel.CENTER); l1.setCursor(new Cursor(Cursor.HAND_CURSOR)); l1.setForeground(Color.blue); dlg.add(l1,BorderLayout.CENTER); l1.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { String commands=“cmd /c start “+ URL ; try{ Runtime rt = Runtime.getRuntime(); rt.exec(commands); }catch(Exception ioe){ ioe.printStackTrace(); } } });
dlg.setVisible(true); } }
|
và tập tin Starting.java
|
package mynotepad.vovanhai.wordpress.com;
public class Starting { public static void main(String[] args) { new MySimpleNotepad().setVisible(true); } } |
**Lưu ý:: đối tượng JTextPane còn có thể làm được nhiều thứ hay ho hơn nhiều. Ở đây chỉ là 1 demo nhỏ.
Bạn có thể download bản execuable jar file tại đây để chạy thử.
Chúc các bạn thành công
Ngân said
chương trình của bạn dc đấy
nhân tiện đây mình demo với các bạn bản JNotepad của mình
Mình thiếu chức năng print loay hoay mãi ko biết làm thé nào
bạn có thể download về xem thử tại đây
http://www.mediafire.com/file/mmnnetgh1ni/JNotepad_Standar.rar
Gui bai Mynotepad hoan chinh said
Thay gui bai mynote hoan chinh dum em di,e lam theo ma bi loi nhieu qua,em moi hoc nen chua ro lam,mong thay chi them.thanks
Gui bai Mynotepad hoan chinh said
Email :nld_1302@yahoo.com.vn
Gui bai Mynotepad dum em nha thay.thanks
Nguyễn Văn Ngân said
Bạn nào quan tâm có thể vào đây download mã nguồn chương trình của mình
Đây là bản JNotepad bằng java của mình
http://www.mediafire.com/file/mmnnetgh1ni/JNotepad_Standar.rar
Nguyễn Văn An said
Thưa thầy, em cần biết thêm về JTextPane để có thể viết một ứng dụng chỉnh sửa tự động một file text theo một qui chuẩn có sẵn ( sắp xếp câu theo một thứ tự nào đó,…), mong thầy hướng dẫn giúp em, cảm ơn thầy.
Magichand said
xin chào Thầy .Chào các bạn .Sắp tới em có làm đề tài notepad .Em thấy tài liệu của thầy rất bổ ich .Nhưng em làm thì sai nhiều chổ .Thầy có thể gửi mã nguồn mỡ cho em được không ah theo mail giatu124@yahoo.com .Cám ơn thầy
Hung said
Thầy ơi, em muốn thay đổi icon cốc caffee mặc định trên trái ứng dụng java thì làm như thế nào ạ?
vovanhai said
JFrame frm = new JFrame(“helo”);
frm.setIconImage(frm.getToolkit().getImage(“c://x.gif”));
//……………….
ngannv said
Ban dung goi minh = thay
Minh la sinh vien nam 3
minh cung moi hoc java.
luc bat dau hoc minh bat gap cai open file nen nay ra y tuong viet cai Jnotepad nay…vua` hoc vua viet vua may` mo`…
luc’ do’ moi’ hoc core nen code giao dien = Jcreator 4.5
cung k de y la’m cai setIcon
Ban co the chay ma nguon cua minh = Jcreator
Cu0ngNguy3n said
Cho em hỏi trong Notepad khi mình mở một File Txt và mình thay đổi nội dung của nó thì làm sao để kiểm tra nội dung trong file đó đã bị thay đổi rồi
Cu0ngNguy3n said
Cho hỏi chèn hình ảnh vào Form dùng NetBeans thế nào ?
Võ Văn Hải said
Nếu bạn chỉ là kiểm tra sau khi nó được modified thì bạn kiểm tra datetime modified.
test said
Link Jnotepad update
http://www.megashare.vnn.vn/download.php?id=FF212C3D2
minhhai said
thay co the gui huong dan lam giup.em chay bi loi qua troi luon.
mail em:minhhai1186@gmail.com.thank thay
Nhh92 said
String selFile=fc.getSelectedFile().getAbsolutePath();
fc là gì vậy ạ ??
Võ Văn Hải said
fc là 1 instance của JFileChooser
Phạm Sơn said
try{
//String selFile=fc.getSelectedFile().getAbsolutePath();//lấy đường dẫn của file được chọn
Scanner sc = new Scanner(new FileInputStream(filename));
//lblStatus.setText(“Opened: “+selFile);
String line=”";
while(sc.hasNextLine())
line+=sc.nextLine()+”\n”;
//tpContent.setText(line);
System.out.print(line); //?????????????????????????????????
sc.close();
}catch (Exception e) {
e.printStackTrace();
}
Làm ơn cho em hỏi System.out.print(line); khi in ra kiểu này: câu đầu tiên sao lại có một dấu chấm, mình muốn loại bỏ dấu chấm này thì làm thế nào?
Võ Văn Hải said
In dấu chấm là do text file của bạn lưu dạng unicode.
Xuân Hào said
thầy ơi cho em hỏi code này có ý nghĩa gì vậy ah ? mFile.addSeparator()
Võ Văn Hải said
code này có ý nghĩa gì vậy ah ? mFile.addSeparator(
Thêm 1 đường gạch ngang trong cái menu.
Xin code hoàn chỉnh said
sao em code code hoàn chinh mà chạy không được vậy thầy. Thầy cho em xin code hoàn chỉnh với nhé. Email của em kque.tran@gmail.com. Thanks thầy nhiều ..!!!
Thảo said
Thầy ơi thầy có thề hướng dẫn em chạy từ eclipse qua jcreator được k thấy? vì chạy bằng clipse nó chạy ra nhiều folder quá e không kiểm soát được
.
Kim Que said
Thầy cho em hỏi em muốn thêm chứ năng Find và Replace cho chương trình Nodepad thì làm thế nào ạ? Thầy chỉ em với. Thanks Thầy.
Võ Văn Hải said
Thầy ơi thầy có thề hướng dẫn em chạy từ eclipse qua jcreator được k thấy? vì chạy bằng clipse nó chạy ra nhiều folder quá e không kiểm soát được
Eclipse là ide pro không học thì học cái gì? Còn nếu bạn muốn thì cứ copy mấy cái file java ra là xong.