03/04/2021, 20:59

Tìm kiếm (txttimkiem)

Mình làm hàm text tìm kiếm(txttimkiem) tự nhiên bị lỗi Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 trong java swing database làm thể nào để khắc phục lỗi.

//class 1
package databyte;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class connect {
public Connection getConnection(){
Connection conn= null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-2UQ7OP1\\SQL1:52919;database=QLBanHang","sa","123456");
if (conn!= null) {
System.out.println("Kết nối thành công!");
}
}catch(Exception ex) {
System.out.println(ex.toString());
}
return conn;
}
 
public static PreparedStatement preparedStatement(String query) {
// TODO Auto-generated method stub
return null;
}
 
public static Connection dbConnector() {
// TODO Auto-generated method stub
return null;
}
}
 
 
//class 2
package databyte;
public class vd2 {
private String MaSP, TenSP, DonViTinh;
private float DonGia;
private byte[] picture;
public vd2(String MaSP, String TenSP, String DonViTinh, float DonGia, byte[] Image) {
// TODO Auto-generated constructor stub
  this.MaSP=MaSP;
   this.TenSP=TenSP;
   this.DonViTinh=DonViTinh;
   this.DonGia=DonGia;
   this.picture=Image;
}
public void vd21(String string, String string2, String string3, float float1, byte[] bytes) {
// TODO Auto-generated constructor stub
}
public String getMaSP() {
return MaSP;
}
public String getTenSP() {
return TenSP;
}
public String getDonViTinh() {
return DonViTinh;
}
public float getDonGia() {
return DonGia;
}
 
public byte[] getImage() {
// TODO Auto-generated method stub
return null;
}
}
 
 
//class 3
package databyte;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Image;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;
import java.lang.NumberFormatException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.util.List;
import net.proteanit.sql.DbUtils;
 
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.SystemColor;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
 
public class dataswing extends javax.swing.JFrame {
private JFrame frame;
private JTable table_2;
private JTextField txtmsp;
private JTextField txtsp;
private JLabel lblNhapTenlop;
private JLabel lbl_image;
private JTextField txtgia;
private JComboBox comboBox;
private byte[] picture;
DefaultTableModel tbn= new DefaultTableModel();
private JTextField txttimkiem;
String MaSP; 
String filename=null;
String from;
Connection conn=null;
private Object list;
    static byte[] person_img=null;
 
 
protected Vector<String> usersList() {
// TODO Auto-generated method stub
return null;
}
/*public ArrayList<vd2>usersList(){
ArrayList<vd2>usersList=new ArrayList<>();
try {
String url = "jdbc:sqlserver://DESKTOP-2UQ7OP1\\SQL1:52919;database=QLBanHang";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection m_connection = DriverManager.getConnection(url,"sa","123456");
//Connection con = DriverManager.getConnection(url);
String queryl="Select * from SANPHAM";
Statement st =m_connection.createStatement();
ResultSet rs = st.executeQuery(queryl);
vd2 user;
while (rs.next()) {
user=new vd2(rs.getString("MaSP"),rs.getString("TenSP"),rs.getString("DonViTinh"),rs.getFloat("DonGia"),rs.getBytes("Image"));
usersList.add(user);
}
}catch(Exception ex){
System.out.println(ex.toString());
}
return usersList();
}*/
/*public dataswing(String malop, String tenlop){
this.malop=malop;
this.tenlop=tenlop;
}*/
/*public static Connection openConnection() throws Exception{
String url = "jdbc:sqlserver://DESKTOP-2UQ7OP1\\SQL1:52919;database=QLBanHang";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection m_connection = DriverManager.getConnection(url,"sa","123456");
return m_connection;
}*/
 
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dataswing window = new dataswing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public dataswing() {
this.picture=getImage();
getContentPane().setLayout(null);
initialize();
sort();
loadData();
loadComobox();
}
public void loadData() {
try {
connect a=new connect();
Connection conn= a.getConnection();
int number;
Vector<String> row, column;
column = new Vector<String>();
Statement at= conn.createStatement();
ResultSet rs = at.executeQuery("Select * from SANPHAM");
ResultSetMetaData metadata = rs.getMetaData();
number= metadata.getColumnCount();
for(int i=1; i<= number; i++){
column.add(metadata.getColumnName(i));
}
tbn.setColumnIdentifiers(column);
while(rs.next()) {
new vd2(rs.getString("MaSP"),rs.getString("TenSP"),rs.getString("DonViTinh"),rs.getFloat("DonGia"),rs.getBytes("Image"));
row=new Vector<String>();
for(int i=1; i<= number;i++) {
row.addElement(rs.getString(i));
}
tbn.addRow(row);
table_2.setModel(tbn);
}
table_2.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
 
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if(table_2.getSelectedRow()>=0) {
int i= table_2.getSelectedRow();
txtmsp.setText(table_2.getValueAt(i,0)+"");
txtsp.setText(table_2.getValueAt(i,1)+"");
comboBox.setSelectedItem(table_2.getModel().getValueAt(i, 2)+"");
txtgia.setText(table_2.getValueAt(i,3)+"");
lbl_image.setVisible(true);
//String img=(usersList().get(i));
//ImageIcon imageIcon= new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(lbl_image.getWidth(),lbl_image.getHeight(),Image.SCALE_SMOOTH));
//lbl_image.setIcon(imageIcon);
}
}
 
});
}catch(Exception ex) {
System.out.println(ex.toString());
}
}
public byte[] getImage() {
return picture;
}
private void sort(){
TableRowSorter<DefaultTableModel> sorter= new TableRowSorter<DefaultTableModel>(tbn);
table_2.setRowSorter(sorter);
}
public void loadComobox() {
try {
connect a=new connect();
Connection conn= a.getConnection();
PreparedStatement ps=conn.prepareStatement("Select DonViTinh from SANPHAM group by DonViTinh");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    comboBox.addItem(rs.getString("DonViTinh"));
}
}catch (Exception ex) {
System.out.println(ex.toString());
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("Sản phẩm");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\doanngoctin\\IMG_26012021_183213_(150_x_100_pixel).jpg"));
frame.setBounds(100, 100, 780, 428);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(240, 27, 514, 201);
table_2 = new JTable();
table_2.setForeground(new Color(204, 51, 255));
table_2.setBackground(new Color(0, 255, 0));
scrollPane.setViewportView(table_2);
table_2.setToolTipText("");
table_2.setModel(new DefaultTableModel(
new Object[][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
},
new String[] {
"New column", "New column", "New column", "New column"
}
));
 
JLabel lblNewLabel = new JLabel("Mã sản phẩm");
lblNewLabel.setBounds(22, 30, 113, 14);
lblNewLabel.setForeground(new Color(204, 0, 255));
 
txtmsp = new JTextField();
txtmsp.setBounds(117, 27, 113, 20);
txtmsp.setBackground(new Color(51, 255, 51));
txtmsp.setColumns(10);
 
txtsp = new JTextField();
txtsp.setBounds(117, 61, 113, 20);
txtsp.setBackground(new Color(51, 255, 51));
txtsp.setColumns(10);
 
lblNhapTenlop = new JLabel("Tên sản phẩm");
lblNhapTenlop.setBounds(22, 64, 113, 14);
lblNhapTenlop.setForeground(new Color(204, 0, 255));
 
JButton btnthem = new JButton("Th\u00EAm");
btnthem.setBounds(29, 205, 89, 23);
btnthem.setForeground(new Color(255, 255, 255));
btnthem.setBackground(new Color(51, 0, 255));
btnthem.addActionListener(new ActionListener() {
private JFrame frame;
 
public void actionPerformed(ActionEvent e) {
try {
connect a=new connect();
Connection conn= a.getConnection();
PreparedStatement ps=conn.prepareStatement("insert into SANPHAM values(?,?,?,?,?)");
ps.setString(1,txtmsp.getText());
ps.setString(2,txtsp.getText());
ps.setString(3,comboBox.getSelectedItem().toString());
ps.setFloat(4,Float.parseFloat(txtgia.getText()));
ps.setBytes(5,person_img);
int chk=ps.executeUpdate();
if(chk>0) {
JOptionPane.showMessageDialog(frame,"Thêm thành công");
tbn.setRowCount(0);
loadData();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
 
JButton btnXoa = new JButton("X\u00F3a");
btnXoa.setBounds(141, 205, 89, 23);
btnXoa.setForeground(new Color(255, 255, 255));
btnXoa.setBackground(new Color(51, 51, 255));
btnXoa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
connect a=new connect();
Connection conn= a.getConnection();
PreparedStatement comm=conn.prepareStatement("Delete SANPHAM where MaSP=?");
comm.setString(1,table_2.getValueAt(table_2.getSelectedRow(),0).toString());
if(JOptionPane.showConfirmDialog(frame, "Xác nhận xóa?","Xác nhận",
   JOptionPane.YES_NO_OPTION)==JOptionPane.YES_NO_OPTION) {
comm.executeUpdate();
tbn.setRowCount(0);
loadData();
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
});
 
JButton btnSua = new JButton("S\u1EEDa");
btnSua.setBounds(29, 252, 89, 23);
btnSua.setForeground(new Color(255, 255, 255));
btnSua.setBackground(new Color(51, 0, 255));
btnSua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
connect a=new connect();
Connection conn= a.getConnection();
PreparedStatement comm=conn.prepareStatement("Update SANPHAM set TenSP=?,DonViTinh=?,DonGia=?,Image=? where MaSP=?");
comm.setString(5,txtmsp.getText());
comm.setString(1,txtsp.getText());
comm.setString(2,comboBox.getSelectedItem().toString());
comm.setFloat(3,Float.parseFloat(txtgia.getText()));
comm.setBytes(4,person_img);
comm.executeUpdate();
tbn.setRowCount(0);
loadData();
}catch(Exception ex){
System.out.println(ex.toString());
}
}
});
 
JLabel lblNewLabel_1 = new JLabel("Loại");
lblNewLabel_1.setBounds(22, 97, 106, 14);
lblNewLabel_1.setForeground(new Color(204, 0, 255));
 
JLabel lblNewLabel_1_1 = new JLabel("Đơn giá");
lblNewLabel_1_1.setBounds(22, 148, 106, 14);
lblNewLabel_1_1.setForeground(new Color(204, 0, 255));
 
txtgia = new JTextField();
txtgia.setBounds(117, 145, 113, 20);
txtgia.setBackground(new Color(51, 255, 51));
txtgia.setColumns(10);
 
 
 
comboBox = new JComboBox();
comboBox.setBounds(117, 92, 96, 22);
comboBox.setForeground(new Color(204, 0, 255));
comboBox.setBackground(new Color(51, 255, 51));
txttimkiem = new JTextField();
txttimkiem.setBounds(110, 302, 120, 20);
txttimkiem.setBackground(new Color(255, 255, 0));
txttimkiem.setColumns(10);
txttimkiem.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent argO) {
try {
connect a=new connect();
conn= a.getConnection();
//Statement st = conn.createStatement();
String query = "SELECT MaSP,TenSP,DonViTinh,DonGia,Image from SANPHAM  Where MaSP=?";
PreparedStatement st=conn.prepareStatement(query);
st.setString(1,txttimkiem.getText());
ResultSet rs = st.executeQuery();
table_2.setModel(DbUtils.resultSetToTableModel(rs));
conn.close();
/*if(rs.next()) {
String setid= rs.getString("MaSP");
txtmsp.setText(setid);
String setname= rs.getString("TenSP");
txtsp.setText(setname);
String setdonvitinh= rs.getString("DonViTinh");
comboBox.setSelectedItem(setdonvitinh);
String setdongia= rs.getString("DonGia");
txtgia.setText(setdongia);
byte[] img=rs.getBytes("Image");
ImageIcon imageIcon= new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(lbl_image.getWidth(),lbl_image.getHeight(),Image.SCALE_SMOOTH));
lbl_image.setIcon(imageIcon);
person_img=img;
rs = pst.executeQuery();
tbn.setRowCount(0);
loadData();
          }*/
 
}catch(Exception ex) {
System.err.println("Got an exception! "); 
        JOptionPane.showMessageDialog(null,"Got an exception!");
        System.err.println(ex.getMessage());
}
}
});
 
JLabel lblNewLabel_2 = new JLabel("Tìm kiếm");
lblNewLabel_2.setBounds(22, 305, 96, 14);
lblNewLabel_2.setForeground(new Color(255, 51, 102));
 
lbl_image = new JLabel("");
lbl_image.setBounds(319, 239, 120, 139);
lbl_image.setIcon(new ImageIcon("C:\\doanngoctin\\PVC-Expotrend-1015-Dark-Grey.jpg"));
lbl_image.setBackground(Color.BLACK);
JButton btnimage = new JButton("Chọn hình ảnh");
btnimage.setBounds(405, 301, 170, 23);
btnimage.setForeground(new Color(255, 255, 255));
btnimage.setBackground(new Color(102, 0, 255));
btnimage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser =new JFileChooser();
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
filename=f.getAbsolutePath();
ImageIcon imageIcon= new ImageIcon(new ImageIcon(filename).getImage().getScaledInstance(lbl_image.getWidth(),lbl_image.getHeight(),Image.SCALE_SMOOTH));
lbl_image.setIcon(imageIcon);
try {
connect a=new connect();
Connection conn= a.getConnection();
File image= new File(filename);
FileInputStream fis= new FileInputStream(image);
ByteArrayOutputStream bos= new ByteArrayOutputStream();
byte[]buf=new byte[1024];
for(int readNum;(readNum=fis.read(buf))!=-1;) {
bos.write(buf,0,readNum);
tbn.setRowCount(0);
loadData();
}
person_img=bos.toByteArray();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
 
JButton btnreset = new JButton("Làm lại");
btnreset.setBounds(141, 252, 89, 23);
btnreset.setForeground(new Color(255, 255, 255));
btnreset.setBackground(new Color(51, 0, 255));
btnreset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtmsp.setText("");
    txtsp.setText("");
comboBox.setSelectedIndex(0);
txtgia.setText("");
txttimkiem.setText("");
lbl_image.setText("");
}
});
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 764, 22);
menuBar.setBackground(Color.WHITE);
 
JMenu mnNewMenu = new JMenu("Menu");
mnNewMenu.setBackground(Color.WHITE);
menuBar.add(mnNewMenu);
 
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Trang chủ");
mntmNewMenuItem_2.setBackground(Color.WHITE);
mntmNewMenuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new menudatabase();
}
+1