Cấp bậc tác giả:

TRAINING

JAVA - Tương tác giữa GUI với ActionListener, đồng thời xử lý dữ liệu

Được viết bởi webmaster ngày 15/07/2018 lúc 03:46 PM
Bài trước chúng ta đã làm quen Layout với Swing, về cơ bản đã nắm được một số giao diện chính để thực hiện yêu cầu bài toán. Bài tiếp theo này sẽ nâng cao khả năng tương tác giữa GUI với ActionListener, đồng thời giúp xử lý dữ liệu
  • 0
  • 4927

JAVA - Tương tác giữa GUI với ActionListener, đồng thời xử lý dữ liệu

Bài trước chúng ta đã làm quen Layout với Swing, về cơ bản đã nắm được một số giao diện chính để thực hiện yêu cầu bài toán. Bài tiếp theo này sẽ nâng cao khả năng tương tác giữa GUI với ActionListener, đồng thời giúp xử lý dữ liệu.
Xây dựng Ứng dụng
ActionListener-01.png 
Khi tìm kiếm dữ liệu sẽ ra kết quả bên dưới
 ActionListener-02.png
Khi nhấn hàng bất kỳ, có thể nhấn nút xóa
 ActionListener-03.png
Nhấn nút Exit sẽ thoát chương trình

Gợi ý làm bài

Viết xử lý cho nút “Search”
Bước 1: Khai báo tiêu đề và model cho Table
private String header[] = {"Id", "Title", "Price"};
private DefaultTableModel tblModel = new DefaultTableModel(header, 0);
Bước 2: Truy xuất dữ liệu của bảng Books
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String url = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(url);
String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017";
 conn = DriverManager.getConnection(db);
 // Câu lệnh xem dữ liệu
 String sql = "select * from Books ";

 // Nếu tìm kiếm theo title
 if (txtTitle.getText().length() > 0) {
   sql = sql + " where title like '%" + txtTitle.getText() + "%'";
 }

 // Tạo đối tượng thực thi câu lệnh Select
 st = conn.createStatement();

 // Thực thi 
 rs = st.executeQuery(sql);
 Vector data = null;

 tblModel.setRowCount(0);

 // Nếu sách không tồn tại
 if (rs.isBeforeFirst() == false) {
  JOptionPane.showMessageDialog(this, "The book is not available!");
  return;
 }

 // Trong khi chưa hết dữ liệu
 while (rs.next()) {
   data = new Vector();
   data.add(rs.getInt("id"));
   data.add(rs.getString("title"));
   data.add(rs.getString("price"));

   // Thêm một dòng vào table model
   tblModel.addRow(data);
 }

 jTable1.setModel(tblModel); // Thêm dữ liệu vào table
} catch (Exception e) {
  e.printStackTrace();
} finally {
  try {
    if (conn != null) {
      conn.close();
    }
    if (st != null) {
     st.close();
    }
    if (rs != null) {
     rs.close();
    }
   } catch (Exception ex) {
     ex.printStackTrace();
   }
}
Viết xử lý cho nút “Delete”
Trước khi xoá dữ liệu, người dùng phải chọn một dòng trên table và chương trình sẽ lấy giá trị của cột đầu tiên của dòng được chọn để làm điều kiện xoá (cột id)
int ret = JOptionPane.showConfirmDialog(this, "Do you want to delete?", "Confirm", JOptionPane.YES_NO_OPTION);
if(ret != JOptionPane.YES_OPTION) {
 return;
}

Connection c = null;
PreparedStatement ps = null;

String url = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(url);
String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017";
 c = DriverManager.getConnection(db);
 ps = c.prepareStatement("Delete From Books where id = ?");
 ps.setInt(1, id); //giá trị của cột đầu tiên tại dòng được chọn trong table
 ret = ps.executeUpdate();
 if (ret != -1) {
  JOptionPane.showMessageDialog(this, "This book has been deleted");  
 }
} catch (Exception ex) {
 ex.printStackTrace();
} finally {
  try {
   if (c != null) {
     c.close();
   }
   if (ps != null) {
     ps.close();
   }
 } catch (Exception ex2) {
   ex2.printStackTrace();
 }
}
Cập nhật tiêu đề và giá của sách dựa vào id
ActionListener-04.png 
Khi người dùng chọn id từ combobox, chương trình sẽ hiển thị thông tin của title và price tương ứng vào các textfield. Dữ liệu sẽ được cập nhật khi người dùng chọn nút “Save“
Viết xử lý hiển thị dữ liệu cho combobox
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String url = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(url);
String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017";
 conn = DriverManager.getConnection(db);
 st = conn.createStatement();
 rs = st.executeQuery("select id from books ");
 Vector data = new Vector();

 while (rs.next()) {
   data.add(rs.getString("id"));
 }

 cmbModel = new DefaultComboBoxModel(data);
 cmbCondition.setModel(cmbModel);

} catch (Exception e) {
 e.printStackTrace();
} finally {
 try {
   if (conn != null) {
     conn.close();
   }
  if (st != null) {
    st.close();
 }
  if (rs != null) {
    rs.close();
  }
 } catch (Exception ex) {
  ex.printStackTrace();
 }
}
Đăng ký và xử lý sự kiện cho combobox
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String url = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(url);
String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017";
 conn = DriverManager.getConnection(db);
 id = Integer.parseInt((String) cmbCondition.getSelectedItem());
 String sql = "Select * from books where id = ?";
 
 ps = conn.prepareStatement(sql); 
 ps.setInt(1, id);
 
 rs = ps.executeQuery();
 if (rs.next()) {
  //Hiển thị dữ liệu vào các textfield
  txtTitle.setText(rs.getString("title"));
  txtPrice.setText(rs.getString("price"));
 } 
} catch (Exception e) {
 e.printStackTrace();
} finally {
 try {
  if (conn != null) {
   conn.close();
  }
  
  if (rs != null) {
   rs.close();
  }

  if (ps != null) {
   ps.close();
  }
 } catch (Exception ex2) {
   ex2.printStackTrace();
 }
}
Viết xử lý cho nút “Save”
int ret = JOptionPane.showConfirmDialog(this, "Do you want to update?", "Confirm", JOptionPane.YES_NO_OPTION);
if (ret != JOptionPane.YES_OPTION) {
 return;
}

String update = "update books set title = ?, price = ? where id = ?";
System.out.println(update);

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String url = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(url);
String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017";
 conn = DriverManager.getConnection(db);
 ps = conn.prepareStatement(update);
 
 ps.setString(1, txtTitle.getText());
 ps.setFloat(2, Float.parseFloat(txtPrice.getText()));
 ps.setInt(3, id); //id được chọn từ combobox
 
 ret = ps.executeUpdate();
 if (ret != -1) {
   lblStatus.setText("The book has been updated");
 }
} catch (Exception e) {
 e.printStackTrace();
} finally {
 try {
  if (conn != null) {
   conn.close();
  }

  if(rs != null) {
   rs.close();
  }

  if (ps != null) {
   ps.close();
  }
 } catch (Exception ex2) {
  ex2.printStackTrace();
 }
}
Thêm dữ liệu
ActionListener-05.png 
Xử lý cho nút “Save”
// Nếu không nhập tiêu đề (Title)
if (txtTitle.getText().isEmpty()) {
 JOptionPane.showMessageDialog(this, "Please input title");
 txtTitle.requestFocus();
 return; // Thoát khỏi xử lý không thực hiện các lệnh tiếp theo
}

 // Nếu không nhập giá (Price)
if (txtPrice.getText().isEmpty()) {
 JOptionPane.showMessageDialog(this, "Please input price");
 txtPrice.requestFocus();
 return;
}

 // Hiển thị hộp thoại xác nhận có muốn lưu hay không?
 int ret = JOptionPane.showConfirmDialog(this, "Do you want to save?", "Confirm", JOptionPane.YES_NO_OPTION);
 
 // Trường hợp không lưu
 if (ret != JOptionPane.YES_OPTION) {
 return; // Thoát khỏi phương thức
 }
 
 // Câu lệnh insert
 String insert = "insert into books (title,price) values(?, ?)";
 System.out.println(insert);
 
 Connection conn = null;
 PreparedStatement ps = null;
String url = "net.sourceforge.jtds.jdbc.Driver";
        try {
            Class.forName(url);
            String db = "jdbc:jtds:sqlserver://DOTNETGROUP:1433/Bank2017"; 
conn = DriverManager.getConnection(db);  
ps = conn.prepareStatement(insert);
  ps.setString(1, txtTitle.getText());
  ps.setFloat(2, Float.parseFloat(txtPrice.getText()));

  // Thực thi câu lệnh insert
  ret = ps.executeUpdate();

  if (ret != -1) {
    lblStatus.setText("The book has been inserted");
  }
 } catch (Exception e) {
   e.printStackTrace();
 } finally {
   try {
    if (conn != null) {
     conn.close();
    }

    if (ps != null) {
     ps.close();
    }
   } catch (Exception ex2) {
    ex2.printStackTrace();
   }
}

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML