the code below is of a table that displays data fetched from database,hte table desnot display the scrollable bar,it only shows the moving up arrow only, so i cannot scroll downwards,it also became difficult to set column widths for specific columns..i did research in the internet but could not solve it
static JTable table1 = new JTable();
static DefaultTableModel model;
table1=new JTable(model);
JScrollPane pane = new JScrollPane(table1);
String col[] = {"CLASS","TERM","PAYABLE","YEAR"};
model = new DefaultTableModel(col,100);
saachs.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String adm = adms.getText();
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
try {
throw new Exception ("driver not found");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
String url = "jdbc:mysql://localhost/test";
try {
con = DriverManager.getConnection(url,"abda","abda");
} catch (SQLException e1) {
e1.printStackTrace();
}if(con!=null){
Statement st = null;
ResultSet rs = null;
String query = "select date,term,paid,receipt from fees where adm = '"+adms.getText()+"'";
try {
st = con.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
rs = st.executeQuery(query);
} catch (SQLException e1) {
System.out.println("query not executed");
e1.printStackTrace();
}
try {
while(rs.next()){
Vector<String> rowData = new Vector<>();
rowData.add(rs.getString(1));
rowData.add(rs.getString(2));
rowData.add(rs.getString(3));
rowData.add(rs.getString(4));
// row++;
model.addRow(rowData);
}
table1.setModel(model);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
When you use the addRow(...) method the rows added are 101, 102, 103 etc. so you can't see the data unless you scroll through all 100 rows.
Don't hardcode the number of rows. The default should be 0. Then the addRow(...) method will add rows to the table one at a time. Scrollbars will then appear as necessary.
You have a problem with your program structure. Using statics is NOT the way to fix it.
I suggest you read the section from the Swing tutorial on How to Use Table. The
SimpleTableDemo
will show you how to better structure your code. It simply creates a panel with all the components and adds the panel to the frame. All the variables are contained in the panel class.