How to populate JTable from database on button event

前端 未结 2 999
误落风尘
误落风尘 2021-01-17 02:27

I have a text box that allows users to put in select type queries with the idea that when they click a button the result of the select statement will be shown in a JTable. I

2条回答
  •  佛祖请我去吃肉
    2021-01-17 03:15

    Ive removed the local variable

    No, you removed the instance variable. Did you actually try this with your real code or just edit the question?

    I have no idea how to provide a testable database for this question

    I already suggested you create a method to simplify the logic. Somethng like:

    public TableModel getDataFromDatabase()
    {
        DefaultTableModel model = new DefaultTableModel(5, 5);
        model.setValueAt("Hard", 0, 0);
        model.setValueAt("Coded", 1, 1);
        model.setValueAt("Data", 2, 2);
    
        return model;
    }
    

    Then in your ActionListener you simple do something like:

    table_ResQues.setModel( getDataFromDataBase() );
    

    Once you get this basic logic working you move the SQL logic into the getDataFromDatabase() method.

    So now you create your SSCCE showing how you actually create the frame and add the components to the frame. The code should be compilable and executable.

    Edit:

    You have been told to display a table is a scrollpane. It is no extra effort to do this. Instead of using:

    panel.add(table);
    

    you use:

    panel.add( new JScrollPane( table ) );
    

    I would also suggest that to test your layout you can use code like the following to display a dummy table:

    //JTable table_ResQues = new JTable();
    JTable table_ResQues = new JTable(5,5);
    

    Then when you use the setModel() method, only the data is affected, not the layout of the table.

    I cant help but feel this is a fireTableDataChanged problem though.

    I doubt it. That method is invoked by the TableModel when you change the data in the model. It is not used in this case because you are using the setModel(...) method. This will cause the table to repaint() itself automatically.

提交回复
热议问题