I am working on a project "Library Management System", everything was fine till I got a problem which I am unable to figure out.
I have a GUI(Screenshot attached) App that is getting data from database table and then show the result in a JTable. I have applied a filter on the JTextField to filter the data of JTable on the basis of data entered by user.
The error I am having is that I have a JButton that should show all the data again from database and clear the JTextField. The JButton is clearing the JTextField but not showing the data from database again in JTable.
App GUI screenshot and Code is below:
I have only two classes Login
(main) class and Home
class both are shown below:
Login (main) class:
package com.softoak.lms;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Login {
private JFrame frmLibraryManagementSystem;
private JTextField textField;
private JPasswordField passwordField;
JComboBox<String> comboBox;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
Login window = new Login();
window.frmLibraryManagementSystem.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() throws Exception {
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=LMS;integratedSecurity=true");
initialize();
}
public void actionLogin() {
String query = "SELECT * FROM LMSAdmin WHERE Username = ? AND Password = ?";
try {
ps = con.prepareStatement(query);
ps.setString(1, textField.getText());
char[] pwd = passwordField.getPassword();
String password = String.valueOf(pwd);
ps.setString(2, password);
rs = ps.executeQuery();
if (rs.next()) {
frmLibraryManagementSystem.dispose();
new Home().frame.setVisible(true);
JOptionPane.showMessageDialog(null, "Welcome ! ! !\nYou Are Logged In", "Welcome",
JOptionPane.INFORMATION_MESSAGE);
} else if (textField.getText().length() == 0 || password.length() == 0) {
JOptionPane.showMessageDialog(null, "Fields Should Not Be Empty ! ! !", "Error",
JOptionPane.WARNING_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Wrong Username or Password", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmLibraryManagementSystem = new JFrame();
frmLibraryManagementSystem.setTitle("Library Management System - Login");
frmLibraryManagementSystem.setSize(1366, 726);
frmLibraryManagementSystem.setLocationRelativeTo(null);
frmLibraryManagementSystem.setResizable(false);
frmLibraryManagementSystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmLibraryManagementSystem.getContentPane().setLayout(null);
JLabel LoginLock = new JLabel("");
Image imageloginlock = new ImageIcon(this.getClass().getResource("/LoginLock.png")).getImage();
Image imageFrame = new ImageIcon(this.getClass().getResource("/LMS Frame Icon.png")).getImage();
frmLibraryManagementSystem.setIconImage(imageFrame);
JButton btnExit = new JButton("EXIT");
btnExit.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
int i = JOptionPane.showConfirmDialog(null, "Are You Sure You Want To Exit", "Exit",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
}
});
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = JOptionPane.showConfirmDialog(null, "Are You Sure You Want To Exit", "Exit",
JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (i == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
String[] lafoptions = { "Windows", "Nimbus", "Motif" };
comboBox = new JComboBox(lafoptions);
comboBox.setFocusable(false);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (comboBox.getSelectedIndex() == 0) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException exe) {
JOptionPane.showMessageDialog(null, exe.getMessage());
}
SwingUtilities.updateComponentTreeUI(frmLibraryManagementSystem);
} else if (comboBox.getSelectedIndex() == 1) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException exe) {
JOptionPane.showMessageDialog(null, exe.getMessage());
}
SwingUtilities.updateComponentTreeUI(frmLibraryManagementSystem);
} else if (comboBox.getSelectedIndex() == 2) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException exe) {
JOptionPane.showMessageDialog(null, exe.getMessage());
}
SwingUtilities.updateComponentTreeUI(frmLibraryManagementSystem);
}
}
});
comboBox.setBounds(1198, 11, 145, 26);
frmLibraryManagementSystem.getContentPane().add(comboBox);
btnExit.setFont(new Font("Consolas", Font.BOLD, 16));
btnExit.setBounds(681, 355, 100, 29);
frmLibraryManagementSystem.getContentPane().add(btnExit);
JButton btnLogin = new JButton("LOGIN");
btnLogin.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
actionLogin();
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionLogin();
}
});
btnLogin.setFont(new Font("Consolas", Font.BOLD, 16));
btnLogin.setBounds(578, 355, 100, 29);
frmLibraryManagementSystem.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
actionLogin();
}
}
});
passwordField.setBounds(578, 313, 203, 30);
frmLibraryManagementSystem.getContentPane().add(passwordField);
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
actionLogin();
}
}
});
textField.setBounds(578, 271, 203, 30);
frmLibraryManagementSystem.getContentPane().add(textField);
textField.setColumns(10);
JLabel labelPassword = new JLabel("Password");
labelPassword.setFont(new Font("Copperplate Gothic Bold", Font.PLAIN, 20));
labelPassword.setBounds(441, 318, 129, 25);
frmLibraryManagementSystem.getContentPane().add(labelPassword);
JLabel labelUsername = new JLabel("Username");
labelUsername.setFont(new Font("Copperplate Gothic Bold", Font.PLAIN, 20));
labelUsername.setBounds(441, 276, 125, 25);
frmLibraryManagementSystem.getContentPane().add(labelUsername);
JLabel labelTitle = new JLabel("Library Management System");
labelTitle.setFont(new Font("Cooper Black", Font.BOLD, 34));
labelTitle.setBounds(396, 96, 567, 38);
frmLibraryManagementSystem.getContentPane().add(labelTitle);
LoginLock.setIcon(new ImageIcon(imageloginlock));
LoginLock.setBounds(924, 206, 256, 226);
frmLibraryManagementSystem.getContentPane().add(LoginLock);
JLabel labelLogin = new JLabel("Login");
labelLogin.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 30));
labelLogin.setBounds(622, 206, 115, 38);
frmLibraryManagementSystem.getContentPane().add(labelLogin);
JLabel lblSoftoak = new JLabel("");
Image image = new ImageIcon(this.getClass().getResource("/SoftOak Logo.jpeg")).getImage();
lblSoftoak.setIcon(new ImageIcon(image));
lblSoftoak.setBounds(988, 647, 172, 50);
frmLibraryManagementSystem.getContentPane().add(lblSoftoak);
JLabel lblCopyright = new JLabel("Copyright \u00A9 2016 Library Management System Developed By");
lblCopyright.setFont(new Font("Consolas", Font.BOLD, 20));
lblCopyright.setBounds(377, 669, 605, 24);
frmLibraryManagementSystem.getContentPane().add(lblCopyright);
JLabel lblBackground = new JLabel("");
lblBackground.setBackground(Color.BLACK);
lblBackground.setForeground(Color.WHITE);
Image imagebackground = new ImageIcon(this.getClass().getResource("/Background.jpg")).getImage();
lblBackground.setIcon(new ImageIcon(imagebackground));
lblBackground.setBounds(0, 0, 1366, 726);
frmLibraryManagementSystem.getContentPane().add(lblBackground);
}
}
Home Class
package com.softoak.lms;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import net.proteanit.sql.DbUtils;
public class Home {
public JFrame frame;
private JTable tableBooks;
private JTextField textFieldSearch;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
TableModel tm;
TableRowSorter<TableModel> sorter;
/**
* Create the application.
*/
public Home() throws Exception {
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=LMS;integratedSecurity=true");
initialize();
getAllBooks();
}
public void getAllBooks(){
try {
String query = "SELECT ISBN, BookTitle AS 'Book Title', DateOfPublication AS 'Publication Date' FROM Books";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
tableBooks.setModel(DbUtils.resultSetToTableModel(rs));
tm = tableBooks.getModel();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
public void filterTable(){
sorter = new TableRowSorter<TableModel>(tm);
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + textFieldSearch.getText()));
tableBooks.setRowSorter(sorter);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Library Management System - Home");
frame.setSize(1366, 726);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblBackground = new JLabel("");
Image imagebackground = new ImageIcon(this.getClass().getResource("/Background.jpg")).getImage();
Image imageFrame = new ImageIcon(this.getClass().getResource("/LMS Frame Icon.png")).getImage();
frame.setIconImage(imageFrame);
JButton btnshowBooks = new JButton("Show All Books");
btnshowBooks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFieldSearch.setText("");
try {
String query = "SELECT ISBN, BookTitle AS 'Book Title', DateOfPublication AS 'Publication Date' FROM Books";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
tableBooks.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
textFieldSearch = new JTextField();
textFieldSearch.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
filterTable();
}
});
textFieldSearch.setBounds(422, 82, 590, 29);
frame.getContentPane().add(textFieldSearch);
textFieldSearch.setColumns(10);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 1350, 28);
frame.getContentPane().add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmAddNewBook = new JMenuItem("Add New Book");
mntmAddNewBook.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
mnFile.add(mntmAddNewBook);
JMenu mnAbout = new JMenu("Help");
menuBar.add(mnAbout);
JMenuItem mntmAboutUs = new JMenuItem("About Us");
mntmAboutUs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK));
mntmAboutUs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon(getClass().getResource("/SoftOak Logo.jpeg"));
JOptionPane.showMessageDialog(null,
"Library Management System\nDeveloped By Softoak\nFor Any Questions Contact: Chaudary Usman",
"About Us", JOptionPane.INFORMATION_MESSAGE, icon);
}
});
mnAbout.add(mntmAboutUs);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(422, 122, 842, 475);
frame.getContentPane().add(scrollPane);
tableBooks = new JTable();
scrollPane.setViewportView(tableBooks);
tableBooks.setModel(new DefaultTableModel(new Object[][] {}, new String[] {}));
btnshowBooks.setBounds(1022, 82, 242, 30);
frame.getContentPane().add(btnshowBooks);
JLabel labelTitle = new JLabel("Library Management System");
labelTitle.setFont(new Font("Cooper Black", Font.BOLD, 34));
labelTitle.setBounds(391, 39, 567, 38);
frame.getContentPane().add(labelTitle);
lblBackground.setIcon(new ImageIcon(imagebackground));
lblBackground.setBounds(0, 0, 1350, 687);
frame.getContentPane().add(lblBackground);
}
}
Here is my Database Schema of SQL server 2012:
I have only theses records present in my database(only in Books table)
Your btnShowBooks
handler clears the text field, rebuilds the table model using DbUtils
and applies the new model to tableBooks
using setModel()
. Unfortunately, the table is using the old filter and the old filter is using the old model. Because a RowFilter
affects the view, it may not be necessary reconstruct the table model at all; in either case, you can simply clear the filter:
tableBooks.setRowSorter(null);
For reference, this complete example shows how to toggle a RowFilter
in situ, without rebuilding the TableModel
. As suggested here, don't use KeyListener
on textFieldSearch
. Instead, add a DocumentListener
to listen for changes. Instead of setBounds()
, use a layout to avoid the problem illustrated here.