gpt4 book ai didi

java - JTable 过滤数据无法正常工作

转载 作者:行者123 更新时间:2023-12-01 21:09:36 30 4
gpt4 key购买 nike

我正在开发一个项目“图书馆管理系统”,一切都很好,直到我遇到了一个我无法解决的问题。

我有一个 GUI(附有屏幕截图)应用程序,它从数据库表中获取数据,然后在 JTable 中显示结果。我在 JTextField 上应用了过滤器,以根据用户输入的数据过滤 JTable 的数据。

我遇到的错误是我有一个 JButton,它应该再次显示数据库中的所有数据并清除 JTextField。 JButton 正在清除 JTextField,但不会在 JTable 中再次显示数据库中的数据。

应用程序 GUI 屏幕截图和代码如下:

App Screenshot

我只有两个类Login(主)类和Home类,均如下所示:

登录(主)类:

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);
}
}

家庭类

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);
}
}

这是我的 SQL Server 2012 数据库架构:

Schema

我的数据库中仅存在这些记录(仅在图书表中)

enter image description here

最佳答案

您的 btnShowBooks 处理程序清除文本字段,使用 DbUtils 重建表模型,并使用 setModel 将新模型应用到 tableBooks ()。不幸的是,该表使用的是旧过滤器,而旧过滤器使用的是旧模型。因为 RowFilter 会影响 View ,所以可能根本不需要重建表模型;无论哪种情况,您都可以简单地清除过滤器:

tableBooks.setRowSorter(null);

作为引用,这个完整的example展示如何在不重建 TableModel 的情况下原位切换 RowFilter。按照建议here ,不要在 textFieldSearch 上使用 KeyListener。相反,添加 DocumentListener聆听变化。使用 layout 而不是 setBounds()避免如图所示的问题here .

关于java - JTable 过滤数据无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413795/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com