Objective
This toturiel will help you to dynamically use a list of JButton in a JTable. The case study is a modul of searching client to edit the information about a client.
Assume that we have a table in the database which contains the information about clients as follow:
And at the interface level, the search form and its results is shown as a table of clients whose name contains the entered keyword: each row of the table represents the information of a client. The last two columns are two button to 'edit' or 'delete' the corresponding client.
If we click on an 'edit' button, a subform of editClient appears and presents the information of the selected client to edit. After update, the informaion of the updated client will be automatically updated in the table of search result.
Design
Static design
This modul is designed in the architect of classical MVC model:
- At the level of model, we have only one class: Client
- At the level of control, we have only one class: ClientDAO
- At the level of view, we need two main classes: SearchClientFrm, EditClientFrm
The control class, ClientDAO, has three main functions:
- ArrayList<Client> searchClient(String key): search in the tblClient all client whose name contains the @key.
- void editClient(Client client): update information of the @client, except its @id
- void deleteClient(int id): delete the client from tblClient in the DB whose id is @id
Note that in this class, you have to modify the following code based on your database and your JDBC (text in red are sujected to modify):
public ClientDAO(){
if(con == null){
String dbUrl = "jdbc:mysql://localhost:3306/hotel";
String dbClass = "com.mysql.jdbc.Driver";
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, "root", "12345678");
}catch(Exception e) {
e.printStackTrace();
}
}
}
At the view level, the class of searchClientFrm has three explicite view objects:
- txtKey: to receive the entered keyword to search
- btnSearch: to search the clients who satisfy the search filter
- tblResult: to represent the search result
And three implicit view attributes:
- listClient: to represent the search result
- listEdit: to dynamically represent the list of edit button in the table
- listDelete: to dynamically representthe list of delete button in the table
The EditClientFrm has 5 text field attributes to represent 5 editable attribute of a client: name, address, tel, email, note; and two buttons: update and reset.
Dynamic design
The scenario of this modul is follow:
- The user enters a keyword and clicks on the search button on the SearchClientFrm.
- The method actionperformed() of this class is triggered: it detects that the search button is clicked, so it calls the method btnSearchClick().
- The method btnSearchClick() calls and passes the keyword to the method searchClient() of the clientDAO class.
- The method searchClient() searches all clients whose name contains the keyword. Then, calls the method new and setter of the entity class Client to encapsulate the object of Client to return to the btnSearchClick().
- The btnSearchClick() method update the listClient, listEdit, and listDelete into the result table and then, displays the form to the user.
- The user clicks on an edit button in the table.
- The actionperformed() method is invoked one more time, its detects that an edit button is clicked, then its call the function btnEditClick().
- The btnEditClick() calls and passes the parameters to the class EditClientFrm.
- The class EditClientFrm receives input parameter and displays them in the form to the user
- The user modifies some attributs and clicks on Update button
- The method actionperformed() of the class EditClientFRm is invoked. It detects that the btnUpdate button is clicked, then it calls the method btnUpdateClick().
- This method calls the setter method of the entity class Client to enveloppe the object and passes it to the method editClient() of control class ClientDAO.
- The control class executes the function ecditClient() and return to the btnUpdateClick().
- This method call the method refrehResultAfterUpdate() of the class SearchClientFrm to automatically refresh the result table
- After refreshing the result table, the SearchClientFrm shows the form to the user.
Implementation
Client.java
import java.io.Serializable;
public class Client implements Serializable{
private static final long serialVersionUID = 2018040801L;
private int id;
private String name;
private String address;
private String tel;
private String email;
private String note;
public Client() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
ClientDAO.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class ClientDAO {
private static Connection con;
public ClientDAO(){
if(con == null){
String dbUrl = "jdbc:mysql://localhost:3306/hotel";
String dbClass = "com.mysql.jdbc.Driver";
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, "root", "12345678");
}catch(Exception e) {
e.printStackTrace();
}
}
}
/**
* search all clients in the tblClient whose name contains the @key
* @param key
* @return list of client whose name contains the @key
*/
public ArrayList<Client> searchClient(String key){
ArrayList<Client> result = new ArrayList<Client>();
String sql = "SELECT * FROM tblClient WHERE name LIKE ?";
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "%" + key + "%");
ResultSet rs = ps.executeQuery();
while(rs.next()){
Client client = new Client();
client.setId(rs.getInt("id"));
client.setName(rs.getString("name"));
client.setAddress(rs.getString("address"));
client.setTel(rs.getString("tel"));
client.setEmail(rs.getString("email"));
client.setNote(rs.getString("note"));
result.add(client);
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* update the @client
* @param client
*/
public void editClient(Client client){
String sql = "UPDATE tblClient SET name=?, address=?, tel=?, email=?, note=? WHERE id=?";
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, client.getName());
ps.setString(2, client.getAddress());
ps.setString(3, client.getTel());
ps.setString(4, client.getEmail());
ps.setString(5, client.getNote());
ps.setInt(6, client.getId());
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* delete the client whose id is @id
* @param id
*/
public void deleteClient(int id){
String sql = "DELETE FROM tblClient WHERE id=?";
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
}
SearchClientFrm.java
import java.awt.Component;
import java.awt.Dimension;
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 javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class SearchClientFrm extends JFrame implements ActionListener{
private ArrayList<Client> listClient;
private ArrayList<JButton> listEdit, listDelete;
private JTextField txtKey;
private JButton btnSearch;
private JTable tblResult;
public SearchClientFrm(){
super("Search Client Demo");
listClient = new ArrayList<Client>();
listEdit = new ArrayList<JButton>();
listDelete = new ArrayList<JButton>();
JPanel pnMain = new JPanel();
pnMain.setSize(this.getSize().width-5, this.getSize().height-20);
pnMain.setLayout(new BoxLayout(pnMain,BoxLayout.Y_AXIS));
JPanel pn1 = new JPanel();
pn1.setLayout(new BoxLayout(pn1,BoxLayout.X_AXIS));
pn1.setSize(this.getSize().width-5, 20);
pn1.add(new JLabel("Keyword: "));
txtKey = new JTextField();
pn1.add(txtKey);
btnSearch = new JButton("Search");
btnSearch.addActionListener(this);
pn1.add(btnSearch);
pnMain.add(pn1);
JPanel pn2 = new JPanel();
pn2.setLayout(new BoxLayout(pn2,BoxLayout.Y_AXIS));
tblResult = new JTable(new ClientTableModel());
JScrollPane scrollPane= new JScrollPane(tblResult);
tblResult.setFillsViewportHeight(false);
scrollPane.setPreferredSize(new Dimension(scrollPane.getPreferredSize().width, 250));
TableCellRenderer buttonRenderer = new JTableButtonRenderer();
tblResult.getColumn("Edit").setCellRenderer(buttonRenderer);
tblResult.getColumn("Delete").setCellRenderer(buttonRenderer);
tblResult.addMouseListener(new JTableButtonMouseListener(tblResult));
pn2.add(scrollPane);
pnMain.add(pn2);
this.add(pnMain);
pnMain.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton btnClicked = (JButton)e.getSource();
if(btnClicked.equals(btnSearch)){
btnSearchClick();
return;
}
for(int i=0; i<listEdit.size(); i++)
if(btnClicked.equals(listEdit.get(i))){
btnEditClick(i);
return;
}
for(int i=0; i<listDelete.size(); i++)
if(btnClicked.equals(listDelete.get(i))){
btnDeleteClick(i);
return;
}
}
/**
* processing the event that the Search button is clicked
*/
private void btnSearchClick(){
if((txtKey.getText() == null)||(txtKey.getText().length() == 0))
return;
ClientDAO clientDAO = new ClientDAO();
listClient = clientDAO.searchClient(txtKey.getText().trim());
listEdit.clear();
listDelete.clear();
for(int i=0; i<listClient.size(); i++){
JButton btn = new JButton("Edit");
btn.addActionListener(this);
listEdit.add(btn);
btn = new JButton("Delete");
btn.addActionListener(this);
listDelete.add(btn);
}
((DefaultTableModel)tblResult.getModel()).fireTableDataChanged();
}
/**
* processing the event that the @index Edit button is clicked
* @param index
*/
private void btnEditClick(int index){
(new EditClientFrm(this, listClient.get(index), index)).setVisible(true);
}
/**
* enable to refresh the result table after update a client from @Update form
* @index: the index of updated client in the list
* @Client: the updated client
*/
public void refreshResultAfterUpdate(int index, Client client){
listClient.remove(index);
listClient.add(index, client);
((DefaultTableModel)tblResult.getModel()).fireTableDataChanged();
}
/**
* processing the event that the @index Delete button is clicked
* @param index
*/
private void btnDeleteClick(int index){
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog (this, "Would you like to delete this client?", "Warning", dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
ClientDAO clientDAO = new ClientDAO();
clientDAO.deleteClient(listClient.get(index).getId());
listClient.remove(index);
listEdit.remove(index);
listDelete.remove(index);
}
((DefaultTableModel)tblResult.getModel()).fireTableDataChanged();
}
class ClientTableModel extends DefaultTableModel {
private String[] columnNames = {"Id", "Name", "Address", "Tel", "Email", "Note", "Edit", "Delete"};
private final Class<?>[] columnTypes = new Class<?>[] {Integer.class, String.class, String.class, String.class,
String.class, String.class, JButton.class, JButton.class};
@Override public int getColumnCount() {
return columnNames.length;
}
@Override public int getRowCount() {
return listClient.size();
}
@Override public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override public Class<?> getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
@Override public Object getValueAt(final int rowIndex, final int columnIndex) {
/*Adding components*/
switch (columnIndex) {
case 0:
return listClient.get(rowIndex).getId();
case 1:
return listClient.get(rowIndex).getName();
case 2:
return listClient.get(rowIndex).getAddress();
case 3:
return listClient.get(rowIndex).getTel();
case 4:
return listClient.get(rowIndex).getEmail();
case 5:
return listClient.get(rowIndex).getNote();
case 6:
return listEdit.get(rowIndex);
case 7:
return listDelete.get(rowIndex);
default: return "Error";
}
}
}
class JTableButtonMouseListener extends MouseAdapter {
private final JTable table;
public JTableButtonMouseListener(JTable table) {
this.table = table;
}
public void mouseClicked(MouseEvent e) {
int column = table.getColumnModel().getColumnIndexAtX(e.getX()); // get the coloum of the button
int row = e.getY()/table.getRowHeight(); //get the row of the button
//*Checking the row or column is valid or not
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
if (value instanceof JButton) {
//perform a click event
((JButton)value).doClick();
}
}
}
}
class JTableButtonRenderer implements TableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JButton button = (JButton)value;
return button;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SearchClientFrm myFrame = new SearchClientFrm();
myFrame.setSize(600,300);
myFrame.setVisible(true);
myFrame.setLocation(200,10);
}
}
EditClientFrm.java
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EditClientFrm extends JFrame implements ActionListener{
private SearchClientFrm parent;
private Client client;
private int index;
private JTextField txtId, txtName, txtAddress, txtTel, txtEmail, txtNote;
private JButton btnUpdate, btnReset;
public EditClientFrm(SearchClientFrm parent, Client client, int index){
super("Edit a client");
this.parent = parent;
this.client = client;
this.index = index;
txtId = new JTextField(15);
txtId.setEditable(false);
txtName = new JTextField(15);
txtAddress = new JTextField(15);
txtTel = new JTextField(15);
txtEmail = new JTextField(15);
txtNote = new JTextField(15);
btnUpdate = new JButton("Update");
btnReset = new JButton("Reset");
JPanel content = new JPanel();
content.setLayout(new GridLayout(7,2));
content.add(new JLabel("ID:")); content.add(txtId);
content.add(new JLabel("Name:")); content.add(txtName);
content.add(new JLabel("Address:")); content.add(txtAddress);
content.add(new JLabel("Tel:")); content.add(txtTel);
content.add(new JLabel("Email:")); content.add(txtEmail);
content.add(new JLabel("Note:")); content.add(txtNote);
content.add(btnUpdate); content.add(btnReset);
btnUpdate.addActionListener(this);
btnReset.addActionListener(this);
initForm();
this.setContentPane(content);
this.pack();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initForm(){
if(client != null){
txtId.setText(client.getId()+"");
txtName.setText(client.getName());
txtAddress.setText(client.getAddress());
txtTel.setText(client.getTel());
txtEmail.setText(client.getEmail());
txtNote.setText(client.getNote());
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton btnClicked = (JButton)e.getSource();
if(btnClicked.equals(btnReset)){
initForm();
return;
}
if(btnClicked.equals(btnUpdate)){
btnUpdateClick();
}
}
private void btnUpdateClick(){
client.setName(txtName.getText());
client.setAddress(txtAddress.getText());
client.setTel(txtTel.getText());
client.setEmail(txtEmail.getText());
client.setNote(txtNote.getText());
ClientDAO clientDAO = new ClientDAO();
clientDAO.editClient(client);
parent.refreshResultAfterUpdate(index, client);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
Coder and Code
Dears,
This blog is moved to a new blog at:
The new update will be found at that new blog, please follow it!
This blog is no more updated.
Thanks for your visit!
Sunday, April 8, 2018
Tuesday, February 11, 2014
Variations of the MVC model
Objective
This post will introduce some variations of MVC model which are popularly used in the reality. Particularly, we will consider and discuss about: MVC model using bean entity, MVC model using pure entity, and strictly MVC model.Demonstration example
We will use a desktop application of hotel reservation management whose users are hotel employees such as receptionist, seller, manager, and system admin. We consider the module of room management: add, edit, and delete hotel room's information.Assume that we have a table named as tblRoom in the database (named hotel) with these attributes:
- id: room id
- name: room name
- type: type of room, e.g. single, double, tween
- displayPrice: the current price of the room, this could changed by tourist season
- description: some additional description about the room, such as garden or see view...
Objective is to create a module which enable to add a new room into this database, with respecting the MVC model. We will design and code this module with three variations of MVC model:
- MVC with bean entity
- MVC with pure entity
- Strictly MVC model
MVC with bean entity
The main feature of this variation is to use bean entity which contains all entity attributes and database access methods (bean entity = pure entity + DAO). This means that bean entity class play the role of both pure entity class and control class. Consequently, in some simple application like this, we do not need any more the control class.That's why this variation remains only two classes:
- RoomBean: bean entity class of room
- AddRoomFrm: view class for add new room function.
And the order of activities is the follow:
1. A hotel room manager enters the room information into the form of AddRoomFrm class and clicks on the "Add Room" button
2. The button clicked event processing method of AddRoomFrm is triggered, it calls the addRoom() method of RoomBean class to save the entered info into the DB.
3. The RoomBean class run the called method
4. The success is returned to the AddRoomFrm class
5. The AddRoomFrm class displays the success message on the form to the manager.
Class RoomBean.java
package mvcBean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class RoomBean {
private String id;
private String name;
private String type;
private float displayPrice;
private String description;
public RoomBean() {
super();
}
public RoomBean(String id, String name, String type, float displayPrice,
String description) {
super();
this.id = id;
this.name = name;
this.type = type;
this.displayPrice = displayPrice;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getDisplayPrice() {
return displayPrice;
}
public void setDisplayPrice(float displayPrice) {
this.displayPrice = displayPrice;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void addRoom(){
String dbUrl = "jdbc:mysql://localhost:3306/hotel";
String dbClass = "com.mysql.jdbc.Driver";
String sql = "INSERT INTO tblRoom(id, name, type, displayPrice, description) VALUES(?,?,?,?,?)";
try{
Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl, "root", "12345678");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, getId());
ps.setString(2, getName());
ps.setString(3, getType());
ps.setFloat(4, getDisplayPrice());
ps.setString(5, getDescription());
ps.executeUpdate();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Class AddRoomFrm.java
package mvcBean;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddRoomFrm extends JFrame implements ActionListener{
private JTextField txtID;
private JTextField txtName;
private JTextField txtType;
private JTextField txtDisplayPrice;
private JTextField txtDescription;
private JButton btnSubmit;
private JButton btnReset;
public AddRoomFrm(){
super("Room management pure-MVC");
txtID = new JTextField(15);
txtName = new JTextField(15);
txtType = new JTextField(15);
txtDisplayPrice = new JTextField(15);
txtDescription = new JTextField(15);
btnSubmit = new JButton("Submit");
btnReset = new JButton("Reset");
JPanel content = new JPanel();
content.setLayout(new GridLayout(6,2));
content.add(new JLabel("ID:")); content.add(txtID);
content.add(new JLabel("Name:")); content.add(txtName);
content.add(new JLabel("Type:")); content.add(txtType);
content.add(new JLabel("Display price:")); content.add(txtDisplayPrice);
content.add(new JLabel("Description:")); content.add(txtDescription);
content.add(btnReset); content.add(btnSubmit);
btnSubmit.addActionListener(this);
btnReset.addActionListener(this);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if(btn.equals(btnSubmit)){
btnSubmit_actionperformed();
}else if(btn.equals(btnReset)){
btnReset_actionperformed();
}
}
public void btnSubmit_actionperformed() {
RoomBean room = new RoomBean();
room.setId(txtID.getText());
room.setName(txtName.getText());
room.setType(txtType.getText());
room.setDisplayPrice(Float.parseFloat(txtDisplayPrice.getText()));
room.setDescription(txtDescription.getText());
room.addRoom();
JOptionPane.showMessageDialog(this, "Add room successfullly!");
}
public void btnReset_actionperformed() {
txtID.setText("");
txtName.setText("");
txtType.setText("");
txtDisplayPrice.setText("");
txtDescription.setText("");
}
}
Class Test.java
package mvcBean;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AddRoomFrm arf = new AddRoomFrm();
arf.setVisible(true);
}
}
MVC with pure entity
This is the standard variation of MVC model with three classes: model (pure model - the model class has only attributes as getter/setter methods), view, and control. In this variation, the control class plays the role of a data access object (DAO).So, in our example, we have three classes:
- Room: pure entity of room
- AddRoomFrm: view class
- RoomDAO: control class with the role of DAO class
And the order of activities is the follow:
1. A hotel room manager enters the room information into the form of AddRoomFrm class and clicks on the "Add Room" button
2. The button clicked event processing method of AddRoomFrm is triggered, it calls the method(s) of Room class to create an entity object of room.
3. The Room class returns the object to the view class.
4. The view class calls the addRoom() method of RoomDAO class to save the entered info which is already packaged in an entity object of room into the DB.
5. The RoomDAO class run the called method
6. The success is returned to the AddRoomFrm class
7. The AddRoomFrm class displays the success message on the form to the manager.
Class Room.java
package mvcPure;
public class Room {
private String id;
private String name;
private String type;
private float displayPrice;
private String description;
public Room() {
super();
}
public Room(String id, String name, String type, float displayPrice,
String description) {
super();
this.id = id;
this.name = name;
this.type = type;
this.displayPrice = displayPrice;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getDisplayPrice() {
return displayPrice;
}
public void setDisplayPrice(float displayPrice) {
this.displayPrice = displayPrice;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Class RoomDAO.java
package mvcPure;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class RoomDAO {
private Connection con;
public RoomDAO(){
String dbUrl = "jdbc:mysql://localhost:3306/hotel";
String dbClass = "com.mysql.jdbc.Driver";
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, "root", "12345678");
}catch(Exception e) {
e.printStackTrace();
}
}
public void addRoom(Room room){
String sql = "INSERT INTO tblRoom(id, name, type, displayPrice, description) VALUES(?,?,?,?,?)";
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, room.getId());
ps.setString(2, room.getName());
ps.setString(3, room.getType());
ps.setFloat(4, room.getDisplayPrice());
ps.setString(5, room.getDescription());
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
}
Class AddRoomFrm.java
package mvcPure;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddRoomFrm extends JFrame implements ActionListener{
private JTextField txtID;
private JTextField txtName;
private JTextField txtType;
private JTextField txtDisplayPrice;
private JTextField txtDescription;
private JButton btnSubmit;
private JButton btnReset;
public AddRoomFrm(){
super("Room management pure-MVC");
txtID = new JTextField(15);
txtName = new JTextField(15);
txtType = new JTextField(15);
txtDisplayPrice = new JTextField(15);
txtDescription = new JTextField(15);
btnSubmit = new JButton("Submit");
btnReset = new JButton("Reset");
JPanel content = new JPanel();
content.setLayout(new GridLayout(6,2));
content.add(new JLabel("ID:")); content.add(txtID);
content.add(new JLabel("Name:")); content.add(txtName);
content.add(new JLabel("Type:")); content.add(txtType);
content.add(new JLabel("Display price:")); content.add(txtDisplayPrice);
content.add(new JLabel("Description:")); content.add(txtDescription);
content.add(btnReset); content.add(btnSubmit);
btnSubmit.addActionListener(this);
btnReset.addActionListener(this);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if(btn.equals(btnSubmit)){
btnSubmit_actionperformed();
}else if(btn.equals(btnReset)){
btnReset_actionperformed();
}
}
public void btnSubmit_actionperformed() {
Room room = new Room();
room.setId(txtID.getText());
room.setName(txtName.getText());
room.setType(txtType.getText());
room.setDisplayPrice(Float.parseFloat(txtDisplayPrice.getText()));
room.setDescription(txtDescription.getText());
RoomDAO rd = new RoomDAO();
rd.addRoom(room);
JOptionPane.showMessageDialog(this, "Add room successfullly!");
}
public void btnReset_actionperformed() {
txtID.setText("");
txtName.setText("");
txtType.setText("");
txtDisplayPrice.setText("");
txtDescription.setText("");
}
}
Class Test.java
package mvcPure;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AddRoomFrm arf = new AddRoomFrm();
arf.setVisible(true);
}
}
Strictly MVC model
In this variation, the control class is the King: it has all control rights, from the right to treat the button click event in the view form to the one to control the database access. That why the control class has some inner classes for this purpose (see more on this variation at the post: mvc-model-example-with-login-application.html).So we have four classes in total:
- Room: pure entity of room
- AddRoomFrm: view class
- RoomControl: the King control class
- AddRoomListener: an inner class of the control class to process the Add room button click event.(This class is difined inside the class of control)
And thus the order of activities is the follow:
1. A hotel room manager enters the room information into the form of AddRoomFrm class and clicks on the "Add Room" button
2. The button clicked event triggers the event processing method of the inner class AddRoomListener, it calls the get Room() method of the view class to get information entered from the form.
3. The getRoom() of the view class is executed
4. It calls the method(s) of Room class to create an entity object of room.
5. The Room class returns the object to the view class.
6. The view class returns the packaged object to the inner class.
7. The inner class calls the addRoom() method of RoomControl class to save the entered info which is already packaged in an entity object of room into the DB.
8. The RoomCotrol class run the called method
9. The success is returned to the inner class
10. The inner class calls displayMessage() method of the view class to display the success message
11. The AddRoomFrm class displays the success message on the form to the manager.
Class Room.java
package mvcNew;
public class Room {
private String id;
private String name;
private String type;
private float displayPrice;
private String description;
public Room() {
super();
}
public Room(String id, String name, String type, float displayPrice,
String description) {
super();
this.id = id;
this.name = name;
this.type = type;
this.displayPrice = displayPrice;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getDisplayPrice() {
return displayPrice;
}
public void setDisplayPrice(float displayPrice) {
this.displayPrice = displayPrice;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Class AddRoomFrm.java
package mvcNew;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddRoomFrm extends JFrame implements ActionListener{
private JTextField txtID;
private JTextField txtName;
private JTextField txtType;
private JTextField txtDisplayPrice;
private JTextField txtDescription;
private JButton btnSubmit;
private JButton btnReset;
public AddRoomFrm(){
super("Room management pure-MVC");
txtID = new JTextField(15);
txtName = new JTextField(15);
txtType = new JTextField(15);
txtDisplayPrice = new JTextField(15);
txtDescription = new JTextField(15);
btnSubmit = new JButton("Submit");
btnReset = new JButton("Reset");
JPanel content = new JPanel();
content.setLayout(new GridLayout(6,2));
content.add(new JLabel("ID:")); content.add(txtID);
content.add(new JLabel("Name:")); content.add(txtName);
content.add(new JLabel("Type:")); content.add(txtType);
content.add(new JLabel("Display price:")); content.add(txtDisplayPrice);
content.add(new JLabel("Description:")); content.add(txtDescription);
content.add(btnReset); content.add(btnSubmit);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public Room getRoom(){
Room room = new Room();
room.setId(txtID.getText());
room.setName(txtName.getText());
room.setType(txtType.getText());
room.setDisplayPrice(Float.parseFloat(txtDisplayPrice.getText()));
room.setDescription(txtDescription.getText());
return room;
}
public void showMessage(String msg){
JOptionPane.showMessageDialog(this, msg);
}
public void addSubmitListener(ActionListener log) {
btnSubmit.addActionListener(log);
}
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if(btn.equals(btnReset)){
btnReset_actionperformed();
}
}
public void btnReset_actionperformed() {
txtID.setText("");
txtName.setText("");
txtType.setText("");
txtDisplayPrice.setText("");
txtDescription.setText("");
}
}
Class RoomControl.java
package mvcNew;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class RoomControl {
private Connection con;
private Room room;
private AddRoomFrm arf;
public RoomControl(){
String dbUrl = "jdbc:mysql://localhost:3306/hotel";
String dbClass = "com.mysql.jdbc.Driver";
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, "root", "12345678");
}catch(Exception e) {
e.printStackTrace();
}
arf = new AddRoomFrm();
arf.addSubmitListener(new AddRoomListener());
arf.setVisible(true);
}
public void addRoom(Room room){
String sql = "INSERT INTO tblRoom(id, name, type, displayPrice, description) VALUES(?,?,?,?,?)";
try{
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, room.getId());
ps.setString(2, room.getName());
ps.setString(3, room.getType());
ps.setFloat(4, room.getDisplayPrice());
ps.setString(5, room.getDescription());
ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
class AddRoomListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
room = arf.getRoom();
addRoom(room);
arf.showMessage("Add room successfullly!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Class Test.java
package mvcNew;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
RoomControl rc = new RoomControl();
}
}
Labels:
JDBC,
MVC,
MySQL,
SQL language
Subscribe to:
Posts (Atom)