Jump to content
xisto Community
Sign in to follow this  
dcalladi

Jtable And Jtextfield / Sql Problems

Recommended Posts

i have a JTable which data is called form a SQL database when a button is pressed i take some variable from a combobox and a textfield for the SQL query. it works the first time and loads up what i want correctly then when i click a record it should fill some textfields with information this also works but when i try to do a new search i get pushed to my catch as this is all in a try and catch loop. a Optionpane comes up and i click ok and it carriers on but the old information is not replaced. when i click on the old information though the new one comes up and the textfields are filled correctly. here is my code any help would be greatly appreciated

package possystem;import javax.swing.JOptionPane;import javax.swing.table.*;import java.util.Vector;import java.sql.*;import javax.swing.ListSelectionModel;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import javax.swing.event.TableModelEvent;import javax.swing.table.AbstractTableModel;/* * DatabaseItemForm.java * * Created on 19-Oct-2011, 19:06:28 *//** * * @author Owner */public class DatabaseItemForm extends javax.swing.JFrame {    ListSelectionModel listSelectionModel;    /** Creates new form DatabaseItemForm */    public DatabaseItemForm() {        initComponents();    }    /** This method is called from within the constructor to     * initialize the form.     * WARNING: Do NOT modify this code. The content of this method is     * always regenerated by the Form Editor.     */    @SuppressWarnings("unchecked")    // <editor-fold defaultstate="collapsed" desc="Generated Code">                              private void initComponents() {        jPanel1 = new javax.swing.JPanel();        searchResultsScrollpane = new javax.swing.JScrollPane();        searchResults = new javax.swing.JTable();        searchByLB = new javax.swing.JLabel();        searchByCB = new javax.swing.JComboBox();        searchByTF = new javax.swing.JTextField();        searchByBT = new javax.swing.JButton();        barcodeLB = new javax.swing.JLabel();        barcodeTF = new javax.swing.JTextField();        nameLB = new javax.swing.JLabel();        nameTF = new javax.swing.JTextField();        costLB = new javax.swing.JLabel();        costTF = new javax.swing.JTextField();        comfirmBT = new javax.swing.JButton();        closeBT = new javax.swing.JButton();        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);        searchResults.setModel(new javax.swing.table.DefaultTableModel(            new Object [][] {                {null, null, null, null},                {null, null, null, null},                {null, null, null, null},                {null, null, null, null}            },            new String [] {                "Id", "Barcode", "Name", "Cost"            }        ) {            boolean[] canEdit = new boolean [] {                false, false, false, false            };            public boolean isCellEditable(int rowIndex, int columnIndex) {                return canEdit [columnIndex];            }        });        searchResults.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);        searchResults.setAutoscrolls(false);        searchResults.setFillsViewportHeight(true);        searchResults.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);        searchResults.setShowHorizontalLines(false);        searchResultsScrollpane.setViewportView(searchResults);        searchResults.getColumnModel().getColumn(0).setResizable(false);        searchResults.getColumnModel().getColumn(0).setPreferredWidth(50);        searchResults.getColumnModel().getColumn(1).setResizable(false);        searchResults.getColumnModel().getColumn(1).setPreferredWidth(100);        searchResults.getColumnModel().getColumn(2).setResizable(false);        searchResults.getColumnModel().getColumn(2).setPreferredWidth(200);        searchResults.getColumnModel().getColumn(3).setResizable(false);        searchResults.getColumnModel().getColumn(3).setPreferredWidth(100);        searchByLB.setText("Search By:");        searchByCB.setEditable(true);        searchByCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Please Choose", "Barcode", "Name", "Cost" }));        searchByBT.setText("Search");        searchByBT.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                searchByBTActionPerformed(evt);            }        });        barcodeLB.setText("Please Enter Barcode");        nameLB.setText("Please Enter Name");        costLB.setText("Please Enter Cost");        comfirmBT.setText("Comfirm Changes");        comfirmBT.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                comfirmBTActionPerformed(evt);            }        });        closeBT.setText("Close");        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);        jPanel1.setLayout(jPanel1Layout);        jPanel1Layout.setHorizontalGroup(            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(jPanel1Layout.createSequentialGroup()                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                    .addGroup(jPanel1Layout.createSequentialGroup()                        .addGap(21, 21, 21)                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)                            .addGroup(jPanel1Layout.createSequentialGroup()                                .addComponent(searchByLB)                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                                .addComponent(searchByCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                                .addComponent(searchByTF, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)                                .addComponent(searchByBT))                            .addComponent(nameLB)                            .addComponent(costLB)                            .addGroup(jPanel1Layout.createSequentialGroup()                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)                                    .addComponent(barcodeTF, javax.swing.GroupLayout.Alignment.LEADING)                                    .addComponent(nameTF, javax.swing.GroupLayout.Alignment.LEADING)                                    .addComponent(costTF, javax.swing.GroupLayout.Alignment.LEADING)                                    .addComponent(barcodeLB, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 222, Short.MAX_VALUE)                                .addComponent(comfirmBT)))                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 190, Short.MAX_VALUE))                    .addGroup(jPanel1Layout.createSequentialGroup()                        .addContainerGap()                        .addComponent(searchResultsScrollpane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))                .addComponent(closeBT)                .addContainerGap())        );        jPanel1Layout.setVerticalGroup(            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)                    .addGroup(jPanel1Layout.createSequentialGroup()                        .addContainerGap()                        .addComponent(closeBT))                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()                        .addGap(22, 22, 22)                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                            .addComponent(searchByLB)                            .addComponent(searchByCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                            .addComponent(searchByTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                            .addComponent(searchByBT))                        .addGap(18, 18, 18)                        .addComponent(barcodeLB)                        .addGap(18, 18, 18)                        .addComponent(barcodeTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                        .addGap(18, 18, 18)                        .addComponent(nameLB)                        .addGap(18, 18, 18)                        .addComponent(nameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                        .addGap(18, 18, 18)                        .addComponent(costLB)                        .addGap(18, 18, 18)                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)                            .addComponent(costTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)                            .addComponent(comfirmBT))                        .addGap(18, 18, 18)                        .addComponent(searchResultsScrollpane, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)))                .addContainerGap())        );        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());        getContentPane().setLayout(layout);        layout.setHorizontalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)        );        layout.setVerticalGroup(            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)        );        pack();    }// </editor-fold>                            private void searchByBTActionPerformed(java.awt.event.ActionEvent evt) {                                                   String searchType = (String) searchByCB.getSelectedItem();        String searchText = searchByTF.getText();        tableFiller(searchType, searchText);    }                                              private void comfirmBTActionPerformed(java.awt.event.ActionEvent evt) {                                                  String changeBarcode = barcodeTF.getText();        String changeName = nameTF.getText();        double changePrice = Double.parseDouble(costTF.getText());        try {            DriverManager.registerDriver(new com.mysql.jdbc.Driver());            Connection conn = DriverManager.getConnection("REMOVED");            ResultSet rs = conn.createStatement().executeQuery("UPDATE Test_items SET null," + changeBarcode + ", " + changeName + "," + changePrice + " WHERE ");        } catch (Exception ex) {            JOptionPane.showMessageDialog(rootPane, "Something is Wrong");        }    }                                             public void tableFiller (String searchType, String searchText)  {        try {            DriverManager.registerDriver(new com.mysql.jdbc.Driver());            Connection conn = DriverManager.getConnection("REMOVED");            //Access Rows and Columns from database            Vector<String> Columns = new Vector<String>();            Vector<Vector<Object>> Rows = new Vector<Vector<Object>>();            ResultSet rs = conn.createStatement().executeQuery("select * from Test_items where " + searchType + " = " + searchText + "");            ResultSetMetaData metaDt = rs.getMetaData();            int cols = metaDt.getColumnCount();            Columns.clear(); // clear unwanted value if exist any in Columns variable.//Get Columns From database            for (int i = 1; i <= cols; i++) {                Columns.addElement(metaDt.getColumnName(i));            }            Rows.clear(); // clear unwanted value if exist any in Rows variable.	//Get RowsNames From database            while (rs.next()) {                Vector<Object> row = new Vector<Object>(cols);                for (int i = 1; i <= cols; i++) {                    row.addElement(rs.getObject(i));                }                Rows.addElement(row);            }            DefaultTableModel Model = new DefaultTableModel(Rows, Columns);            searchResults.setModel(Model);            searchResults.getColumnModel().getColumn(0).setPreferredWidth(50);            searchResults.getColumnModel().getColumn(1).setPreferredWidth(100);            searchResults.getColumnModel().getColumn(2).setPreferredWidth(200);            searchResults.getColumnModel().getColumn(3).setPreferredWidth(100);            listSelectionModel = searchResults.getSelectionModel();            listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());            searchResults.getModel().addTableModelListener(searchResults);            repaint();            conn.close();        } catch (Exception ex) {            JOptionPane.showMessageDialog(rootPane, "Something is Wrong");        }    }    class SharedListSelectionHandler implements ListSelectionListener {        @Override        public void valueChanged(ListSelectionEvent e) {            barcodeTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 1).toString());            nameTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 2).toString());            costTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 3).toString());        }    }    public void tableChanged(TableModelEvent e) {        searchResults.tableChanged(new TableModelEvent(searchResults.getModel()));    }    // Variables declaration - do not modify                         private javax.swing.JLabel barcodeLB;    private javax.swing.JTextField barcodeTF;    private javax.swing.JButton closeBT;    private javax.swing.JButton comfirmBT;    private javax.swing.JLabel costLB;    private javax.swing.JTextField costTF;    private javax.swing.JPanel jPanel1;    private javax.swing.JLabel nameLB;    private javax.swing.JTextField nameTF;    private javax.swing.JButton searchByBT;    private javax.swing.JComboBox searchByCB;    private javax.swing.JLabel searchByLB;    private javax.swing.JTextField searchByTF;    private javax.swing.JTable searchResults;    private javax.swing.JScrollPane searchResultsScrollpane;    // End of variables declaration                   }

Share this post


Link to post
Share on other sites

It has been a while since I last did any Java programming so I may be a bit rusty, but I will try my best to help you debug your code. First off, I would suggest you create a simple console application program or at least a basic Swing form that will help you get out all the clutter and display a single value or string. You can use System.out.println in the console application program or create a JLabel and call the setText method on it while using a StringBuilder to accumulate all of your string text.Next, run your application program and check if you get any exceptions. When creating a database application program, problems often begin at the start - when your application program tries to connect to the database. Check if your connection string (the call to the DriverManager.getConnection) has the right syntax and you have the driver classes available to the program. The problem may be with setting the class path to the driver files. Also check the user credentials being passed when forming the connection. If you can open a connection to the database, run a simple SELECT statement using a database connection utility (the MySQL command line utility if you are connecting to a MySQL database, SQL Plus if you are connecting to an Oracle database, or the SQL Server Management Studio if you are connecting to a Microsoft SQL Server 2005 database or later, or the SQL Server Query Analyzer if you are connecting to a Microsoft SQL Server 2000 database or earlier) with the same user account credentials that you have used for your application program. If it checks out, then you should no longer be getting the exception that prevents your application program from connecting to the database server and executing a simple SELECT query.Next, make sure that you can query the table you need to access from your application program through the database client utility. This helps check for non-existent objects and permission issues when accessing objects. Permission issues are common when accessing information across different schemas or databases. If this works fine, look at the SQL statement being generated in your application program. Initially, try using a simple SELECT statement without any parameters or string concatenation. Often problems occur in string concatenation if SQL string literals are not enclosed within quotes. This can be confusing when developing the application program in a programming language because you have to place quotes for both the programming language string literals and include additional quotes for the database server to read within the SQL statements therefore you may need to escape the inner quotes that are meant for the database server to read rather than the programming language compiler. Also, ensure that the column names being specified in the query exist. If you do a simple SELECT * query with no WHERE or ORDER BY clause, you should be able to perform a basic test within your application program. Also check if values are available within the database table by querying the table using the database client utility.Finally, get your application program to display a value from the first row of the result set returned to the application program from the database server as a result of executing the query. If you are able to access data from the database, you can rule out problems with the database connectivity and can look for a problem in your code specific to handling the result set or displaying the values on the user interface.Using a debugger to step through your source code often makes the process of debugging your application much easier. You will spend a lot of time debugging your code with a debugger unless you use break points at key locations within your source code. Many debuggers support the use of conditional debuggers so you do not have to step through every iteration of a loop or step into the code each time a particular line with a break point executes when a condition has not been met. You may decide to create additional variables within your code to help in setting conditional breakpoints. If your compiler supports conditional compilation (such as the #ifdef used by C and C++) you can define the variables and set their values within conditional compilation blocks rather than have them within the application. Also, consider the use of a logging framework when you have sorted out basic problems with your code. Logging frameworks help in troubleshooting intermittent problems, especially those that occur within a production environment. Logging frameworks often have the ability to send out email or write to a file to notify you of problems during the execution of the application program and are handy in learning about problems within a running application program when you do not have access to a debugger.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.