Em gặp lỗi ở text tìm kiếm (txttimkiem) trong java swing database, lỗi
Exception in thread “AWT-EventQueue-0” java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
//class vd2
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 dataswing
Java swing database. Mã code này có thể bị sai ở chỗ txttimkiem, mong admin trợ giúp, em làm mã tìm kiếm chỉ hiển thị trên bảng.
package databyte;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Vector;
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.TableRowSorter;
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.ImageIcon;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
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;
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;
}
protected Vector<String> usersList() {
// TODO Auto-generated method stub
return null;
}
/**
* 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();
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.setForeground(new Color(204, 0, 255));
txtmsp = new JTextField();
txtmsp.setBackground(new Color(51, 255, 51));
txtmsp.setColumns(10);
txtsp = new JTextField();
txtsp.setBackground(new Color(51, 255, 51));
txtsp.setColumns(10);
lblNhapTenlop = new JLabel("Tên sản phẩm");
lblNhapTenlop.setForeground(new Color(204, 0, 255));
JButton btnthem = new JButton("Th\u00EAm");
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.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.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.setForeground(new Color(204, 0, 255));
JLabel lblNewLabel_1_1 = new JLabel("Đơn giá");
lblNewLabel_1_1.setForeground(new Color(204, 0, 255));
txtgia = new JTextField();
txtgia.setBackground(new Color(51, 255, 51));
txtgia.setColumns(10);
comboBox = new JComboBox();
comboBox.setForeground(new Color(204, 0, 255));
comboBox.setBackground(new Color(51, 255, 51));
txttimkiem = new JTextField();
txttimkiem.setBackground(new Color(255, 255, 0));
txttimkiem.setColumns(10);
//** _Đoạn này có thể là bị sai chổ đó_**
txttimkiem.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(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 LIKE '%" + txttimkiem.getText() + "%'";
//PreparedStatement st=conn.prepareStatement(query);
//st.setString(1,txttimkiem.getText());
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
table_2.setModel(DbUtils.resultSetToTableModel(rs));
conn.close();
}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.setForeground(new Color(255, 51, 102));
lbl_image = new JLabel("");
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.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.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.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();
}
});
mnNewMenu.add(mntmNewMenuItem_2);
JMenuItem mntmNewMenuItem_3 = new JMenuItem("Đăng xuất");
mntmNewMenuItem_3.setBackground(Color.WHITE);
mntmNewMenuItem_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new logindatabase();
}
});
mnNewMenu.add(mntmNewMenuItem_3);
JMenu mnNewMenu_1 = new JMenu("Bảng quản lý bán hàng");
mnNewMenu_1.setBackground(Color.WHITE);
menuBar.add(mnNewMenu_1);
JMenuItem mntmNewMenuItem = new JMenuItem("Khách hàng");
mntmNewMenuItem.setBackground(Color.WHITE);
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
new Succes();
}
});
mnNewMenu_1.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Sản phẩm");
mntmNewMenuItem_1.setBackground(Color.WHITE);
mnNewMenu_1.add(mntmNewMenuItem_1);
JLabel lblNewLabel_3 = new JLabel("");
lblNewLabel_3.setBackground(new Color(51, 51, 255));
lblNewLabel_3.setIcon(new ImageIcon("C:\\doanngoctin\\admin.jpg"));
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(menuBar, GroupLayout.PREFERRED_SIZE, 764, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(95)
.addComponent(txtmsp, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(95)
.addComponent(txtsp, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
.addComponent(lblNhapTenlop, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE)))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(lblNewLabel_1, GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(lblNewLabel_1_1, GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(29)
.addComponent(btnthem, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
.addGap(23)
.addComponent(btnXoa, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(lblNewLabel_2, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
.addGap(23)
.addComponent(btnreset, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
.addGap(20)
.addComponent(lbl_image, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE)
.addGap(74)
.addComponent(btnimage, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(117)
.addComponent(txtgia, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(240)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 514, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(29)
.addComponent(btnSua, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(117)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(110)
.addComponent(txttimkiem, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE))
.addComponent(lblNewLabel_3, GroupLayout.PREFERRED_SIZE, 764, GroupLayout.PREFERRED_SIZE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(menuBar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(5)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(3)
.addComponent(lblNewLabel))
.addComponent(txtmsp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(14)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(txtsp, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(3)
.addComponent(lblNhapTenlop)))
.addGap(16)
.addComponent(lblNewLabel_1)
.addGap(37)
.addComponent(lblNewLabel_1_1)
.addGap(43)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnthem)
.addComponent(btnXoa))
.addGap(11)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(66)
.addComponent(lblNewLabel_2))
.addGroup(groupLayout.createSequentialGroup()
.addGap(13)
.addComponent(btnreset))
.addComponent(lbl_image, GroupLayout.PREFERRED_SIZE, 139, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(62)
.addComponent(btnimage))))
.addGroup(groupLayout.createSequentialGroup()
.addGap(145)
.addComponent(txtgia, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(27)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(252)
.addComponent(btnSua))
.addGroup(groupLayout.createSequentialGroup()
.addGap(92)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(302)
.addComponent(txttimkiem, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(lblNewLabel_3, GroupLayout.PREFERRED_SIZE, 389, GroupLayout.PREFERRED_SIZE)
);
frame.getContentPane().setLayout(groupLayout);
}
}