Je travaille sur un projet "Système de gestion de bibliothèque", tout allait bien jusqu'à ce que j'ai un problème que je suis incapable de comprendre.JTable filtre données ne fonctionne pas correctement
J'ai une application GUI (Capture d'écran ci-jointe) qui obtient des données de la table de base de données, puis affiche le résultat dans un JTable. J'ai appliqué un filtre sur le JTextField pour filtrer les données de JTable sur la base des données saisies par l'utilisateur. L'erreur que j'ai est que j'ai un JButton qui devrait montrer toutes les données de nouveau à partir de la base de données et effacer le JTextField. JButton efface le JTextField mais ne montre plus les données de la base de données dans JTable.
capture d'écran GUI App et le code est ci-dessous:
J'ai que deux classes Connexion (Principal) classe et classe d'accueil les deux sont donnés ci-dessous:
Login (Principal) Classe
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);
}
}
Accueil Classe
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 Qeries 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);
}
}
Voici mon schéma de base de données du serveur SQL 2012:
Je thèses que les enregistrements présents dans ma base de données (uniquement dans le tableau Livres)
Oublié de mentionner J'utilise rs2xml.jar pour créer le modèle de table. –
* "J'ai oublié de mentionner que j'utilise rs2xml.jar .." * Puisque le problème semble être le filtrage des données dans un 'JTable', éliminez l'accès DB et les API externes et codez simplement certaines données dans le code source. Ou pour mettre ça autrement. Pour une meilleure assistance plus tôt, publiez un [MCVE] ou [Short, Self Contained, Example correct] (http://www.sscce.org/). –
Oh, et à propos de 'frame.getContentPane(). SetLayout (null);' Les interfaces graphiques Java doivent fonctionner sur différents OS ', la taille de l'écran, la résolution de l'écran, etc.en utilisant différents PLAFs dans différentes locales. En tant que tels, ils ne sont pas propices à la mise en page pixel parfait. Utilisez plutôt des gestionnaires de disposition, ou [des combinaisons de ceux-ci] (http://stackoverflow.com/a/5630271/418556) avec un remplissage de mise en page et des bordures pour [espace blanc] (http://stackoverflow.com/a/17874718/ 418556). –