Hot questions for Using JTextField in mysql

Question:

I am trying to form a simple login database with SQL (mySQL workbench) and Java (Eclipse). I am not sure how to test the string input (JTextField and JPasswordField) against the database in SQL on even against any other strings.

I would like Java to print a statement out if the login credentials are equal to specified strings. Here is my current code:

import javax.swing.*;
import java.sql.*;


public class Hello1 extends JFrame {




private static final long serialVersionUID = 1487932324102279819L;


public static void main(String[] args) {

    JFrame frame = new JFrame("Frame Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(350,200);



    JPanel panel = new JPanel();
    frame.add(panel);
    placeComponents(panel);

    frame.setVisible(true);

    String username0 = "java";
    String password = "password";

    Statement stmt = null;
    try{
        String url = "jdbc:mysql://localhost:3306/javabase?useSSL=false";
        Connection connection = DriverManager.getConnection(url, username0, password);
        stmt = connection.createStatement();
        ResultSet rs;
        rs = stmt.executeQuery("SELECT * from userids ");
        while(rs.next()) {
            String user = rs.getString("username");
            String pass = rs.getString("paswrd");
            System.out.println(user);
            System.out.println(pass);
        }
        connection.close();

        }

        catch (Exception e) {
             System.err.println("Got an exception! ");
             System.err.println(e.getMessage());
        }
     }



private static void placeComponents(JPanel panel) {

    panel.setLayout(null);
    JLabel userLabel = new JLabel("Username");
    userLabel.setBounds(10,20,80,25);
    panel.add(userLabel);

    JTextField userText = new JTextField(20);
    userText.setBounds(100, 20, 165, 25);
    panel.add(userText);
    String user = userText.getText();       

    JLabel passwordLabel = new JLabel("Password");
    passwordLabel.setBounds(10,50,80,25);
    panel.add(passwordLabel);

    JPasswordField passwordText = new JPasswordField(20);
    passwordText.setBounds(100,50,165,25);
    panel.add(passwordText);
    String pass = passwordText.getSelectedText();

    if(user.equals('b') && pass.equals('t')){
        System.out.println("Correct Login");
    }
    System.out.println(pass);

    JButton loginB = new JButton("Login");
    loginB.setBounds(10, 80, 80, 25);
    panel.add(loginB);


}

}

I have tried getting the text in each userText/passwordText by using the .getText() and .getSelectedText() methods.


Answer:

If I understand correctly, then you need to get password when you click on the Login button.

Please add below code in placeComponents method after initializing the button.

loginB.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            char[] pass = passwordText.getPassword();
            System.out.println(pass);
        }
    });

Action listeners are probably the easiest — and most common — event handlers to implement. You implement an action listener to define what should be done when an user performs certain operation.

You can read more on ActionListener here.

You can refer this example to see how to use password field.

Question:

I'm a rookie in the java language, but i'm trying to create a search function for a mysql database. I've managed to get the search function working with a defined string, but i have no idea how a automatic generated jtextfield works or how they can connect it to an auto generated jbutton.

here is my code for the jtextfield and jbutton:

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            

   //  jTextField1.addActionListener(this);

} 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

   jTextField1.getText();
   jComboBox1.getSelectedItem().toString();

    try {
        Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb");

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mmm WHERE "+jComboBox1+" = '"+jTextField1+"'");

    while (rs.next()) {
            System.out.println("\t" + rs.getString(2) + "\t" + rs.getString(3)+ "\t" + rs.getString(4));
        }
        rs.close();

    } catch (SQLException e) {
        System.out.println(e);
    }

}                    

Like i said, i don't have any idea what to insert into the jtextfield or how to get the inserted data towards the jbutton.

I would be very grateful if anyone can help me, since an answer to this question can also completely finish my insert function for adding to the database.

Already thanks for reading,

Molnaris


Answer:

You can redirect the text field action to the button using something like..

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            

   jButton1ActionPerformed(evt)

} 

This means that when the user presses Enter, it will also trigger a search, which is a nice feature

You need to assign the values returned by the text field and combobox ...

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

   String text = jTextField1.getText();
   String combo =jComboBox1.getSelectedItem().toString();

    try {
        Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb");

        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM mmm WHERE "+combo+" = '"+text+"'");

    while (rs.next()) {
            System.out.println("\t" + rs.getString(2) + "\t" + rs.getString(3)+ "\t" + rs.getString(4));
        }
        rs.close();

    } catch (SQLException e) {
        System.out.println(e);
    }

}                    

Having said that, I'd strongly encourage you to use a PreparedStatement instead

PreparedStatement stmt = con.prepareStatement("SELECT * FROM mmm WHERE ? = ?");
stmt.setString(1, combo);
stmt.setString(2, text);
ResultSet rs = stmt.executeQuery();

See Using PreparedStatements for more details

You also not managing your resources very well, you should ensure that you are closing the various resources when you have finished with them...

try (Connection con = DriverManager.getConnection("jdbc:ucanaccess://C:/Michel's Muziek Magazijn.accdb")) {
    try (PreparedStatement stmt = con.prepareStatement("SELECT * FROM mmm WHERE ? = ?")) {
        try (ResultSet rs = stmt.executeQuery()) {
            //...
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Take a look at The try-with-resources Statement for more details

Question:

I try to create point of sale program that connected to MySQL database. I have one JTable to display the item serial and item name and price I want to get sum of total price in jTextField8 as total I write the following:

try {
        String sql = "Select * from ITEMB where ITEM =13";
        stmt = con.createStatement();

        rs = stmt.executeQuery(sql);

        while (rs.next()) {
            String myNamatxt = rs.getString("PRISE");
            String myHargatxt = rs.getString("ITEMNAME");
            String satuan = rs.getString("ITEM");
            String[] data = {myNamatxt, myHargatxt, satuan,};
            tabMode.addRow(data);
            double price = Double.parseDouble(rs.getString("prise"));
            totalpay = price + totalpay;
            ++rowcount;
        }
    } catch (Exception e) {
        //ignore
    }
    jTextField8.setText(String.valueOf(totalpay));
}

When I try to start new bill, the text field doesn't return to zero and start by total of previous bill.


Answer:

Reset totalPay to 0 before when you need to re-load values or create a new bill

Question:

I have been trying to add a table rows' info to JTextField components after clicking with the mouse however it doesn't work. I have used the DefaultTableModel and JTable as shown below.

Here is the code I have been using.

package scrCode;

import java.util.*;
import java.sql.*;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.proteanit.sql.DbUtils;

import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComboBox;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BorrowABook extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private JButton button;
    private JLabel lblBookId;
    private JTextField textFieldBookID;
    private JLabel lblMemberId;
    private JTextField textFieldMemberID;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BorrowABook frame = new BorrowABook();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public BorrowABook() {
        setTitle("Library system");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 971, 594);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        String data [][]=null;
        String column []=null;
        DefaultTableModel model = new DefaultTableModel();
        try {
            //code to receive data from the database 
            Connection con=DB.login();
            PreparedStatement ps=con.prepareStatement("select * from book",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            ResultSet rs=ps.executeQuery();

            ResultSetMetaData rsmd=rs.getMetaData();
            int cols=rsmd.getColumnCount();
            column=new String[cols];
            for(int i=1;i<=cols;i++){
                column[i-1]=rsmd.getColumnName(i);
            }

            rs.last();
            int rows=rs.getRow();
            rs.beforeFirst();

            data=new String[rows][cols];
            int count=0;
            while(rs.next()){
                for(int i=1;i<=cols;i++){
                    data[count][i-1]=rs.getString(i);
                }
                count++;
            }
            con.close();


        }catch (Exception e){
            System.out.println(e);
        }
        contentPane.setLayout(null);

        table = new JTable(data,column);
        JScrollPane sp = new JScrollPane(table);
        sp.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                int selectedRowIndex = table.getSelectedRow();              
                textFieldBookID.setText(model.getValueAt(selectedRowIndex, 0).toString());
                textFieldMemberID.setText(model.getValueAt(selectedRowIndex, 1).toString());



            }
        });
        sp.setBounds(5, 5, 936, 402);
        contentPane.add(sp);

        button = new JButton("Back");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UserSection.main(new String [] {});
                dispose();
            }
        });
        button.setForeground(Color.BLACK);
        button.setBackground(SystemColor.info);
        button.setBounds(856, 509, 85, 25);
        contentPane.add(button);

        lblBookId = new JLabel("Book ID:");
        lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblBookId.setBounds(28, 420, 141, 29);
        contentPane.add(lblBookId);

        textFieldBookID = new JTextField();
        textFieldBookID.setColumns(10);
        textFieldBookID.setBounds(181, 420, 257, 29);
        contentPane.add(textFieldBookID);

        lblMemberId = new JLabel("Memeber ID:");
        lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblMemberId.setBounds(28, 469, 141, 29);
        contentPane.add(lblMemberId);

        textFieldMemberID = new JTextField();
        textFieldMemberID.setColumns(10);
        textFieldMemberID.setBounds(181, 469, 257, 29);
        contentPane.add(textFieldMemberID);
    }
}

Answer:

Suggestions:

  • Add your MouseListener to your JTable, not to the JScrollPane. You need notification for when the table has been clicked.
  • You're using the wrong model in your listener as you never fill the DefaultTableModel with data. Be safe and get the model in the listener via table.getModel()
  • No null layouts. While this is not causing your current problem, it forces you to code against the library rather than with it.

For example (database code removed for simplicity, null layout removed as well, and posted a MCVE):

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

public class BorrowABook extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private JButton button;
    private JLabel lblBookId;
    private JTextField textFieldBookID;
    private JLabel lblMemberId;
    private JTextField textFieldMemberID;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BorrowABook frame = new BorrowABook();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public BorrowABook() {
        setTitle("Library system");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 971, 594);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        String data[][] = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};
        String column[] = {"One", "Two", "Three" };
        DefaultTableModel model = new DefaultTableModel();
        // !! contentPane.setLayout(null);
        contentPane.setLayout(new BorderLayout());

        table = new JTable(data, column);
        JScrollPane sp = new JScrollPane(table);
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {

                int selectedRowIndex = table.getSelectedRow();
                textFieldBookID.setText(table.getModel().getValueAt(selectedRowIndex, 0).toString());
                textFieldMemberID.setText(table.getModel().getValueAt(selectedRowIndex, 1).toString());
            }
        });
        //!! sp.setBounds(5, 5, 936, 402);
        contentPane.add(sp);

        JPanel bottomPanel = new JPanel();

        lblBookId = new JLabel("Book ID:");
        lblBookId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblBookId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        bottomPanel.add(lblBookId);

        textFieldBookID = new JTextField();
        textFieldBookID.setColumns(10);
        textFieldBookID.setBounds(181, 420, 257, 29);
        bottomPanel.add(textFieldBookID);

        lblMemberId = new JLabel("Memeber ID:");
        lblMemberId.setHorizontalAlignment(SwingConstants.RIGHT);
        lblMemberId.setFont(new Font("Sitka Display", Font.BOLD, 22));
        lblMemberId.setBounds(28, 469, 141, 29);
        bottomPanel.add(lblMemberId);

        textFieldMemberID = new JTextField();
        textFieldMemberID.setColumns(10);
        textFieldMemberID.setBounds(181, 469, 257, 29);
        bottomPanel.add(textFieldMemberID);

        contentPane.add(bottomPanel, BorderLayout.PAGE_END);
    }
}

Question:

I have a JTextField named for Reservation ID on JFrame connected to MySQL database. Whenever I add a new passenger in the database, the JTextField should automatically generate a new Reservation ID for me in the JTextField based on an auto increment before I enter the passenger names and other details in the other textfields.

My code:

    resId = new JTextField();
    try{
        rs = stt.executeQuery("select ReservID as last_id from passenger");
        int lastid = rs.getInt("last_id");
        lastid++;
        resId.setText(String.valueOf(last_id));

    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "cannot retrieve");
    }
    resId.setBounds(432, 178, 126, 22);
    frame.getContentPane().add(resId);
    resId.setColumns(10);

The last row of my column RevervID has value of 003. When I run the form, it should display me 004 in the Reservation ID textfield How do I achieve that ? Please help.. Thanks

The texfield in the image link below http://i.imgbox.com/wcf9KicU.png


Answer:

First find out the maximum id using database query-> Select max(id) from mytable

Store the maximum id in a variable-> int max_id= max_id_from_database;

Increment max_id by one-> max_id++;

add max_id value to your JTextField-> myJTextField.setText("" + max_id);

Edited: According to your code (just add max before ReservID and add rs.next() in a if condition and ReservID must be integer in your database).

 resId = new JTextField();
    try{
        rs = stt.executeQuery("select max(ReservID) as last_id from passenger");
        if(rs.next()){
        int lastid = rs.getInt("last_id");
        lastid++;
        resId.setText(String.valueOf(last_id));
        }

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