Sql

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

Sql :

package javanangcao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class bai15_2 extends JFrame{

public static void main(String[] args) {


JFrame frame = new JFrame("DANH SÁCH SINH VIÊN");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLayout(new BorderLayout());

// Table model
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);

tableModel.addColumn("MSSV");
tableModel.addColumn("HoTen");
tableModel.addColumn("NamSinh");

try {
Class.forName("com.mysql.cj.jdbc.Driver");
String dbUrl = "jdbc:mysql://localhost:3306/qlhv";
Connection con = DriverManager.getConnection(dbUrl, "root", "");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM qlhv");
while(rs.next())
{
String mssv = rs.getString("mssv");
String hoten = rs.getString("hoten");
String namsinh = rs.getString("namsinh");
tableModel.addRow(new Object[]{mssv, hoten, namsinh});
}
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
//System.out.println("Kết nối thành công");
} catch (Exception e) {
System.out.println("Kết nối thất bại: " + e.getMessage());
}
frame.setVisible(true);
}

Sqlsever
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.sql.ResultSet;

public class MySQLConnection {

// Thông tin kết nối cơ sở dữ liệu

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/ten_database";

private static final String JDBC_USER = "ten_nguoi_dung";

private static final String JDBC_PASSWORD = "mat_khau";

public static void main(String[] args) {

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;


try {

// Tạo kết nối tới cơ sở dữ liệu

connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);

System.out.println("Kết nối thành công!");

// Tạo statement để thực thi câu lệnh SQL

statement = connection.createStatement();

// Thực thi câu lệnh SQL SELECT

String sql = "SELECT * FROM ten_bang";

resultSet = statement.executeQuery(sql);

// Duyệt qua kết quả và in ra

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

System.out.println("ID: " + id + ", Name: " + name);

} catch (SQLException e) {

e.printStackTrace();

} finally {

// Đóng các tài nguyên để tránh rò rỉ

try {

if (resultSet != null) {

resultSet.close();

if (statement != null) {

statement.close();

}
if (connection != null) {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

Vd2:
package javanangcao;
import java.sql.*;
public class bai15{
protected static Connection con;
public static void main(String args[]){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url
="jdbc:sqlserver://localhost:1433;databaseName=qlsv;encrypt=true;trustServerCertificate=true";
String username = "long"; String password= "123456789";
con=DriverManager.getConnection(url, username, password);
Statement stmt =con.createStatement();
ResultSet rs =stmt.executeQuery("SELECT * FROM sinhvien");
while(rs.next()) {
System.out.println(rs.getString("mssv")+"\t");
System.out.println(rs.getString("hoten")+"\t");
System.out.println(rs.getString("tuoi")+"\t");
System.out.println();
}
if(rs !=null) rs.close();
if(stmt !=null)stmt.close();
if(con !=null)con.close();
System.out.println("ket noi thanh cong");
} catch(Exception loi){
System.out.println("loi"+loi.getMessage());
loi.printStackTrace();
}
}}

Them xoa su ds sinh vien :

package chuong4;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;
import java.sql.Statement;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class capnhatsinhvien extends JFrame{

protected static Connection con;

public static void main(String[] args) {

// tạo giao diện thêm xóa sửa

JFrame frame = new JFrame("CẬP NHẬT SINH VIÊN");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(600, 400);

frame.setLayout(new BorderLayout());

JButton btthem=new JButton("Thêm");

JButton btsua=new JButton("Sửa");

JButton btxoa=new JButton("Xóa");

JLabel lbmssv=new JLabel("Mssv");

JLabel lbhoten=new JLabel("Họ tên");

JLabel lbbamsinh=new JLabel("Năm sinh");

JTextField jmssv=new JTextField();

JTextField jhoten=new JTextField();

JTextField jnamsinh=new JTextField();

JPanel panel = new JPanel();

frame.getContentPane().add(panel);

panel.setLayout(new GridLayout(5, 2, 10, 10));

panel.add(lbmssv); panel.add(jmssv);

panel.add(lbhoten); panel.add(jhoten);

panel.add(lbbamsinh); panel.add(jnamsinh);

panel.add(btthem); panel.add(btsua);
panel.add(btxoa);

frame.setVisible(true);

btthem.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String mssv=jmssv.getText();

String hoten=jhoten.getText();

int namsinh=Integer.parseInt(jnamsinh.getText());

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Edit URL , username, password to authenticate with your MS SQL Server

String url =
"jdbc:sqlserver://localhost:1433;databaseName=QLSV;encrypt=true;trustServerCertificate=true";

String username = "vinh";

String password = "123456789";

con = DriverManager.getConnection(url, username, password);

Statement stmt=con.createStatement();//Truy vấn bảng Sinh viên trong CSDL

String lenh="Insert into Sinhvien Values(?,?,?)";

PreparedStatement them = con.prepareStatement(lenh);

them.setString(1, mssv);

them.setString(2,hoten);

them.setInt(3, namsinh);

them.executeUpdate();

System.out.println("Thêm dữ liệu thành công");

con.close();

}catch (Exception loi) {

System.out.println("Lỗi: "+loi.getMessage());

}
}

});

btsua.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String mssv=jmssv.getText();

String hoten=jhoten.getText();

int namsinh=Integer.parseInt(jnamsinh.getText());

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Edit URL , username, password to authenticate with your MS SQL Server

String url =
"jdbc:sqlserver://localhost:1433;databaseName=QLSV;encrypt=true;trustServerCertificate=true";

String username = "vinh";

String password = "123456789";

con = DriverManager.getConnection(url, username, password);

Statement stmt=con.createStatement();//Truy vấn bảng Sinh viên trong CSDL

String lenh="Update Sinhvien set NamSinh="+namsinh+" where


mssv='"+mssv+"'";

PreparedStatement sua = con.prepareStatement(lenh);

sua.executeUpdate();

System.out.println("sửa dữ liệu thành công");

con.close();

}catch (Exception loi) {

System.out.println("Lỗi: "+loi.getMessage());

});

btxoa.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent e) {

String mssv=jmssv.getText();

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

// Edit URL , username, password to authenticate with your MS SQL Server

String url =
"jdbc:sqlserver://localhost:1433;databaseName=QLSV;encrypt=true;trustServerCertificate=true";

String username = "vinh";

String password = "123456789";

con = DriverManager.getConnection(url, username, password);

Statement stmt=con.createStatement();

String lenh="Delete from Sinhvien where mssv='"+mssv+"'";

PreparedStatement xoa = con.prepareStatement(lenh);

xoa.executeUpdate();

System.out.println("Xóa dữ liệu thành công");

con.close();

}catch (Exception loi) {

System.out.println("Lỗi: "+loi.getMessage());

});

Them,xoa,sua , tim hoa dshang:


package javanangcao;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.*;

public class bai16 extends JFrame{


private JTextField txtMaSP, txtTenSP, txtGia, txtMaLoaiSP;
private JButton btnAdd,btndelete,btnsua,btnseach;
protected static Connection con;
public bai16() {
createView();
setTitle("Quản lý bán hàng");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setResizable(false);

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url =
"jdbc:sqlserver://localhost:1433;databaseName=qlbanhang;encrypt=true;trustServerCertificate=true";
String username = "long";
String password = "123456789";
con = DriverManager.getConnection(url, username, password);

}catch(Exception loi) {System.out.println(loi.getMessage());}


}
private void createView() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new BorderLayout());

JPanel inputPanel = new JPanel(new GridLayout(4, 2));


inputPanel.add(new JLabel("Mã sản phẩm:"));
txtMaSP = new JTextField();
inputPanel.add(txtMaSP);

inputPanel.add(new JLabel("Tên sản phẩm:"));


txtTenSP = new JTextField();
inputPanel.add(txtTenSP);
inputPanel.add(new JLabel("Giá:"));
txtGia = new JTextField();
inputPanel.add(txtGia);

inputPanel.add(new JLabel("Mã loại sản phẩm:"));


txtMaLoaiSP = new JTextField();
inputPanel.add(txtMaLoaiSP);

panel.add(inputPanel, BorderLayout.NORTH);

JPanel buttonPanel = new JPanel();


//nut them
btnAdd = new JButton("Thêm sản phẩm");
btnAdd.addActionListener(new ButtonaddListener());
buttonPanel.add(btnAdd);
panel.add(buttonPanel, BorderLayout.SOUTH);
//mut xoa
btndelete = new JButton("xoa sản phẩm");
btndelete.addActionListener(new ButtondeleteListener());
buttonPanel.add(btndelete);
panel.add(buttonPanel, BorderLayout.SOUTH);
//nut sua
btnsua = new JButton("sua sản phẩm");
btnsua.addActionListener(new updateButtonListener ());
buttonPanel.add(btnsua);
panel.add(buttonPanel, BorderLayout.SOUTH);
//nut tim
btnseach = new JButton("tim sản phẩm");
btnseach.addActionListener(new SearchButtonListener ());
buttonPanel.add( btnseach);
panel.add(buttonPanel, BorderLayout.SOUTH);

}
//su kien them
private class ButtonaddListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
String maSP = txtMaSP.getText();
String tenSP = txtTenSP.getText();
String gia = txtGia.getText();
String maloaiSP = txtMaLoaiSP.getText();
String lenh= "INSERT INTO sanpham (masp, tensp, gia, maloaisp)
VALUES('"+maSP+"','"
+tenSP+"',"+gia+",'"+maloaiSP+"')";
Statement stmt=con.createStatement();
stmt.execute(lenh);
JOptionPane.showMessageDialog(null, "Thêm sản phẩm thành công!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi thêm sản phẩm: " +
ex.getMessage());
}
}
}
//su kien xoa
private class ButtondeleteListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
String maSP = txtMaSP.getText();

String lenh= "DELETE FROM sanpham WHERE masp='"+maSP+"'";


Statement stmt=con.createStatement();
stmt.execute(lenh);
JOptionPane.showMessageDialog(null, "xoa sản phẩm thành công!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi xoa sản phẩm: " + ex.getMessage());
}
}
}
//su kien sua
private class updateButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
String maSP = txtMaSP.getText();
String tenSP = txtTenSP.getText();
String gia = txtGia.getText();
String maloaiSP = txtMaLoaiSP.getText();
String lenh="UPDATE sanpham SET tensp='" + tenSP + "', gia=" + gia + ", maloaisp='"
+ maloaiSP + "' WHERE masp='" + maSP + "'";

Statement stmt=con.createStatement();
stmt.execute(lenh);
JOptionPane.showMessageDialog(null, "sua sản phẩm thành công!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi sua sản phẩm: " + ex.getMessage());
}
}
}

//tim
private class SearchButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
String maSP = txtMaSP.getText();
String lenh = "SELECT * FROM sanpham WHERE masp='" + maSP + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(lenh);
if (rs.next()) {
txtTenSP.setText(rs.getString("tensp"));
txtGia.setText(rs.getString("gia"));
txtMaLoaiSP.setText(rs.getString("maloaisp"));
JOptionPane.showMessageDialog(null, "Tìm thấy sản phẩm!");
} else {
JOptionPane.showMessageDialog(null, "Không tìm thấy sản phẩm với mã SP: " +
maSP);
}
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi tìm sản phẩm: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai16().setVisible(true);
}
});
}

package Nguyen_Hoang_Long_221A010124;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class bai1 extends JFrame {


private JTextField txtHoTen;
private JTextField txtDiemBatDau;
private JTextField txtDiemKetThuc;
private JTextField txtGiaVe;

protected static Connection con;

public bai1() {
setTitle("Đặt Vé Xe Bus");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLayout(new BorderLayout());

JPanel panel = new JPanel(new GridLayout(5, 2));


txtHoTen = new JTextField();
txtDiemBatDau = new JTextField();
txtDiemKetThuc = new JTextField();
txtGiaVe = new JTextField();
JButton btnDatVe = new JButton("Đặt vé");
JButton btnHuyDatVe = new JButton("Hủy đặt vé");

panel.add(new JLabel("Họ tên khách hàng:"));


panel.add(txtHoTen);
panel.add(new JLabel("Điểm bắt đầu:"));
panel.add(txtDiemBatDau);
panel.add(new JLabel("Điểm kết thúc:"));
panel.add(txtDiemKetThuc);
panel.add(new JLabel("Giá vé:"));
panel.add(txtGiaVe);
panel.add(btnDatVe);
panel.add(btnHuyDatVe);
add(panel, BorderLayout.CENTER);

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url =
"jdbc:sqlserver://localhost:1433;databaseName=qlbuss;encrypt=true;trustServerCertificate=true";
String username = "long";
String password = "123456";
con = DriverManager.getConnection(url, username, password);
System.out.println("Kết nối thành công");
} catch (Exception loi) {
System.out.println("Lỗi " + loi.getMessage());
loi.printStackTrace();
}

btnDatVe.addActionListener(new DatVeButtonListener());
btnHuyDatVe.addActionListener(new HuyDatVeButtonListener());

setVisible(true);
}

private class DatVeButtonListener implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
try {
String hoTen = txtHoTen.getText();
String diemBatDau = txtDiemBatDau.getText();
String diemKetThuc = txtDiemKetThuc.getText();
String giaVe = txtGiaVe.getText();

String queryKhachHang = "SELECT makh FROM KhachHang WHERE hoten = ?";


PreparedStatement stmtKhachHang = con.prepareStatement(queryKhachHang);
stmtKhachHang.setString(1, hoTen);
ResultSet rsKhachHang = stmtKhachHang.executeQuery();

int makh = -1;


if (rsKhachHang.next()) {
makh = rsKhachHang.getInt("makh");
} else {
JOptionPane.showMessageDialog(null, "Khách hàng không tồn tại!");
return;
}

String queryTuyenDuong = "SELECT matuyen FROM TuyenDuong WHERE diemdi = ? AND


diemden = ?";
PreparedStatement stmtTuyenDuong = con.prepareStatement(queryTuyenDuong);
stmtTuyenDuong.setString(1, diemBatDau);
stmtTuyenDuong.setString(2, diemKetThuc);
ResultSet rsTuyenDuong = stmtTuyenDuong.executeQuery();

int matuyen = -1;


if (rsTuyenDuong.next()) {
matuyen = rsTuyenDuong.getInt("matuyen");
} else {
JOptionPane.showMessageDialog(null, "Tuyến đường không tồn tại!");
return;
}

String lenh = "INSERT INTO DatVe (makh, matuyen, ngaydatve) VALUES (?, ?, ?)";
PreparedStatement stmtDatVe = con.prepareStatement(lenh);
stmtDatVe.setInt(1, makh);
stmtDatVe.setInt(2, matuyen);
stmtDatVe.setString(3, java.time.LocalDate.now().toString());

stmtDatVe.executeUpdate();
JOptionPane.showMessageDialog(null, "Đặt vé thành công!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi đặt vé: " + ex.getMessage());
}
}
}

private class HuyDatVeButtonListener implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showConfirmDialog(null, "Bạn chắc chắn hủy đặt vé?", "Xác nhận",
JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION) {
try {
String hoTen = txtHoTen.getText();

String queryKhachHang = "SELECT makh FROM KhachHang WHERE hoten = ?";


PreparedStatement stmtKhachHang = con.prepareStatement(queryKhachHang);
stmtKhachHang.setString(1, hoTen);
ResultSet rsKhachHang = stmtKhachHang.executeQuery();

int makh = -1;


if (rsKhachHang.next()) {
makh = rsKhachHang.getInt("makh");
} else {
JOptionPane.showMessageDialog(null, "Khách hàng không tồn tại!");
return;
}

String lenh = "DELETE FROM DatVe WHERE makh = ?";


PreparedStatement stmt = con.prepareStatement(lenh);
stmt.setInt(1, makh);
stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Hủy đặt vé thành công!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Lỗi khi hủy đặt vé: " + ex.getMessage());
}
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai1().setVisible(true);
}
});
}
}

package Nguyen_Hoang_Long_221A010124;

import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.table.DefaultTableModel;

public class bai2 extends JFrame {


private JTextField txttuyenduong;
private JTable table;
private DefaultTableModel tableModel;
protected static Connection con;
public bai2() {
setTitle("tìm kiếm theo mã tuyến");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLayout(new BorderLayout());
JPanel panel = new JPanel(new GridLayout(5, 2));
txttuyenduong = new JTextField();
JButton btntimkiem = new JButton("tim kiem");
panel.add(new JLabel("nhập mã tuyến đường:"));
panel.add(txttuyenduong);
panel.add(btntimkiem);
add(panel, BorderLayout.NORTH);

tableModel = new DefaultTableModel(new String[]{"Mã tuyến", "Điểm bắt đầu", "Điểm kết
thúc", "Giá"}, 0);
table = new JTable(tableModel);
add(new JScrollPane(table), BorderLayout.CENTER);
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url =
"jdbc:sqlserver://localhost:1433;databaseName=qlbuss;encrypt=true;trustServerCertificate=true";
String username = "long";
String password = "123456";
con = DriverManager.getConnection(url, username, password);
System.out.println("Kết nối thành công");
} catch (Exception loi) {
System.out.println("Lỗi " + loi.getMessage());
loi.printStackTrace();
}
btntimkiem.addActionListener(new TimKiemButtonListener());

setVisible(true);
}
private class TimKiemButtonListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
try {
String maTuyen = txttuyenduong.getText();
String sql = "SELECT * FROM TuyenDuong WHERE matuyen = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, maTuyen);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String matuyen = rs.getString("matuyen");
String diembatdau = rs.getString("diemdi");
String diemketthuc = rs.getString("diemden");
int giave = rs.getInt("giave");
tableModel.addRow(new Object[]{matuyen, diembatdau, diemketthuc, giave});
}
}catch (Exception loi) {
System.out.println("Lỗi " + loi.getMessage());
loi.printStackTrace();
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai2().setVisible(true);
}
});
}
}

File:
package javanangcao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class bai10 extends JFrame {
private JTextArea textarea;
private JButton openbutton;
public bai10() {

setTitle("doc file");
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
textarea=new JTextArea();
JScrollPane scorllpane =new JScrollPane(textarea);
openbutton =new JButton("mo file");
openbutton.addActionListener(new Openbuttonlisterner());
add(scorllpane, BorderLayout.CENTER);
add(openbutton, BorderLayout.SOUTH);
}

private class Openbuttonlisterner implements ActionListener{


@Override
public void actionPerformed(ActionEvent e) {
JFileChooser filechooser =new JFileChooser();
int returnvalue = filechooser.showOpenDialog(null);
if (returnvalue == JFileChooser.APPROVE_OPTION) {
File seclectedfile = filechooser.getSelectedFile();
try (BufferedReader reader =new BufferedReader(new FileReader(seclectedfile))){
textarea.setText(" ");
String line;
while((line= reader.readLine())!=null) {
textarea.append(line+"\n");
}
}catch (IOException ex) {
JOptionPane.showMessageDialog(null, "loi file" + ex.getMessage());
}
}
}

}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new bai10().setVisible(true);

}
});

}
}

package javanangcao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class bai11 extends JFrame {

public static void main(String[] args) {


JFrame frame =new JFrame("ghi du lieu vao file");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400 ,400);
JTextArea textarea =new JTextArea();
JScrollPane scoellpane =new JScrollPane(textarea);
JButton button =new JButton("ghi du lieu suong file");

button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
String text = textarea.getText();

try (BufferedWriter writer =new BufferedWriter(new FileWriter("C:\\


Users\\ASUS\\Desktop\\textjava.txt")) ){
writer.write(text);
JOptionPane.showMessageDialog(frame, "da ghi du lieu");

}catch (IOException iorexception) {


JOptionPane.showMessageDialog(frame, "co loi","loi",
JOptionPane.ERROR_MESSAGE);
}

}
});
frame.getContentPane().add(scoellpane, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.setVisible(true);

}
}

Coppy tu file nay sang file khac:


package javanangcao;
import java.io.*;
import java.nio.file.*;
public class bai12 {
public static void main(String[] args) {
Path sourcrpath = Paths.get("C:\\Users\\ASUS\\Desktop\\textjava.txt");
Path destinationpath = Paths.get("txt1.txt");
try {
Files.copy(sourcrpath, destinationpath);
System.out.println("da coppy thanh cong");
}catch (IOException e) {
System.err.println("loi"+ e.getMessage());
}
}
}
package javanangcao;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ClickCounter {


private int count = 0;

public ClickCounter() {
// Tạo frame
JFrame frame = new JFrame("Counter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

// Tạo panel
JPanel panel = new JPanel();

// Tạo label để hiển thị số lần click


JLabel label = new JLabel("Click count: 0");

// Tạo button và thêm ActionListener cho button


JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Click count: " + count);
}
});

// Thêm button và label vào panel


panel.add(button);
panel.add(label);

// Thêm panel vào frame


frame.add(panel);

// Hiển thị frame


frame.setVisible(true);
}

public static void main(String[] args) {


new ClickCounter();
}
}

package javanangcao;
import javax.swing.*;

public class table {


JFrame f;
table(){
f=new JFrame("bang diem");
String data[][]={{"sv1","long","8"},{"sv2","a","8"}};
String column[]={"id","name","mark"};
JTable jt=new JTable(data,column);
jt.setBounds(30, 40, 200, 300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String[] args){
new table();
}}

package javanangcao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class tinhtoancoban extends JFrame{
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
public tinhtoancoban() {
createView();
setTitle("Máy tính đơn giản");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600, 300);
setLocationRelativeTo(null);
setResizable(false);
}
private void createView() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(5, 2, 10, 10));
JLabel label1 = new JLabel("Số thứ nhất:");
panel.add(label1);
textField1 = new JTextField();
panel.add(textField1);
JLabel label2 = new JLabel("Số thứ hai:");
panel.add(label2);
textField2 = new JTextField();
panel.add(textField2);
JLabel label3 = new JLabel("Kết quả: ");
panel.add(label3);
textField3 = new JTextField();
panel.add(textField3);
JButton addButton = new JButton("Cộng");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performOperation("+");
}
});
panel.add(addButton);
JButton subtractButton = new JButton("Trừ");
subtractButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performOperation("-");
}
});
panel.add(subtractButton);
JButton multiplyButton = new JButton("Nhân");
multiplyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performOperation("*");
}
});
panel.add(multiplyButton);
JButton divideButton = new JButton("Chia");
divideButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performOperation("/");
}
});
panel.add(divideButton);
}
private void performOperation(String operation) {
try {
double num1 = Double.parseDouble(textField1.getText());
double num2 = Double.parseDouble(textField2.getText());
double result = 0;
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
JOptionPane.showMessageDialog(this, "Không thể chia cho 0!", "Lỗi",
JOptionPane.ERROR_MESSAGE);
return;
}
result = num1 / num2;
break;
}

textField3.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Vui lòng nhập số hợp lệ!", "Lỗi",
JOptionPane.ERROR_MESSAGE);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new tinhtoancoban().setVisible(true);
}
});
}

package javanangcao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class bai3 extends JFrame{
private JComboBox<String>corlorcombobox;
private JPanel mainpanel;
public bai3() {
setTitle("doi mau");
setSize(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

mainpanel =new JPanel();


mainpanel.setLayout(new BorderLayout());
add(mainpanel);

String[] corlors= {"white","red","grenn","blue"};


corlorcombobox =new JComboBox<>(corlors);

corlorcombobox.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
changeBackgroundcolor((String) corlorcombobox.getSelectedItem());

}
});
mainpanel.add(corlorcombobox, BorderLayout.NORTH);
setVisible(true);

}
private void changeBackgroundcolor(String color) {
switch (color) {
case "white:":
mainpanel.setBackground(Color.white);
break;
case "red":
mainpanel.setBackground(Color.red);

break;
case "grenn":
mainpanel.setBackground(Color.green);
break;
case "blue":
mainpanel.setBackground(Color.BLUE);
break;
}

}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

public void run() {


new bai3().setVisible(true);

}
});
}
}
package javanangcao;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class bai4 extends JFrame{

private JRadioButton catButton;


private JRadioButton bigButton;
private JRadioButton fishButton;
private JRadioButton dogButton;
private JRadioButton rabbitButton;
private JLabel imageLabel;

public bai4() {
setTitle("Animal Selector");
setSize(600, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Create components
catButton = new JRadioButton("Cat");
dogButton = new JRadioButton("Dog");
bigButton = new JRadioButton("big");
fishButton = new JRadioButton("fish");
rabbitButton = new JRadioButton("rabbit");

ButtonGroup group = new ButtonGroup();


group.add(catButton);
group.add(dogButton);
group.add(bigButton);
group.add(fishButton);
group.add(rabbitButton);
imageLabel = new JLabel();
// Set initial image
updateImage("Cat");
// Add action listeners to radio buttons
catButton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
updateImage("Cat");
}
});
dogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateImage("Dog");
}
});
bigButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateImage("big");
}
});
fishButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateImage("fish");
}
});
rabbitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateImage("rabbit");
}
});

// Layout setup
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(3, 1));
radioPanel.add(catButton);
radioPanel.add(dogButton);
radioPanel.add(bigButton);
radioPanel.add(fishButton);
radioPanel.add(rabbitButton);
setLayout(new BorderLayout());
add(radioPanel, BorderLayout.WEST);
add(imageLabel, BorderLayout.NORTH);

// Set default selection


catButton.setSelected(true);
}

private void updateImage(String animal) {


// Update image based on selected animal
String imagePath = "";
switch (animal) {
case "Cat":
imagePath = "C:\\Users\\Administrator\\Desktop\\cat.jpg";
break;
case "Dog":
imagePath = "C:\\Users\\Administrator\\Desktop\\dog.jpg";
break;

case "fish":
imagePath = "C:\\Users\\Administrator\\Desktop\\fish.jpg";
break;
case "rabbit":
imagePath = "C:\\Users\\Administrator\\Desktop\\rabbit.jpg";
break;
}
ImageIcon imageIcon = new ImageIcon(imagePath);
imageLabel.setIcon(imageIcon);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai4().setVisible(true);
}
}); }}

package javanangcao;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class bai5 extends JFrame {
private JCheckBox pizza;
private JCheckBox burger;
private JCheckBox tea;
private JCheckBox coffe;
private JButton orderbutton;
public bai5() {

setTitle("food ordering");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

pizza=new JCheckBox("pizza(25$)");
burger=new JCheckBox("burger(30$)");
tea=new JCheckBox("tea(5$)");
coffe=new JCheckBox("coffe(7$)");

orderbutton =new JButton("order");


setLayout(new GridLayout(4, 1));
add(pizza);
add(burger);
add(tea);
add(coffe);
add(orderbutton);

orderbutton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
StringBuilder message =new StringBuilder();
int total =0;
if(pizza.isSelected()) {
message.append("pizaa:$25\n");
total +=25;
}
if(burger.isSelected()) {
message.append("burger:$30\n");
total +=30;
}
if(tea.isSelected()) {
message.append("tea:$5\n");
total +=5;
}
if(coffe.isSelected()) {
message.append("coffe:$7\n");
total +=7;
}
message.append("---------------------\n");
message.append("total: $"+total);

JOptionPane.showMessageDialog(bai5.this,message.toString(),"message",JOptionPane.INFORMATION_
MESSAGE);

}
});

}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai5().setVisible(true);
}
});
}

}
package javanangcao;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class bai6 extends JFrame{
private JTable table;
private DefaultTableModel tablemodel;
public bai6() {
setTitle("phonebook");
setSize(400,300);
setLocationRelativeTo(null);
setLayout(new BorderLayout());

tablemodel =new DefaultTableModel(new Object[] {"name","phone no"},0);


table =new JTable(tablemodel);
JScrollPane scrollpane =new JScrollPane(table);
add(scrollpane,BorderLayout.CENTER);

JPanel buttonpanel =new JPanel();


JButton addbutton =new JButton("add contact");
JButton deletebutton=new JButton("delete contact");
buttonpanel.add(addbutton);
buttonpanel.add(deletebutton);
add(buttonpanel,BorderLayout.SOUTH);

addbutton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

String name =JOptionPane.showInputDialog(bai6.this,"enter name: ");


if(name != null&&!name.trim().isEmpty()) {
String phoneno =JOptionPane.showInputDialog(bai6.this,"enter
phone no");
if(phoneno !=null&&! phoneno.trim().isEmpty()){
tablemodel.addRow(new Object[] {name,phoneno});
}else
{

JOptionPane.showMessageDialog(bai6.this,"phone canot
empty" ,"error",JOptionPane.ERROR_MESSAGE);
}

}else {
JOptionPane.showMessageDialog(bai6.this,"name canot
empty" ,"error",JOptionPane.ERROR_MESSAGE );
}

}
});

deletebutton.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
int selectedrow = table.getSelectedRow();
if(selectedrow !=-1) {
tablemodel.removeRow(selectedrow);
}else {
JOptionPane.showMessageDialog(bai6.this,"no contact
selected.","error",JOptionPane.ERROR_MESSAGE);
}

}
});

}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai6().setVisible(true);
}
});
}

}
package javanangcao;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class bai7 extends JFrame {


// Khai báo các thành phần
private JTextField txtSoa, txtSob, txtSoc, txtKetqua;
private JButton btnGiai, btnXoaTrang, btnThoat;
private JLabel lblTieuDe;

public bai7() {
// Thiết lập tiêu đề cho JFrame
setTitle("Giải Phương Trình Bậc 2");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);

// Tạo và thêm các thành phần GUI


lblTieuDe = new JLabel("Giải phương trình bậc 2");
lblTieuDe.setBounds(120, 10, 200, 25);
add(lblTieuDe);

JLabel lblSoa = new JLabel("a:");


lblSoa.setBounds(50, 50, 20, 25);
add(lblSoa);

txtSoa = new JTextField();


txtSoa.setBounds(100, 50, 200, 25);
add(txtSoa);

JLabel lblSob = new JLabel("b:");


lblSob.setBounds(50, 90, 20, 25);
add(lblSob);

txtSob = new JTextField();


txtSob.setBounds(100, 90, 200, 25);
add(txtSob);

JLabel lblSoc = new JLabel("c:");


lblSoc.setBounds(50, 130, 20, 25);
add(lblSoc);

txtSoc = new JTextField();


txtSoc.setBounds(100, 130, 200, 25);
add(txtSoc);

JLabel lblKetqua = new JLabel("Kết Quả:");


lblKetqua.setBounds(50, 170, 50, 25);
add(lblKetqua);

txtKetqua = new JTextField();


txtKetqua.setBounds(100, 170, 200, 25);
txtKetqua.setEditable(false);
add(txtKetqua);

btnGiai = new JButton("Giải");


btnGiai.setBounds(50, 210, 80, 25);
add(btnGiai);

btnXoaTrang = new JButton("Xóa trắng");


btnXoaTrang.setBounds(150, 210, 100, 25);
add(btnXoaTrang);

btnThoat = new JButton("Thoát");


btnThoat.setBounds(270, 210, 80, 25);
add(btnThoat);

// Thêm các sự kiện cho nút


btnGiai.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
solveQuadraticEquation();
}
});

btnXoaTrang.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearFields();
}
});

btnThoat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

// Hiển thị JFrame


setVisible(true);
}

// Phương thức giải phương trình bậc 2


private void solveQuadraticEquation() {
try {
double a = Double.parseDouble(txtSoa.getText());
double b = Double.parseDouble(txtSob.getText());
double c = Double.parseDouble(txtSoc.getText());
if (a == 0) {
txtKetqua.setText("Không phải phương trình bậc 2");
} else {
double delta = b * b - 4 * a * c;
if (delta < 0) {
txtKetqua.setText("Phương trình vô nghiệm");
} else if (delta == 0) {
double x = -b / (2 * a);
txtKetqua.setText("Phương trình có nghiệm kép: x = " + x);
} else {
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
txtKetqua.setText("Phương trình có 2 nghiệm: x1 = " + x1 + ", x2 = " + x2);
}
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Vui lòng nhập số hợp lệ", "Lỗi",
JOptionPane.ERROR_MESSAGE);
}
}

// Phương thức xóa trắng các ô nhập liệu


private void clearFields() {
txtSoa.setText("");
txtSob.setText("");
txtSoc.setText("");
txtKetqua.setText("");
}

public static void main(String[] args) {


// Tạo và hiển thị JFrame trên Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new bai7();
}
});
}
}
package javanangcao;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
public class bai8 extends JFrame {
private JTextField txtaccountnumber, txtaccountname, txtaccountmoney ;
private JTable table;
private JButton btnadd, btnclear, btnexit;
private DefaultTableModel tabelmodel;

public bai8() {
setTitle("account");
setSize(500,400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);

JLabel lblaccountnumber =new JLabel("account number");


lblaccountnumber.setBounds(30,20,100,25);
add(lblaccountnumber);

txtaccountnumber =new JTextField();


txtaccountnumber.setBounds(150,20,100,25);
add(txtaccountnumber);

JLabel lblaccountname = new JLabel("account name");


lblaccountname.setBounds(30,60,100,25);
add(lblaccountname);

txtaccountname =new JTextField();


txtaccountname.setBounds(150,60,300,25);
add(txtaccountname);
JLabel lblaccountmoney = new JLabel("account money");
lblaccountmoney.setBounds(30,100,100,25);
add(lblaccountmoney);

txtaccountmoney =new JTextField();


txtaccountmoney.setBounds(150,100,300,25);
add(txtaccountmoney);

tabelmodel = new DefaultTableModel();


tabelmodel.addColumn("acc number");
tabelmodel.addColumn("acc name");
tabelmodel.addColumn("acc money");
table =new JTable(tabelmodel);
JScrollPane scrollpane =new JScrollPane(table);
scrollpane.setBounds(30,140,420,150);
add(scrollpane);

btnadd =new JButton("add");


btnadd.setBounds(350,310,100,25);
add(btnadd);

btnclear =new JButton("clear");


btnclear.setBounds(200,310,100,25);
add(btnclear);

btnexit =new JButton("exit");


btnexit.setBounds(350,310,100,25);
add(btnexit);

btnadd.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
addaccount();

}
});

btnclear.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

clearfields();
}
});
btnexit.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);

}
});
setVisible(true);
}

private void addaccount() {


String accountnumber = txtaccountnumber.getText();
String accountname = txtaccountname.getText();
String accountmoney =txtaccountmoney.getText();

if(accountname.isEmpty() || accountmoney.isEmpty() || accountnumber.isEmpty()) {


JOptionPane.showMessageDialog(this, "vui long nhap day du thong tin",
"loi",JOptionPane.ERROR_MESSAGE);
}else {
tabelmodel.addRow(new Object[] {accountnumber,accountmoney,accountname});
clearfields();
}
}
private void clearfields() {
txtaccountmoney.setText("");
txtaccountname.setText("");
txtaccountnumber.setText("");
}
public static void main(String[]args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new bai8();

}
});
}

You might also like