0

I already search many time for this but I can't find the code that will work properly. I also try recommended by questions by stackoverflow but still not successful.

I created a search function in my program in java and it's working fine during my testing one by one, but when I called all the search function in 1 button the only working is the last part only not all function,

here is my sample code of running all the function.

     public ArrayList<pcfdBoards> ListofInventory(String ValToSearch)
{
    ArrayList<pcfdBoards> usersList = new ArrayList<pcfdBoards>();

    Statement st;
    ResultSet rs;

    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String url = "jdbc:sqlserver://ets88-spare:1433;databaseName=users;user=sa;password=test";
        Connection conn = DriverManager.getConnection(url);
        st = conn.createStatement();
        String searchQuery = "SELECT * FROM PCFD WHERE CONCAT(sno,BoardName) LIKE '%"+ValToSearch+"%'";
        rs = st.executeQuery(searchQuery);
        pcfdBoards user;
        while(rs.next())
        {
            user = new pcfdBoards( rs.getInt("sno"), 
                                        rs.getString("Date"), 
                                        rs.getString("DieType"), 
                                        rs.getString("DeviceName"), 
                                        rs.getString("ProgramName"), 
                                        rs.getString("ProgramRevision"), 
                                        rs.getString("BoardName"), 
                                        rs.getString("SerialNumber"),
                                        rs.getString("BoardRevision"),
                                        rs.getString("BoardSlotNumber"),
                                        rs.getString("DIBChannel"),
                                        rs.getString("Area"),
                                        rs.getString("TestOption"),
                                        rs.getString("TestName"),
                                        rs.getString("BinNumber"),
                                        rs.getString("LoadboardSN"),
                                        rs.getString("MotherboardSN"),
                                        rs.getString("AdditionalHW"),
                                        rs.getString("VerifiedBy"),
                                        rs.getString("Datalogs"));
            usersList.add(user);
        }            
    }catch(ClassNotFoundException | SQLException ex){
        jnote.setBackground(Color.red);
        jnote.setText(ex.toString());
    }

    return usersList;
            }

      public void boardname() {ArrayList<pcfdBoards> users = ListofInventory(jboardnameSearch.getText());
    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(new Object[]{"Item ID","Date","Die Type","Device Name", "Program Name", "Program Revision", "Board Name","Serial Number","Board Revision","Board Slot Number","DIB Channel","Area","Test Option","Test Name","Bin Number","Loadboard SN","Motherboard SN","Additional HW","Verifief By","Datalogs"});
    Object[] row = new Object[21];
    for(int i = 0; i < users.size(); i++)
    {
        row[0] = users.get(i).getsno();
        row[1] = users.get(i).getDate();
        row[2] = users.get(i).getDieType();
        row[3] = users.get(i).getDeviceName();
        row[4] = users.get(i).getProgramName();
        row[5] = users.get(i).getProgramRevision();
        row[6] = users.get(i).getBoardName();
        row[7] = users.get(i).getSerialNumber();
        row[8] = users.get(i).getBoardRevision();
        row[9] = users.get(i).getBoardSlotNumber();
        row[10] = users.get(i).getDIBChannel();
        row[11] = users.get(i).getArea();
        row[12] = users.get(i).getTestOption();
        row[13] = users.get(i).getTestName();
        row[14] = users.get(i).getBinNumber();
        row[15] = users.get(i).getLoadboardSN();
        row[16] = users.get(i).getMotherboardSN();
        row[17] = users.get(i).getAdditionalHW();
        row[18] = users.get(i).getVerifiedBy();
        row[19] = users.get(i).getDatalogs();
        model.addRow(row);
    }
   jTable1.setModel(model);
           }
    public ArrayList<pcfdBoards> ListofInventorySN(String ValToSearch)
{
    ArrayList<pcfdBoards> usersList = new ArrayList<pcfdBoards>();

    Statement st;
    ResultSet rs;

    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String url = "jdbc:sqlserver://ets88-spare:1433;databaseName=users;user=sa;password=test";
        Connection conn = DriverManager.getConnection(url);
        st = conn.createStatement();
        String searchQuery = "SELECT * FROM PCFD WHERE CONCAT(sno,SerialNumber) LIKE '%"+ValToSearch+"%'";
        rs = st.executeQuery(searchQuery);
        pcfdBoards user;
        while(rs.next())
        {
            user = new pcfdBoards( rs.getInt("sno"), 
                                        rs.getString("Date"), 
                                        rs.getString("DieType"), 
                                        rs.getString("DeviceName"), 
                                        rs.getString("ProgramName"), 
                                        rs.getString("ProgramRevision"), 
                                        rs.getString("BoardName"), 
                                        rs.getString("SerialNumber"),
                                        rs.getString("BoardRevision"),
                                        rs.getString("BoardSlotNumber"),
                                        rs.getString("DIBChannel"),
                                        rs.getString("Area"),
                                        rs.getString("TestOption"),
                                        rs.getString("TestName"),
                                        rs.getString("BinNumber"),
                                        rs.getString("LoadboardSN"),
                                        rs.getString("MotherboardSN"),
                                        rs.getString("AdditionalHW"),
                                        rs.getString("VerifiedBy"),
                                        rs.getString("Datalogs"));
            usersList.add(user);
        }            
    }catch(ClassNotFoundException | SQLException ex){
        jnote.setBackground(Color.red);
        jnote.setText(ex.toString());
    }

    return usersList;
        }       
   public void serialNum() {ArrayList<pcfdBoards> users = ListofInventorySN(jSerialNumSearch.getText());
    DefaultTableModel model = new DefaultTableModel();
    model.setColumnIdentifiers(new Object[]{"Item ID","Date","Die Type","Device Name", "Program Name", "Program Revision", "Board Name","Serial Number","Board Revision","Board Slot Number","DIB Channel","Area","Test Option","Test Name","Bin Number","Loadboard SN","Motherboard SN","Additional HW","Verifief By","Datalogs"});
    Object[] row = new Object[21];
    for(int i = 0; i < users.size(); i++)
    {
        row[0] = users.get(i).getsno();
        row[1] = users.get(i).getDate();
        row[2] = users.get(i).getDieType();
        row[3] = users.get(i).getDeviceName();
        row[4] = users.get(i).getProgramName();
        row[5] = users.get(i).getProgramRevision();
        row[6] = users.get(i).getBoardName();
        row[7] = users.get(i).getSerialNumber();
        row[8] = users.get(i).getBoardRevision();
        row[9] = users.get(i).getBoardSlotNumber();
        row[10] = users.get(i).getDIBChannel();
        row[11] = users.get(i).getArea();
        row[12] = users.get(i).getTestOption();
        row[13] = users.get(i).getTestName();
        row[14] = users.get(i).getBinNumber();
        row[15] = users.get(i).getLoadboardSN();
        row[16] = users.get(i).getMotherboardSN();
        row[17] = users.get(i).getAdditionalHW();
        row[18] = users.get(i).getVerifiedBy();
        row[19] = users.get(i).getDatalogs();
        model.addRow(row);
    }
   jTable1.setModel(model);
           }

How can I call the boardname() and serialNum() using one button only, I try to use below code but the last part is always working, not all.

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            boardname();
            serialNum();
         }        
Justine
  • 21
  • 4
  • 3
    Welcome to Stack Overflow! It looks like you need to learn to use a debugger. Please help yourself to some complementary debugging techniques. If you still have issues afterwards, please feel free to come back with a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that demonstrates your problem. – Ivan Pronin Jul 22 '17 at 20:19
  • I'm not entirely clear what your question is here. – Joe C Jul 22 '17 at 20:30
  • As your code is now, when **jButton1** is selected the methods ***boardname()*** is called, then the ***serialnumber()*** method is called, then the ***dieType()*** method is called, and then finally the ***programName()*** method is called (in that order). All your methods will be called unless something in one of the preceding methods halts program flow or takes control of the flow and never allows it to return. Hard to tell since you don't show the code for all your specific methods (functions). – DevilsHnd - 退職した Jul 22 '17 at 20:57
  • @DevilsHnd I already edit my post. please check again – Justine Jul 22 '17 at 21:20

1 Answers1

0

The program works without errors, but using a different TableModel, which means when the program calls boardname() method then a new instance of TableModel is set to JTable. But when serialnum() is called, again a new TableModel is created, so the previous model is dissociated from JTable. This is the reason why the table only shows the data of the last method serialnum().

If the target of the program is called, both methods using one TableModel, then avoid creating a new instance of DefaultTableModel on every method. That means:

  1. Remove DefaultTableModel model = new DefaultTableModel(); from boardname() and serialnum() methods.

  2. Remove jTable.setModel() from both methods, and use it outside. For example at the end of jButton1ActionPerformed method.

  3. Declare the model as an attribute of your class, so for example if your class name is MyProgram, then declare the model like this:

    public class MyProgram {
       DefaultTableModel model = new DefaultTableModel();
    

Hope this information helps.

If you need more ideas to see a different approach of how to read your data using one method instead of many, please see the following example. Sorry if the example is quite long, the example is using H2 database. Also visit this link to clarify how use a customized object model for JTable instead of DefaultTableModel: Create JTable from ArrayList of Objects - Java

public class MyInventoryAppDemo {

    public static void main(String[] args) {
        new MyInventoryAppDemo();
    }

    public class MyInventoryDataSource {
        JdbcDataSource ds = new JdbcDataSource();
        Connection cnn;


        public MyInventoryDataSource() {

            PreparedStatement ps = null;
            ds.setURL("jdbc:h2:mem:test");

            try{
                cnn = ds.getConnection();
                //cnn.prepareCall("DROP TABLE ItemResource").execute();
                cnn.prepareCall("CREATE TABLE ItemResource(id INT PRIMARY KEY, name VARCHAR(50)," +
                        "serial VARCHAR(50), location VARCHAR(50));").execute();
                cnn.prepareCall("INSERT INTO ItemResource(id,name,serial,location) values(1,'Notebook','1235','warehouse')").execute();
                cnn.prepareCall("INSERT INTO ItemResource(id,name,serial,location) values(2,'Desktop','12356','warehouse')").execute();
                cnn.prepareCall("INSERT INTO ItemResource(id,name,serial,location) values(3,'Mainframe','12357','garage')").execute();
                cnn.prepareCall("INSERT INTO ItemResource(id,name,serial,location) values(4,'Abacus','12358','warehouse')").execute();

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

        }

        private Connection getCnn() throws SQLException {
            //return ds.getConnection();
            return cnn;
        }

        public List<ItemResource> getItemResources(String byLocation, String bySerial) {

            String sql = "SELECT * FROM ItemResource WHERE location like ? and serial like ?";
            PreparedStatement ps = null;
            ResultSet rs = null;
            Connection cnn = null;
            List<ItemResource> itemResourceList=null;
            try {
                cnn = getCnn();
                ps = cnn.prepareCall(sql);

                ps.setString(1, "%" + byLocation + "%");
                ps.setString(2, "%" + bySerial + "%");
                rs = ps.executeQuery();
                itemResourceList = itemResourceMapper(rs);

            } catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                try {
                    //rs.close();
                    //ps.close();
                    //cnn.close();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
            return itemResourceList;

        }

        private List<ItemResource> itemResourceMapper(ResultSet rs){
            ItemResource item = null;
            List<ItemResource> itemResourceList= new ArrayList<>();
            try {
                while (rs.next()) {
                    item = new ItemResource(
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("serial"),
                            rs.getString("location")
                    );

                    itemResourceList.add(item);

                }
            }catch(Exception ex){
                ex.printStackTrace();
            }
            return itemResourceList;


        }

    }



    public MyInventoryAppDemo() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (UnsupportedLookAndFeelException e) {
                    e.printStackTrace();
                }


                MyInventoryDataSource ds = new MyInventoryDataSource();
                ItemResourceModel model = new ItemResourceModel(ds.getItemResources("",""));
                JTable table = new JTable(model);
                JTextField serial = new JTextField(50);
                JTextField location = new JTextField(50);
                JButton jButton = new JButton("Filter");

                jButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        ItemResourceModel model = new ItemResourceModel(ds.getItemResources(location.getText(),serial.getText()));
                        table.setModel(model);
                        model.fireTableDataChanged();
                        //table.repaint();
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridLayout(2,2));
                frame.add(serial);
                frame.add(location);
                frame.add(jButton);
                frame.add(new JScrollPane(table));

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ItemResourceModel extends AbstractTableModel {

        private List<ItemResource> itemResourceList;
        ItemResourceMetaData itemResourceMetaData;

        public ItemResourceModel(List<ItemResource> itemResourceList) {
            this.itemResourceList = itemResourceList;
            itemResourceMetaData = new ItemResourceMetaData();
        }

        @Override
        public int getRowCount() {
            return itemResourceList.size();
        }

        @Override
        public int getColumnCount() {
            return itemResourceMetaData.getColumns().length;
        }

        @Override
        public String getColumnName(int column) {
            return itemResourceMetaData.getColumns()[column];
        }


        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return itemResourceMetaData.getColumnClass()[columnIndex];
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            ItemResource item = itemResourceList.get(rowIndex);
            Object itemValue = null;
            switch (columnIndex) {
                case 0:
                    itemValue = item.getId();
                    break;
                case 1:
                    itemValue = item.getName();
                    break;
                case 2:
                    itemValue = item.getSerial();
                    break;

                case 3:
                    itemValue = item.getLocation();
                    break;

            }

            return itemValue;
        }
    }

    public class ItemResourceMetaData {
        private String[] columns =
                {"Id", "Name", "Serial", "Location"};

        private Class[] columnClass =
                {String.class, String.class, String.class, String.class};


        public String[] getColumns() {
            return columns;
        }

        public void setColumns(String[] columns) {
            this.columns = columns;
        }

        public Class[] getColumnClass() {
            return columnClass;
        }

        public void setColumnClass(Class[] columnClass) {
            this.columnClass = columnClass;
        }
    }


    public class ItemResource {
        private int id;
        private String name;
        private String serial;

        public ItemResource(int id, String name, String serial, String location) {
            this.id = id;
            this.name = name;
            this.serial = serial;
            this.location = location;
        }

        private String location;


        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSerial() {
            return serial;
        }

        public void setSerial(String serial) {
            this.serial = serial;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }
    }
}
user812786
  • 4,302
  • 5
  • 38
  • 50
Daniel C.
  • 5,418
  • 3
  • 23
  • 26