JTable过滤器数据无法正常工作

时间:2017-01-01 06:32:54

标签: java database swing jtable jtextfield

我正在开展一个项目"图书馆管理系统"一切都很好,直到我遇到一个我无法弄清楚的问题。

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

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

App 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

1 个答案:

答案 0 :(得分:3)

您的btnShowBooks处理程序清除文本字段,使用DbUtils重建表格模型,并使用tableBooks将新模型应用于setModel()。不幸的是,该表使用旧过滤器,旧过滤器使用旧模型。因为RowFilter影响视图,所以可能根本不需要重建表模型;在任何一种情况下,您都可以简单地清除过滤器:

tableBooks.setRowSorter(null);

作为参考,这个完整的example显示了如何在不重建RowFilter的情况下切换TableModel in situ 。根据建议here,请勿在{{1​​}}上使用KeyListener。而是添加DocumentListener来监听更改。使用layout代替textFieldSearch,以避免显示问题here