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 {
String selFile=fc.getSelectedFile().getAbsolutePath();//lấy đường dẫn của file được chọn
Scanner sc=new Scanner(new FileInputStream(selFile));
lblStatus.setText(“Opened: “+selFile);
String line=”";
while(sc.hasNextLine())
line+=sc.nextLine()+”\n”;
tpContent.setText(line);
sc.close();
} catch (Exception e) {
e.printStackTrace();
}

-Lưu tập tin: Ta cũng dùng code ghi văn bản chứa đụng trong textpane ra file

 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();
}

- 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, truenullnulltrue);

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

Post a Comment

Mới hơn Cũ hơn