skip to Main Content

I have tried to populate the table but not working this is the code.
i am creating a small application to insert delete update my customer management system

i have the execution for the records table to get the data from the database. everything is running on my code there are no errors but my jtable is still not showing the data from my database.


package javaapplication16;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;

public class NewJFrame extends javax.swing.JFrame {

     private static final String DB_URL = "jdbc:mysql://localhost:3306/customer database?zeroDateTimeBehavior=CONVERT_TO_NULL";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "";
    
    Connection sqlConn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    int q, i, id, deleteItem;
    
    public NewJFrame() {
        initComponents();
    }
private void initializeDB()  {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        sqlConn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        pst = sqlConn.prepareStatement("SELECT * FROM customer database");
        rs = pst.executeQuery();
        ResultSetMetaData stData = rs.getMetaData();
        q= stData.getColumnCount();
        DefaultTableModel RecordTable = (DefaultTableModel)jTable2.getModel();
                RecordTable.setRowCount(0);
                while(rs.next()){
                     obj columnData = new obj ();
                    for (i= 1; i<=q; i++){
                        columnData.add(rs.getString("id"));
                       columnData.add(rs.getString("name"));
                       columnData.add(rs.getString("age"));
                       columnData.add(rs.getString("order_number"));
                    }
                    RecordTable.addRow(columnData);
                }
    }
    catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
}

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
   

    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {                                     
      DefaultTableModel RecordTable = (DefaultTableModel)jTable2.getModel();
               int SelectedRows = jTable2.getSelectedRow();
               
               txtID.setText(RecordTable.getValueAt(SelectedRows, 1).toString());
               txtName.setText(RecordTable.getValueAt(SelectedRows, 2).toString());
               txtAge.setText(RecordTable.getValueAt(SelectedRows, 3).toString());
               txtOrderNo.setText(RecordTable.getValueAt(SelectedRows, 4).toString());
               
               
    }                                    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {       
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JButton jbtnAdd;
    private javax.swing.JButton jbtnDelete;
    private javax.swing.JButton jbtnExit;
    private javax.swing.JButton jbtnPrint;
    private javax.swing.JButton jbtnUpdate;
    private javax.swing.JTextField txtAge;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtOrderNo;
    // End of variables declaration                   
}

2

Answers


  1. This is how you attempt to load the records from the database:

            Class.forName("com.mysql.jdbc.Driver");
            sqlConn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            pst = sqlConn.prepareStatement("SELECT * FROM customer database");
            rs = pst.executeQuery();
            ResultSetMetaData stData = rs.getMetaData();
            q= stData.getColumnCount();
            DefaultTableModel RecordTable = (DefaultTableModel)jTable2.getModel();
                    RecordTable.setRowCount(0);
                    while(rs.next()){
                         obj columnData = new obj ();
                        for (i= 1; i<=q; i++){
                            columnData.add(rs.getString("id"));
                           columnData.add(rs.getString("name"));
                           columnData.add(rs.getString("age"));
                           columnData.add(rs.getString("order_number"));
                        }
                        RecordTable.addRow(columnData);
                    }
    

    The query of

    SELECT * FROM customer database
    

    is syntactically incorrect. Your table is called customers, so you will need to change your query to

    SELECT * FROM `customer`
    
    Login or Signup to reply.
  2. I managed to get the original code in your question working for me. I located the classes AbsoluteLayout and AbsoluteConstraints on GitHub. I fixed compilation errors in the original code that you posted, for example, the following:

    obj columnData = new obj ();
    

    I changed it to:

    java.util.Vector<Object> columnData = new java.util.Vector<>();
    

    And when I ran the code, I could not reproduce your problem. After entering data into the JTextFields and pressing the ADD button, the JTable displayed the data.

    I assume that you are students and hence I believe that the code that you wrote is due to the fact that you don’t have much experience and therefore are unfamiliar (or unaware) of many aspects of Java (including Swing).

    • An ActionListener can be implemented as a lambda expression (or method reference) rather than an anonymous class.
    • You are not closing resources such as database connections. The below code uses try-with-resources.
    • It is no longer required to explicitly load the JDBC driver via calling method Class.forName. In any case, there is definitely no need to call it each time you want to connect to the database. Once any class is loaded (by the JVM) it remains loaded so no need to reload it.
    • I don’t know the structure of the CUSTOMERS [database] table, but I assume that it contains only the four columns indicated in your code, including:
      • id
      • name
      • age
      • order_number

    I also assume that all those columns are VARCHAR columns since you treat them as strings in your code.

    • Rather than using a MouseListener to handle row selection in the JTable, you should use a selection listener.
    • No need for class NewJFrame to extend JFrame. Many online examples of Swing applications do this but it is not required.
    • If you want to display a dialog window to the user, there is no need to create another JFrame just so that you can provide an owner to JOptionPane. Any java.awt.Component subclass can serve as the owner.
    • Rather than new java.awt.Color(0, 0, 0) you can use the constant Color.black.
    • It appears that column ID, in [database] table CUSTOMERS, is the primary key. It is usually not a good idea to update a primary key but rather delete the row if that primary key is no longer required and insert a new row with the new primary key value. In fact, some databases do not allow updating a primary key. Hence I changed your [SQL] UPDATE statement.
    • Index of first column in a JTable is 0 (zero) – and not 1 (one), hence method jTable2MouseClicked will throw an exception since there is no column with index 4.
    import javax.swing.BorderFactory;
    import javax.swing.GroupLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.LayoutStyle;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.border.BevelBorder;
    import javax.swing.event.ListSelectionEvent;
    
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    
    import org.netbeans.lib.awtextra.AbsoluteConstraints;
    import org.netbeans.lib.awtextra.AbsoluteLayout;
    
    public class NewJFrame {
        private static final Logger LOGGER = Logger.getLogger(NewJFrame.class.getName());
        private static final String DB_URL = "jdbc:mysql://localhost:3306/customer database?zeroDateTimeBehavior=CONVERT_TO_NULL";
        private static final String DB_USER = "root";
        private static final String DB_PASSWORD = "";
        private static final String INSERT = """
    insert into CUSTOMERS (ID
                          ,NAME
                          ,AGE
                          ,ORDER_NUMBER)
    values (?
           ,?
           ,?
           ,?)
    """;
        private static final String SELECT = "select * from CUSTOMERS";
        private static final String UPDATE = """
    update CUSTOMERS
        set NAME = ?
           ,AGE = ?
           ,ORDER_NUMBER = ?
      where ID = ?
    """;
        private static final Vector<Object> COLUMNS;
    
        static {
            COLUMNS = new Vector<>(4);
            COLUMNS.add("ID");
            COLUMNS.add("Name");
            COLUMNS.add("Age");
            COLUMNS.add("Order Number");
        }
    
        public NewJFrame() {
            initComponents();
        }
    
        private void initializeDB() {
            try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                 Statement s = conn.createStatement();
                 ResultSet rows = s.executeQuery(SELECT)) {
                DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                Vector<Vector<Object>> data = new Vector<>();
                while (rows.next()) {
                    Vector<Object> columnData = new Vector<>();
                    columnData.add(rows.getString("id"));
                    columnData.add(rows.getString("name"));
                    columnData.add(rows.getString("age"));
                    columnData.add(rows.getString("order_number"));
                    data.add(columnData);
                }
                model.setDataVector(data, COLUMNS);
            }
            catch (Exception ex) {
                LOGGER.log(Level.SEVERE, ex.toString(), ex);
                JOptionPane.showMessageDialog(frame, ex, "Refresh Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    
        private void initComponents() {
            frame = new JFrame();
            jPanel1 = new JPanel();
            jPanel7 = new JPanel();
            jPanel8 = new JPanel();
            jPanel9 = new JPanel();
            jPanel10 = new JPanel();
            jPanel11 = new JPanel();
            jbtnUpdate = new JButton();
            jbtnPrint = new JButton();
            jbtnAdd = new JButton();
            jbtnExit = new JButton();
            jbtnDelete = new JButton();
            jPanel12 = new JPanel();
            jPanel13 = new JPanel();
            jPanel14 = new JPanel();
            jScrollPane2 = new JScrollPane();
            jTable2 = new JTable();
            jLabel2 = new JLabel();
            txtID = new JTextField();
            jLabel3 = new JLabel();
            txtName = new JTextField();
            jLabel4 = new JLabel();
            txtAge = new JTextField();
            jLabel5 = new JLabel();
            txtOrderNo = new JTextField();
            jPanel15 = new JPanel();
            jPanel17 = new JPanel();
            jPanel18 = new JPanel();
            jLabel1 = new JLabel();
    
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setPreferredSize(new Dimension(1333, 900));
            jPanel1.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel1.setLayout(new AbsoluteLayout());
    
            jPanel7.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel7.setLayout(new AbsoluteLayout());
            jPanel1.add(jPanel7, new AbsoluteConstraints(999, 20, -1, -1));
    
            jPanel8.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel8.setLayout(new AbsoluteLayout());
            jPanel1.add(jPanel8, new AbsoluteConstraints(32, 24, -1, -1));
    
            jPanel9.setBorder(BorderFactory.createLineBorder(Color.black, 8));
    
            jPanel10.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel10.setLayout(new AbsoluteLayout());
    
            jPanel11.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel11.setLayout(new AbsoluteLayout());
    
            jbtnUpdate.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jbtnUpdate.setText("Update");
            jbtnUpdate.addActionListener(this::jbtnUpdateActionPerformed);
    
            jbtnPrint.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jbtnPrint.setText("Print");
    
            jbtnAdd.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jbtnAdd.setText("ADD");
            jbtnAdd.addActionListener(this::jbtnAddActionPerformed);
    
            jbtnExit.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jbtnExit.setText("Exit");
            jbtnExit.addActionListener(this::jbtnExitActionPerformed);
    
            jbtnDelete.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jbtnDelete.setText("Delete");
    
            GroupLayout jPanel9Layout = new GroupLayout(jPanel9);
            jPanel9.setLayout(jPanel9Layout);
            jPanel9Layout.setHorizontalGroup(jPanel9Layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel9Layout.createSequentialGroup().addGap(14, 14, 14)
                            .addComponent(jPanel10, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(GroupLayout.Alignment.TRAILING, jPanel9Layout
                            .createSequentialGroup().addContainerGap(37, Short.MAX_VALUE)
                            .addGroup(jPanel9Layout
                                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                                    .addComponent(jbtnExit, GroupLayout.PREFERRED_SIZE, 190,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtnAdd, GroupLayout.PREFERRED_SIZE, 190,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtnPrint, GroupLayout.PREFERRED_SIZE,
                                            190, GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtnUpdate, GroupLayout.PREFERRED_SIZE,
                                            190, GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jbtnDelete, GroupLayout.PREFERRED_SIZE,
                                            190, GroupLayout.PREFERRED_SIZE))
                            .addGap(17, 17, 17))
                    .addGroup(jPanel9Layout
                            .createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel9Layout.createSequentialGroup().addGap(24, 24, 24)
                                    .addComponent(jPanel11, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(220, Short.MAX_VALUE))));
            jPanel9Layout.setVerticalGroup(
                    jPanel9Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel9Layout.createSequentialGroup().addContainerGap()
                                    .addComponent(jPanel10, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addGap(16, 16, 16)
                                    .addComponent(jbtnAdd, GroupLayout.PREFERRED_SIZE, 63,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addGap(33, 33, 33)
                                    .addComponent(jbtnUpdate, GroupLayout.PREFERRED_SIZE,
                                            63, GroupLayout.PREFERRED_SIZE)
                                    .addGap(50, 50, 50)
                                    .addComponent(jbtnPrint, GroupLayout.PREFERRED_SIZE, 63,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addGap(42, 42, 42)
                                    .addComponent(jbtnDelete, GroupLayout.PREFERRED_SIZE,
                                            63, GroupLayout.PREFERRED_SIZE)
                                    .addGap(43, 43, 43)
                                    .addComponent(jbtnExit, GroupLayout.PREFERRED_SIZE, 63,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(79, Short.MAX_VALUE))
                            .addGroup(jPanel9Layout
                                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel9Layout.createSequentialGroup().addGap(16, 16, 16)
                                            .addComponent(jPanel11,
                                                    GroupLayout.PREFERRED_SIZE,
                                                    GroupLayout.DEFAULT_SIZE,
                                                    GroupLayout.PREFERRED_SIZE)
                                            .addContainerGap(568, Short.MAX_VALUE))));
    
            jPanel1.add(jPanel9, new AbsoluteConstraints(1060, 120, 260, 600));
    
            jPanel12.setBorder(BorderFactory.createLineBorder(Color.black, 8));
    
            jPanel13.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel13.setLayout(new AbsoluteLayout());
    
            jPanel14.setBorder(BorderFactory.createLineBorder(Color.black, 8));
            jPanel14.setLayout(new AbsoluteLayout());
    
            jTable2.setModel(new DefaultTableModel(new Vector<>(), COLUMNS));
            jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            jTable2.getSelectionModel().addListSelectionListener(this::jTable2MouseClicked);
            jScrollPane2.setViewportView(jTable2);
    
            jLabel2.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jLabel2.setText("ID");
    
            txtID.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            txtID.addActionListener(this::txtIDActionPerformed);
    
            jLabel3.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jLabel3.setText("Name");
    
            txtName.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
    
            jLabel4.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jLabel4.setText("Age");
    
            txtAge.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
    
            jLabel5.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
            jLabel5.setText("Order number");
    
            txtOrderNo.setFont(new Font("Segoe UI", 1, 24)); // NOI18N
    
            GroupLayout jPanel12Layout = new GroupLayout(jPanel12);
            jPanel12.setLayout(jPanel12Layout);
            jPanel12Layout.setHorizontalGroup(jPanel12Layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel12Layout.createSequentialGroup().addGroup(jPanel12Layout
                            .createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel12Layout.createSequentialGroup().addGap(77, 77, 77)
                                    .addComponent(jPanel13, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel12Layout.createSequentialGroup().addGap(132, 132, 132)
                                    .addComponent(jLabel3))
                            .addGroup(jPanel12Layout.createSequentialGroup().addGroup(jPanel12Layout
                                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel12Layout.createSequentialGroup()
                                            .addGap(132, 132, 132)
                                            .addGroup(jPanel12Layout
                                                    .createParallelGroup(
                                                            GroupLayout.Alignment.LEADING)
                                                    .addGroup(jPanel12Layout.createSequentialGroup()
                                                            .addGap(19, 19, 19).addComponent(jLabel2))
                                                    .addGroup(jPanel12Layout.createSequentialGroup()
                                                            .addGap(11, 11, 11).addComponent(jLabel4))))
                                    .addGroup(jPanel12Layout.createSequentialGroup().addGap(90, 90, 90)
                                            .addComponent(jLabel5)))
                                    .addGap(180, 180, 180)
                                    .addGroup(jPanel12Layout
                                            .createParallelGroup(
                                                    GroupLayout.Alignment.LEADING, false)
                                            .addComponent(txtAge, GroupLayout.DEFAULT_SIZE,
                                                    145, Short.MAX_VALUE)
                                            .addComponent(txtOrderNo).addComponent(txtName)
                                            .addComponent(txtID))))
                            .addContainerGap(459, Short.MAX_VALUE))
                    .addGroup(jPanel12Layout
                            .createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel12Layout.createSequentialGroup().addGap(24, 24, 24)
                                    .addComponent(jPanel14, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(1010, Short.MAX_VALUE))));
            jPanel12Layout.setVerticalGroup(jPanel12Layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel12Layout.createSequentialGroup().addContainerGap()
                            .addComponent(jPanel13, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.DEFAULT_SIZE,
                                    GroupLayout.PREFERRED_SIZE)
                            .addGap(24, 24, 24)
                            .addGroup(jPanel12Layout
                                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel2).addComponent(txtID,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE))
                            .addGap(32, 32, 32)
                            .addGroup(jPanel12Layout
                                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3).addComponent(txtName,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE))
                            .addGap(28, 28, 28)
                            .addGroup(jPanel12Layout
                                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4).addComponent(txtAge,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE))
                            .addGap(31, 31, 31)
                            .addGroup(jPanel12Layout
                                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel5).addComponent(txtOrderNo,
                                            GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 143,
                                    Short.MAX_VALUE)
                            .addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 168,
                                    GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel12Layout
                            .createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel12Layout.createSequentialGroup().addGap(16, 16, 16)
                                    .addComponent(jPanel14, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(568, Short.MAX_VALUE))));
    
            jPanel1.add(jPanel12, new AbsoluteConstraints(10, 120, 1050, 600));
    
            jPanel15.setLayout(new AbsoluteLayout());
            jPanel1.add(jPanel15, new AbsoluteConstraints(22, 14, 971, -1));
    
            GroupLayout jPanel17Layout = new GroupLayout(jPanel17);
            jPanel17.setLayout(jPanel17Layout);
            jPanel17Layout.setHorizontalGroup(
                    jPanel17Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGap(0, 100, Short.MAX_VALUE));
            jPanel17Layout.setVerticalGroup(
                    jPanel17Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGap(0, 100, Short.MAX_VALUE));
    
            jPanel1.add(jPanel17, new AbsoluteConstraints(128, 20, -1, -1));
    
            jPanel18.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    
            jLabel1.setFont(new Font("Segoe UI", 1, 36)); // NOI18N
            jLabel1.setText("Customer management system");
            jLabel1.setMaximumSize(new java.awt.Dimension(500, 16));
    
            GroupLayout jPanel18Layout = new GroupLayout(jPanel18);
            jPanel18.setLayout(jPanel18Layout);
            jPanel18Layout.setHorizontalGroup(
                    jPanel18Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel18Layout.createSequentialGroup().addGap(368, 368, 368)
                                    .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(396, Short.MAX_VALUE)));
            jPanel18Layout.setVerticalGroup(
                    jPanel18Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel18Layout.createSequentialGroup().addGap(20, 20, 20)
                                    .addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 44,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(36, Short.MAX_VALUE)));
    
            jPanel1.add(jPanel18, new AbsoluteConstraints(10, 10, 1290, -1));
    
            Container contentPane = frame.getContentPane();
            GroupLayout layout = new GroupLayout(contentPane);
            contentPane.setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(layout
                                    .createSequentialGroup().addComponent(jPanel1,
                                            GroupLayout.DEFAULT_SIZE, 1327, Short.MAX_VALUE)
                                    .addContainerGap()));
            layout.setVerticalGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup().addContainerGap()
                                    .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, 726,
                                            GroupLayout.PREFERRED_SIZE)
                                    .addContainerGap(168, Short.MAX_VALUE)));
    
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }// </editor-fold>
    
        private void jbtnAddActionPerformed(ActionEvent evt) {
            try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                 PreparedStatement ps = conn.prepareStatement(INSERT)) {
                ps.setString(1, txtID.getText());
                ps.setString(2, txtName.getText());
                ps.setString(3, txtAge.getText());
                ps.setString(4, txtOrderNo.getText());
                ps.executeUpdate();
                JOptionPane.showMessageDialog(frame, "Record added.");
                initializeDB();
            }
            catch (SQLException ex) {
                LOGGER.log(Level.SEVERE, ex.toString(), ex);
                JOptionPane.showMessageDialog(frame,
                                              "Failed to add data.",
                                              "ERROR",
                                              JOptionPane.ERROR_MESSAGE);
            }
        }
    
        private void txtIDActionPerformed(ActionEvent evt) {
            // TODO add your handling code here:
        }
    
        private JFrame frame;
    
        private void jbtnExitActionPerformed(java.awt.event.ActionEvent evt) {
            if (JOptionPane.showConfirmDialog(frame,
                                              "Do you really want to exit?",
                                              "Customer Management System",
                                              JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        }
    
        private void jbtnUpdateActionPerformed(ActionEvent evt) {
            try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
                 PreparedStatement ps = conn.prepareStatement(UPDATE)) {
                ps.setString(1, txtName.getText());
                ps.setString(2, txtAge.getText());
                ps.setString(3, txtOrderNo.getText());
                ps.setString(4, txtID.getText());
                ps.executeUpdate();
                JOptionPane.showMessageDialog(frame, "Record Updated");
                initializeDB();
            }
            catch (SQLException ex) {
                LOGGER.log(Level.SEVERE, ex.toString(), ex);
                JOptionPane.showMessageDialog(frame,
                                              "Update failed.",
                                              "ERROR",
                                              JOptionPane.ERROR_MESSAGE);
            }
        }
    
        private void jTable2MouseClicked(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                int selectedRow = jTable2.getSelectedRow();
                if (selectedRow >= 0) {
                    TableModel model = jTable2.getModel();
                    Object idObj = model.getValueAt(selectedRow, 0);
                    String id = idObj == null ? "" : idObj.toString();
                    txtID.setText(id);
                    Object nameObj = model.getValueAt(selectedRow, 1);
                    String name = nameObj == null ? "" : nameObj.toString();
                    txtName.setText(name);
                    Object ageObj = model.getValueAt(selectedRow, 2);
                    String age = ageObj == null ? "" : ageObj.toString();
                    txtAge.setText(age);
                    Object orderObj = model.getValueAt(selectedRow, 3);
                    String order = orderObj == null ? "" : orderObj.toString();
                    txtOrderNo.setText(order);
                }
            }
        }
    
        public static void main(String args[]) {
            try {
                for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            }
            catch (ClassNotFoundException ex) {
                LOGGER.log(java.util.logging.Level.SEVERE, null, ex);
            }
            catch (InstantiationException ex) {
                LOGGER.log(java.util.logging.Level.SEVERE, null, ex);
            }
            catch (IllegalAccessException ex) {
                LOGGER.log(java.util.logging.Level.SEVERE, null, ex);
            }
            catch (UnsupportedLookAndFeelException ex) {
                LOGGER.log(java.util.logging.Level.SEVERE, null, ex);
            }
            // </editor-fold>
    
            /* Create and display the form */
            EventQueue.invokeLater(() -> new NewJFrame());
        }
    
        // Variables declaration - do not modify
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel4;
        private JLabel jLabel5;
        private JPanel jPanel1;
        private JPanel jPanel10;
        private JPanel jPanel11;
        private JPanel jPanel12;
        private JPanel jPanel13;
        private JPanel jPanel14;
        private JPanel jPanel15;
        private JPanel jPanel17;
        private JPanel jPanel18;
        private JPanel jPanel7;
        private JPanel jPanel8;
        private JPanel jPanel9;
        private JScrollPane jScrollPane2;
        private JTable jTable2;
        private JButton jbtnAdd;
        private JButton jbtnDelete;
        private JButton jbtnExit;
        private JButton jbtnPrint;
        private JButton jbtnUpdate;
        private JTextField txtAge;
        private JTextField txtID;
        private JTextField txtName;
        private JTextField txtOrderNo;
        // End of variables declaration
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search