Hot questions for Using JTextField in database

Question:

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)


Answer:

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.

Question:

Whenever I add values in database through JtexField it saves extra spaces in the sql database is there any way to restrict wide spaces and save only the text added in TextField?

try {
  String query = "insert into items (item_name, category_id, item_price, item_description, stock) Values (?,?,?,?,?) ;";
  PreparedStatement pst = con.prepareStatement(query);
  pst.setString(1, textField_1.getText());
  pst.setString(2, textField_2.getText());
  pst.setString(3, textField_3.getText());
  pst.setString(4, textField_4.getText());
  pst.setString(5, textField_5.getText());

  pst.execute();
  JOptionPane.showMessageDialog(null, "Data Saved");
  pst.close();
 } catch (Exception e) {
  e.printStackTrace();
 }

spaces like this

Trim function


Answer:

Eliminates leading and trailing spaces:

  1. Using String's trim() method

    textField_1.getText().trim();

  2. Using Regex

    textField_1.getText().replaceAll("^\\s+|\\s+$", "");

Question:

I am creating a small database that can store the records of my job numbers. I want to start each job number with 2 zeros (00) and then put the number of the job after. Like this "001-2019". When I go to query the database, it doesnt work. But if I get rid of the zeros and get rid of any special characters, it works fine. How can I use the zeros and special characters to query the database?

        btnOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                String jobNumber = txtJobNumber.getText();
                String sql = "SELECT Date FROM JOBCOSTS where Job_Number =" +jobNumber;
                try {
                    pst=conn.prepareStatement(sql);
                    rs = pst.executeQuery();
                    if(rs.next()) {
                    String date=rs.getString("Date");
                    txtJobCostDate.setText(date);

                    }
                }catch (Exception e) {
                    JOptionPane.showMessageDialog(null, e);

                }
            }
        });

Answer:

First try using parametarized query since you are already using Prepared statements.

String sql = "SELECT Date FROM JOBCOSTS where Job_Number = ?";
pst=conn.prepareStatement(sql);
pst.setString(1, jobNumber);

Second, is your jobNumber should be in string so your leading zeroes will not be truncated.

btnOpen.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        String jobNumber = txtJobNumber.getText();
        String sql = "SELECT Date FROM JOBCOSTS where Job_Number ='" +jobNumber+"'";
        try {
            pst=conn.prepareStatement(sql);
            rs = pst.executeQuery();
            if(rs.next()) {
            String date=rs.getString("Date");
            txtJobCostDate.setText(date);

            }
        }catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);

        }
    }
});

Question:

I have write program that program have 2 frame one frame to add item and save to database in another frame I have to select the item which is add in first frame in JComboBox I write that code for insert data into database but I don't know how to display in JComboBox

try {
    String host = "jdbc:derby://localhost:1527/PROCAT";
    String uName = "zain";
    String uPass = "zain";
    con = DriverManager.getConnection(host, uName, uPass);
    String m = "insert into ITEMB (ITEM,ITEMNAME,PRISE) values(?,?,?)";
    ps = con.prepareStatement(m);
    ps.setInt(1, Integer.parseInt(jTextField3.getText()));
    ps.setString(2, jTextField2.getText());
    ps.setString(3, jTextField4.getText());
    ps.executeUpdate();
    JOptionPane.showMessageDialog(null, "record saved");
} catch (Exception ex) {
    JOptionPane.showMessageDialog(null, ex);
}

This for JComboBox:

try
{

    String host = "jdbc:derby://localhost:1527/PROCAT";
    String uName = "zain";
    String uPass = "zain";
    con = DriverManager.getConnection(host,uName,uPass);

    st = con.createStatement();
    rs = st.executeQuery("select ITEMNAME from ITEMB;");
    while (rs.next()) {
        jCom.addItem(rs.getString("ITEMNAME"));
    }

 }
 catch(Exception ex) {
     JOptionPane.showMessageDialog(null,ex);
 }

Answer:

On my understanding, there are 2 frames. One of them is for viewing records and has the JComboBox, the other one is for inserting records and has the JTextField.

The default frame would be the one with the JComboBox. If you want to add a new record into the JComboBox, a frame will appear for adding of records.

Once the INSERT statements are issued, the frame with the JTextField will be closed and the frame with the JComboBox will appear showing the newly added records.

You can provide a Reload button for deleting the items inside the JComboBox and then reloading the data using the SELECT statement.

while (rs.next()) {
    jComboBox.addItem(rs.getString("ITEMNAME"));
}

And then, use

jComboBox.repaint();

Question:

my problem here is that if i try to leave blank spaces in my app, this code inserts an empty string into database on lines txtIme.getText() and txtPrezime.getText() and for that reason my if statement doesn't recognize .executeUpdate() as 0 and therefore doesn't print that nothing has been changed. Can I somehow change it so the app can reach my if statement if blank spaces are left in JTextField? Thank you.

    private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {

        izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");

        izraz.setString(1, txtIme.getText());
        izraz.setString(2, txtPrezime.getText());



        if (izraz.executeUpdate()== 0) {
            JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");

        } else {
            ucitajIzBaze();
            ocistiPolja();
        }

        izraz.close();

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

}                          

Answer:

In case you dont want to use any lib

private void btnDodajActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {

        if(txtIme.getText() == null || "".equals(txtIme.getText())) return;
        if(txtPrezime.getText() == null || "".equals(txtPrezime.getText())) return;
        izraz = veza.prepareStatement("insert into autor (ime,prezime)" + "value (?,?)");


        izraz.setString(1, txtIme.getText());
        izraz.setString(2, txtPrezime.getText());



        if (izraz.executeUpdate()== 0) {
            JOptionPane.showMessageDialog(getRootPane(), "Nothing was changed.");

        } else {
            ucitajIzBaze();
            ocistiPolja();
        }

        izraz.close();

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

}    

But I recommend use any library for string related operations like

if(StringUtils.isBlank(txtIme.getText())) return;
if(StringUtils.isBlank(txtPrezime.getText())) return;

It in apache common lang package.