Bài 38-Thiết kế giao diện trong Kotlin – phần 4

[polldaddy poll=9764234]

Bài 37-Thiết kế giao diện trong Kotlin – phần 3 bạn đã xây dựng được một phần mềm quản lý Sản phẩm nhưng chưa liên quan tới OOP, tương tác File , JMenu và JFileChooser. Trong bài này Tui sẽ tiếp tục phát triển bài 37, nên bạn nào chưa học bài 37 thì tự vào học để lấy Code tiếp tục phát triển nhé, giao diện sẽ bổ sung thêm JMenu để lưu file và mở File:

Bài này Tui bổ sung thêm các Menu Lưu File và Mở file với 4 loại mà chúng ta đã được học trước đó (Text File, Serialize File, XML file,JSon File) cũng như các Icon cho các Button.

Chương trình sẽ dùng JFileChooser để cho phép người dùng chỉ định nơi lưu trữ, đặc biệt phải dùng lập trình hướng đối tượng để xử lý. Bài học này khá khó nên các bạn phải chú ý làm theo hướng dẫn và chịu khó suy luận.

Bây giờ Tui hướng dẫn chi tiết cách thực hiện:

Trước tiên bạn lôi cái Project làm ở bài 37 ra, bổ sung thêm danh sách các hình ảnh sau(bạn tạo một thư mục hinh, các hình bạn tự tải rồi lưu vào đây, lấy đại cho nó lành):

Bổ sung ICon cho các Button trong SanPhamPanel bằng cách tạo một hàm createICon() có coding như sau(Tui lược bỏ các coding cũ, chút nữa sẽ có coding đầy đủ):

[code language=”java”]

public SanPhamPanel() {
//Tui hide coding …. cho dễ nhìn
createICon();
}

private void createICon() {
btnLuu.setIcon(new ImageIcon(“hinh/add.png”));
btnTiep.setIcon(new ImageIcon(“hinh/clear.png”));
btnXoa.setIcon(new ImageIcon(“hinh/delete.png”));
btnThoat.setIcon(new ImageIcon(“hinh/exit.png”));
}

[/code]

Tiếp tục vào SanPhamUI để bổ sung các Menu và Icon cho nó (Tui lược bỏ các coding cũ, chút nữa sẽ có coding đầy đủ):

[code language=”java”]

public class SanPhamUI extends JFrame {
JMenuBar mnuBar;
JMenu mnuSystem;
JMenu mnuSystemSave;
JMenuItem mnuSystemSaveTextFile;
JMenuItem mnuSystemSaveSerializeFile;
JMenuItem mnuSystemSaveXMLFile;
JMenuItem mnuSystemSaveJSonFile;
JMenu mnuSystemOpen;
JMenuItem mnuSystemOpenTextFile;
JMenuItem mnuSystemOpenSerializeFile;
JMenuItem mnuSystemOpenXMLFile;
JMenuItem mnuSystemOpenJSonFile;
JMenuItem mnuSystemExit;
public SanPhamUI(String title)
{
super(title);
setContentPane(new SanPhamPanel().getPnMain());
createMenu();
createICon();
}
public void createMenu()
{
mnuBar=new JMenuBar();
setJMenuBar(mnuBar);
mnuSystem=new JMenu(“Hệ thống”);
mnuBar.add(mnuSystem);

mnuSystemSave=new JMenu(“Lưu file”);
mnuSystem.add(mnuSystemSave);
mnuSystemSaveTextFile=new JMenuItem(“Text file”);
mnuSystemSave.add(mnuSystemSaveTextFile);
mnuSystemSave.addSeparator();
mnuSystemSaveSerializeFile=new JMenuItem(“Serialize file”);
mnuSystemSave.add(mnuSystemSaveSerializeFile);
mnuSystemSave.addSeparator();
mnuSystemSaveXMLFile=new JMenuItem(“XML file”);
mnuSystemSave.add(mnuSystemSaveXMLFile);
mnuSystemSave.addSeparator();
mnuSystemSaveJSonFile=new JMenuItem(“JSON file”);
mnuSystemSave.add(mnuSystemSaveJSonFile);

mnuSystem.addSeparator();

mnuSystemOpen=new JMenu(“Đọc File”);
mnuSystem.add(mnuSystemOpen);
mnuSystemOpenTextFile=new JMenuItem(“Text file”);
mnuSystemOpen.add(mnuSystemOpenTextFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenSerializeFile=new JMenuItem(“Serialize file”);
mnuSystemOpen.add(mnuSystemOpenSerializeFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenXMLFile=new JMenuItem(“XML file”);
mnuSystemOpen.add(mnuSystemOpenXMLFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenJSonFile=new JMenuItem(“JSON file”);
mnuSystemOpen.add(mnuSystemOpenJSonFile);

mnuSystem.addSeparator();

mnuSystemExit=new JMenuItem(“Thoát”);
mnuSystem.add(mnuSystemExit);
}
private void createICon() {
mnuSystem.setIcon(new ImageIcon(“hinh/system.png”));
mnuSystemSave.setIcon(new ImageIcon(“hinh/save.png”));
mnuSystemSaveTextFile.setIcon(new ImageIcon(“hinh/textfile.png”));
mnuSystemSaveSerializeFile.setIcon(new ImageIcon(“hinh/serializefile.png”));
mnuSystemSaveXMLFile.setIcon(new ImageIcon(“hinh/xmlfile.png”));
mnuSystemSaveJSonFile.setIcon(new ImageIcon(“hinh/jsonfile.png”));

mnuSystemOpen.setIcon(new ImageIcon(“hinh/open.png”));
mnuSystemOpenTextFile.setIcon(new ImageIcon(“hinh/textfile.png”));
mnuSystemOpenSerializeFile.setIcon(new ImageIcon(“hinh/serializefile.png”));
mnuSystemOpenXMLFile.setIcon(new ImageIcon(“hinh/xmlfile.png”));
mnuSystemOpenJSonFile.setIcon(new ImageIcon(“hinh/jsonfile.png”));

mnuSystemExit.setIcon(new ImageIcon(“hinh/exit.png”));
}
}

[/code]

Khi bạn bổ sung xong các coding ở trên thì sẽ có được giao diện như Tui yêu cầu ở trên.

Bây giờ Ta xử lý Coding hướng đối tượng Kotlin cho Sản Phẩm (tạo class SanPham), và 4 loại tập tin (Tui sẽ viết mô hình lớp kế thừa dẫn xuất từ Interface).

Trước tiên bạn tạo một package tên là communityuni.com.model, có chứa Lớp Sản phẩm với cấu trúc như sau:

[code language=”groovy”]

package communityuni.com.model

import java.io.Serializable

/**
* Created by cafe on 04/06/2017.
*/
class SanPham:Serializable {
private var ma:String=””;
private var ten:String=””;
private var gia:Double=0.0;
constructor()
constructor(ma: String, ten: String, gia: Double) {
this.ma = ma
this.ten = ten
this.gia = gia
}
public var Ma:String
get() = ma
set(value) {ma=value}
public var Ten:String
get() = ten
set(value) {ten=value}
public var Gia:Double
get() = gia
set(value) {gia=value}
}
override fun toString(): String {
return “$ma\t$ten\t$gia”
}
[/code]

Để xử lý lưu và đọc tập tin ta tạo package communityuni.com.io, tạo một interface FileFactory bằng Kotlin như hình dưới đây:

[code language=”groovy”]

package communityuni.com.io

import communityuni.com.model.SanPham

/**
* Created by cafe on 04/06/2017.
*/
interface FileFactory {
/**
* @author Trần Duy Thanh
* @param data: Dữ liệu là Danh sách sản phẩm muốn lưu
* @param path: Đường dẫn lưu trữ
* @return true nếu lưu thành công, false nếu lưu thất bại
*/
fun LuuFile(database:MutableList,path:String):Boolean
/**
* @author Trần Duy Thanh
* @param path:đường dẫn muốn đọc dữ liệu
* @return Danh sách sản phẩm MutableList
*/
fun DocFile(path:String):MutableList
}

[/code]

Sau Đó bạn tạo 4 Lớp để xử lý 4 loại tập tin, các lớp này bạn đã được học ở các bài: Text File, Serialize File, XML file,JSon File.

Lớp TextFileFactory dẫn xuất từ Interface FileFactory ở trên để lưu và đọc TextFile:

Chú ý khi bạn cho dẫn xuất từ Interface thì như lý thuyết đã học, bạn phải Override toàn bộ phương thức trừu tượng trong Interface nhé (chỉ cần nhấn tổ hợp phím Alt+ Enter nó sẽ tự động làm giùm ta):

[code language=”groovy”]

package communityuni.com.io

import communityuni.com.model.SanPham
import java.io.*

/**
* Created by cafe on 04/06/2017.
*/
class TextFileFactory:FileFactory {
override fun LuuFile(database: MutableList, path: String): Boolean {
try {
val fos = FileOutputStream(path)
val osw = OutputStreamWriter(fos, “UTF-8”)
val bw = BufferedWriter(osw)
for (sp in database) {
bw.write(sp.toString());
bw.newLine();
}
bw.close();
osw.close();
fos.close();
return true
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return false
}

override fun DocFile(path: String): MutableList {
var data:MutableList = mutableListOf()
try {
val fis = FileInputStream(path)
val isr = InputStreamReader(fis, “UTF-8”)
val br = BufferedReader(isr)

var line = br.readLine()
while (line != null) {
var arr = line.split(“\t”)
if (arr.size == 3) {
var sp: SanPham = SanPham()
sp.Ma = arr[0]
sp.Ten = arr[1]
sp.Gia = arr[2].toDouble()
data.add(sp)
}
line = br.readLine()
}
br.close()
isr.close()
fis.close()
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return data
}
}

[/code]

Tương tự cho Serialize File:

[code language=”groovy”]

package communityuni.com.io
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import communityuni.com.model.SanPham

/**
* Created by cafe on 04/06/2017.
*/
class SerializeFileFactory : FileFactory{
override fun LuuFile(database: MutableList, path: String): Boolean {
try {
var fos=FileOutputStream(path);
var oos=ObjectOutputStream(fos);
oos.writeObject(database);
oos.close();
fos.close();
return true
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return false
}
override fun DocFile(path: String): MutableList {
var database:MutableList = mutableListOf()
try
{
var fis=FileInputStream(path);
var ois=ObjectInputStream(fis);
var obj=ois.readObject();
database= obj as MutableList;
ois.close();
fis.close();
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return database
}
}

[/code]

Tương tự với lớp Kotlin XML File:

[code language=”groovy”]

package communityuni.com.io

import communityuni.com.model.SanPham
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.TransformerFactory
import org.w3c.dom.Element
/**
* Created by cafe on 04/06/2017.
*/
class XMLFileFactory:FileFactory {
override fun LuuFile(database: MutableList, path: String): Boolean {
try
{
val docFactory = DocumentBuilderFactory.newInstance()
val docBuilder = docFactory.newDocumentBuilder()
// root elements
val doc = docBuilder.newDocument()
val rootElement = doc.createElement(“SanPhams”)
doc.appendChild(rootElement)
for(sp in database)
{
val sanPhamElement = doc.createElement(“SanPham”)
val maElement=doc.createElement(“Ma”)
maElement.textContent=sp.Ma
sanPhamElement.appendChild(maElement)
val tenElement=doc.createElement(“Ten”)
tenElement.textContent=sp.Ten
sanPhamElement.appendChild(tenElement)
val giaElement=doc.createElement(“Gia”)
giaElement.textContent=sp.Gia.toString()
sanPhamElement.appendChild(giaElement)
rootElement.appendChild(sanPhamElement);
}
// write the content into xml file
val transformerFactory = TransformerFactory.newInstance()
val transformer = transformerFactory.newTransformer()
val source = DOMSource(doc)

val result = StreamResult(File(path).absolutePath)

// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result)
return true
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return false
}

override fun DocFile(path: String): MutableList {
var database:MutableList = mutableListOf()
try {
//Get the DOM Builder Factory
val factory = DocumentBuilderFactory.newInstance()

//Get the DOM Builder
val builder = factory.newDocumentBuilder()

//Load and Parse the XML document
//document contains the complete XML as a Tree.
val xmlfile = File(path)

val document = builder.parse(xmlfile)

//Iterating through the nodes and extracting the data.
val nodeList = document.documentElement.childNodes

for (i in 0..nodeList.length – 1) {

//We have encountered an tag.
val node = nodeList.item(i)
if (node is Element) {
val sp = SanPham()
val childNodes = node.getChildNodes()
for (j in 0..childNodes.getLength() – 1) {
val cNode = childNodes.item(j)

//Identifying the child tag of employee encountered.
if (cNode is Element) {
val content = cNode.getLastChild().getTextContent().trim()
when (cNode.getNodeName()) {
“Ma” -> sp.Ma= content
“Ten” -> sp.Ten= content
“Gia” -> sp.Gia= content.toDouble()
}
}
}
database.add(sp)
}
}
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return database
}
}

[/code]

Cuối cùng tới lớp JSon File :

[code language=”groovy”]

package communityuni.com.io

import communityuni.com.model.SanPham
import com.google.gson.Gson
import java.io.FileWriter
import java.io.FileReader
import com.google.gson.reflect.TypeToken
/**
* Created by cafe on 04/06/2017.
*/
class JSonFileFactory:FileFactory {
override fun LuuFile(database: MutableList, path: String): Boolean {
try {
val gs= Gson()
val file=FileWriter(path)
gs.toJson(database,file)
file.close()
return true
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return false
}

override fun DocFile(path: String): MutableList {
var database:MutableList = mutableListOf()
try
{
val gson = Gson()
var file=FileReader(path)
database = gson.fromJson<MutableList>(file,
object : TypeToken<MutableList>()
{
}.type
)
file.close()
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return database
}
}

[/code]

Như vậy là bạn đã tạo xong các lớp mô hình, bây giờ ta tiến hành xử lý nghiệp vụ.

vào SanPhamPanel, bổ sung thêm đối tượng để lưu danh sách Sản phẩm, viết lại hàm thêm, hiển thị lên JTable cũng như hiển thị chi tiết:

Trong Lớp SanPhamPanel bổ sung biến:

[code language=”java”]

Listdatabase=new ArrayList();

[/code]

Sửa lại sự kiện thêm sản phẩm:

[code language=”java”]

btnLuu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Vectorvector=new Vector();
vector.add(txtMa.getText());
vector.add(txtTen.getText());
vector.add(txtDonGia.getText());
tableModelSanPham.addRow(vector);
//bổ sung thêm ở đây:
SanPham sp=new SanPham();
sp.setMa(txtMa.getText());
sp.setTen(txtTen.getText());
sp.setGia(Double.parseDouble(txtDonGia.getText()));
database.add(sp);
}
});

[/code]

Sửa lại đoạn lệnh cho sự kiện xóa:

[code language=”java”]

btnXoa.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(tblSanPham.getSelectedRow()>=0)
{
tableModelSanPham.removeRow(tblSanPham.getSelectedRow());
database.remove(tblSanPham.getSelectedRow());
}
}
});

[/code]

Bổ sung thêm hàm để hiển thị toàn bộ danh sách Sản phẩm từ biến database lên JTable:

[code language=”java”]

public void showDataOnJTable()
{
tableModelSanPham.setRowCount(0);
for(int i=0;i<database.size();i++)
{
SanPham sp=database.get(i);
Vectorvector=new Vector();
vector.add(sp.getMa());
vector.add(sp.getTen());
vector.add(sp.getGia()+””);
tableModelSanPham.addRow(vector);
}
}

[/code]

Vậy cuối cùng ta có cấu trúc coding của lớp SanPhamPanel này như sau:

[code language=”java”]

package communityuni.com.ui;

import communityuni.com.model.SanPham;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
* Created by cafe on 04/06/2017.
*/
public class SanPhamPanel {
private JPanel pnMain;
private JTable tblSanPham;
private DefaultTableModel tableModelSanPham;
private JButton btnLuu;
private JButton btnTiep;
private JButton btnXoa;
private JButton btnThoat;
private JTextField txtMa;
private JTextField txtTen;
private JTextField txtDonGia;

Listdatabase=new ArrayList();

public SanPhamPanel() {
btnTiep.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
txtMa.setText(“”);
txtTen.setText(“”);
txtDonGia.setText(“”);
txtMa.requestFocus();
}
});
btnThoat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnLuu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Vectorvector=new Vector();
vector.add(txtMa.getText());
vector.add(txtTen.getText());
vector.add(txtDonGia.getText());
tableModelSanPham.addRow(vector);
//bổ sung thêm ở đây:
SanPham sp=new SanPham();
sp.setMa(txtMa.getText());
sp.setTen(txtTen.getText());
sp.setGia(Double.parseDouble(txtDonGia.getText()));
database.add(sp);
}
});
tblSanPham.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
int row= tblSanPham.getSelectedRow();
String ma=tblSanPham.getValueAt(row,0).toString();
String ten=tblSanPham.getValueAt(row,1).toString();
double gia=Double.parseDouble(tblSanPham.getValueAt(row,2).toString());
txtMa.setText(ma);
txtTen.setText(ten);
txtDonGia.setText(gia+””);
}
});
tblSanPham.addMouseListener(new MouseAdapter() {
});
btnXoa.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(tblSanPham.getSelectedRow()>=0)
{
tableModelSanPham.removeRow(tblSanPham.getSelectedRow());
database.remove(tblSanPham.getSelectedRow());
}
}
});
createICon();
}
public void showDataOnJTable()
{
tableModelSanPham.setRowCount(0);
for(int i=0;i<database.size();i++)
{
SanPham sp=database.get(i);
Vectorvector=new Vector();
vector.add(sp.getMa());
vector.add(sp.getTen());
vector.add(sp.getGia()+””);
tableModelSanPham.addRow(vector);
}
}
private void createICon() {
btnLuu.setIcon(new ImageIcon(“hinh/add.png”));
btnTiep.setIcon(new ImageIcon(“hinh/clear.png”));
btnXoa.setIcon(new ImageIcon(“hinh/delete.png”));
btnThoat.setIcon(new ImageIcon(“hinh/exit.png”));
}

private void createUIComponents() {
tableModelSanPham=new DefaultTableModel();
tableModelSanPham.addColumn(“Mã Sản Phẩm”);
tableModelSanPham.addColumn(“Tên Sản Phẩm”);
tableModelSanPham.addColumn(“Đơn Giá Sản Phẩm”);
tblSanPham=new JTable(tableModelSanPham);
}
public JPanel getPnMain()
{
return pnMain;
}
}

[/code]

Bây giờ ta vào SanPhamUI để xử lý cho các Menu Lưu và đọc File, bổ sung thêm 2 biến cho FileFactory và JFileChooser, SanPhamPanel:

[code language=”java”]

FileFactory fileFactory;
JFileChooser fileChooser=new JFileChooser();
SanPhamPanel sanPhamPanel;

[/code]

Trong Constructor của SanPhamUI sửa lại chỗ setContentPane và gọi hàm createEvent(hàm này do ta tạo thêm để gán sự kiện cho các Menu):

[code language=”java”]

public SanPhamUI(String title)
{
super(title);
sanPhamPanel=new SanPhamPanel();
setContentPane(sanPhamPanel.getPnMain());
createMenu();
createICon();
creatEvent();
}

private void creatEvent() {
mnuSystemSaveTextFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây

}
});
}

[/code]

Coding chi tiết cho sự kiện lưu TextFile:

[code language=”java”]

private void creatEvent() {
mnuSystemSaveTextFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây
fileFactory=new TextFileFactory();
if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
boolean kq=fileFactory.LuuFile(sanPhamPanel.database,fileChooser.getSelectedFile().getAbsolutePath());
if(kq==true)
{
JOptionPane.showMessageDialog(null,”Lưu Text File thành công”);
}
else
{
JOptionPane.showMessageDialog(null,”Lưu Text File thất bại”);
}
}
}
});
}

[/code]

Tới đây ta chạy phần mềm lên để Test chức năng lưu Text File trước xem thành công hay không nhé:

Ta Vào Menu Lưu file/ chọn Save Text File:

Màn hình JFileChooser sẽ hiển thị ra như dưới đây:

Đặt tên file là databasesanpham.txt (tên gì kệ bạn), chọn nơi lưu trữ bất kỳ(kệ bạn). Rồi nhấn nút Save để xác thực lưu Text File, nếu ra cửa sổ thông báo sau là Lưu text file thành công:

Ta kiểm lại xem có đúng không nhé, vào nơi mà ta chọn lưu:

Rõ ràng là lưu Text File thành công, bây giờ ta tắt phần mềm và tiến hành viết lệnh đọc Text File:

[code language=”java”]

private void creatEvent() {
mnuSystemOpenTextFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileFactory=new TextFileFactory();
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
sanPhamPanel.database=fileFactory.DocFile(fileChooser.getSelectedFile().getAbsolutePath());
sanPhamPanel.showDataOnJTable();
}
}
});

}

[/code]

Chạy chương trình lên ta sẽ có giao diện trống rỗng như sau:

Vào menu Hệ thống / chọn Đọc File/ chọn Text File, cửa sổ chọn File xuất hiện:

Chọn đúng tập tin lúc nãy bạn lưu (databasesanpham.txt) rồi bấm Open, kết quả:

Như vậy chúng ta đã Đọc text file thành công, kết thúc công việc lưu file và đọc text file. Còn Serialize, XML, JSON hoàn toàn tương tự, Các bạn tự xử nhé.

và chú ý là không quan tâm lưu dữ liệu với loại định dạng nào, khi đã Nạp lên Bộ nhớ thì ta có thể xuất ra bất kỳ định dạng tập tin nào (4 loại).

Coding đầy đủ của SanPhamUI ở đây:

[code language=”java”]

package communityuni.com.ui;

import communityuni.com.io.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
* Created by cafe on 04/06/2017.
*/
public class SanPhamUI extends JFrame {
JMenuBar mnuBar;
JMenu mnuSystem;
JMenu mnuSystemSave;
JMenuItem mnuSystemSaveTextFile;
JMenuItem mnuSystemSaveSerializeFile;
JMenuItem mnuSystemSaveXMLFile;
JMenuItem mnuSystemSaveJSonFile;
JMenu mnuSystemOpen;
JMenuItem mnuSystemOpenTextFile;
JMenuItem mnuSystemOpenSerializeFile;
JMenuItem mnuSystemOpenXMLFile;
JMenuItem mnuSystemOpenJSonFile;
JMenuItem mnuSystemExit;

FileFactory fileFactory;
JFileChooser fileChooser=new JFileChooser();
SanPhamPanel sanPhamPanel;
public SanPhamUI(String title)
{
super(title);
sanPhamPanel=new SanPhamPanel();
setContentPane(sanPhamPanel.getPnMain());
createMenu();
createICon();
creatEvent();
}

private void creatEvent() {
mnuSystemOpenTextFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileFactory=new TextFileFactory();
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
sanPhamPanel.database=fileFactory.DocFile(fileChooser.getSelectedFile().getAbsolutePath());
sanPhamPanel.showDataOnJTable();
}
}
});
mnuSystemSaveTextFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây
fileFactory=new TextFileFactory();
if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
boolean kq=fileFactory.LuuFile(sanPhamPanel.database,fileChooser.getSelectedFile().getAbsolutePath());
if(kq==true)
{
JOptionPane.showMessageDialog(null,”Lưu Text File thành công”);
}
else
{
JOptionPane.showMessageDialog(null,”Lưu Text File thất bại”);
}
}
}
});

mnuSystemOpenSerializeFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileFactory=new SerializeFileFactory();
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
sanPhamPanel.database=fileFactory.DocFile(fileChooser.getSelectedFile().getAbsolutePath());
sanPhamPanel.showDataOnJTable();
}
}
});
mnuSystemSaveSerializeFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây
fileFactory=new SerializeFileFactory();
if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
boolean kq=fileFactory.LuuFile(sanPhamPanel.database,fileChooser.getSelectedFile().getAbsolutePath());
if(kq==true)
{
JOptionPane.showMessageDialog(null,”Lưu Serialize File thành công”);
}
else
{
JOptionPane.showMessageDialog(null,”Lưu Serialize File thất bại”);
}
}
}
});
mnuSystemOpenXMLFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileFactory=new XMLFileFactory();
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
sanPhamPanel.database=fileFactory.DocFile(fileChooser.getSelectedFile().getAbsolutePath());
sanPhamPanel.showDataOnJTable();
}
}
});
mnuSystemSaveXMLFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây
fileFactory=new XMLFileFactory();
if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
boolean kq=fileFactory.LuuFile(sanPhamPanel.database,fileChooser.getSelectedFile().getAbsolutePath());
if(kq==true)
{
JOptionPane.showMessageDialog(null,”Lưu XML File thành công”);
}
else
{
JOptionPane.showMessageDialog(null,”Lưu XML File thất bại”);
}
}
}
});
mnuSystemOpenJSonFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileFactory=new JSonFileFactory();
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
sanPhamPanel.database=fileFactory.DocFile(fileChooser.getSelectedFile().getAbsolutePath());
sanPhamPanel.showDataOnJTable();
}
}
});
mnuSystemSaveJSonFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//xử lý lưu TextFile ở đây
fileFactory=new JSonFileFactory();
if(fileChooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION)
{
boolean kq=fileFactory.LuuFile(sanPhamPanel.database,fileChooser.getSelectedFile().getAbsolutePath());
if(kq==true)
{
JOptionPane.showMessageDialog(null,”Lưu Json File thành công”);
}
else
{
JOptionPane.showMessageDialog(null,”Lưu JSon File thất bại”);
}
}
}
});
}

public void createMenu()
{
mnuBar=new JMenuBar();
setJMenuBar(mnuBar);
mnuSystem=new JMenu(“Hệ thống”);
mnuBar.add(mnuSystem);

mnuSystemSave=new JMenu(“Lưu file”);
mnuSystem.add(mnuSystemSave);
mnuSystemSaveTextFile=new JMenuItem(“Text file”);
mnuSystemSave.add(mnuSystemSaveTextFile);
mnuSystemSave.addSeparator();
mnuSystemSaveSerializeFile=new JMenuItem(“Serialize file”);
mnuSystemSave.add(mnuSystemSaveSerializeFile);
mnuSystemSave.addSeparator();
mnuSystemSaveXMLFile=new JMenuItem(“XML file”);
mnuSystemSave.add(mnuSystemSaveXMLFile);
mnuSystemSave.addSeparator();
mnuSystemSaveJSonFile=new JMenuItem(“JSON file”);
mnuSystemSave.add(mnuSystemSaveJSonFile);

mnuSystem.addSeparator();

mnuSystemOpen=new JMenu(“Đọc File”);
mnuSystem.add(mnuSystemOpen);
mnuSystemOpenTextFile=new JMenuItem(“Text file”);
mnuSystemOpen.add(mnuSystemOpenTextFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenSerializeFile=new JMenuItem(“Serialize file”);
mnuSystemOpen.add(mnuSystemOpenSerializeFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenXMLFile=new JMenuItem(“XML file”);
mnuSystemOpen.add(mnuSystemOpenXMLFile);
mnuSystemOpen.addSeparator();
mnuSystemOpenJSonFile=new JMenuItem(“JSON file”);
mnuSystemOpen.add(mnuSystemOpenJSonFile);

mnuSystem.addSeparator();

mnuSystemExit=new JMenuItem(“Thoát”);
mnuSystem.add(mnuSystemExit);
}
private void createICon() {
mnuSystem.setIcon(new ImageIcon(“hinh/system.png”));
mnuSystemSave.setIcon(new ImageIcon(“hinh/save.png”));
mnuSystemSaveTextFile.setIcon(new ImageIcon(“hinh/textfile.png”));
mnuSystemSaveSerializeFile.setIcon(new ImageIcon(“hinh/serializefile.png”));
mnuSystemSaveXMLFile.setIcon(new ImageIcon(“hinh/xmlfile.png”));
mnuSystemSaveJSonFile.setIcon(new ImageIcon(“hinh/jsonfile.png”));

mnuSystemOpen.setIcon(new ImageIcon(“hinh/open.png”));
mnuSystemOpenTextFile.setIcon(new ImageIcon(“hinh/textfile.png”));
mnuSystemOpenSerializeFile.setIcon(new ImageIcon(“hinh/serializefile.png”));
mnuSystemOpenXMLFile.setIcon(new ImageIcon(“hinh/xmlfile.png”));
mnuSystemOpenJSonFile.setIcon(new ImageIcon(“hinh/jsonfile.png”));

mnuSystemExit.setIcon(new ImageIcon(“hinh/exit.png”));
}
public void showWindow()
{
setSize(500,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
}

[/code]

So sánh định dạng dữ liệu kết quả 4 loại:

Như vậy Tui đã hướng dẫn xong toàn bộ phần mềm quản lý sản phẩm theo HƯỚNG ĐỐI TƯỢNG, thao tác với các control cơ bản và nâng của trong Kotlin. Kết xuất dữ liệu ra 4 loại tập tin, dễ dàng triệu gọi coding giữa Kotlin vs Java rất hay. Bài Sau Tui sẽ làm minh họa về JTree trong Kotlin, các bạn chú ý theo dõi nhé.

Các bạn có thể tải source code bài này ở đây: http://www.mediafire.com/file/1wbbj8tb05vtvqe/HocGUIPhan4.rar

Hẹn gặp các bạn ở những bài tiếp theo

Chúc các bạn thành công!

Trần Duy Thanh (http://communityuni.com/)