java - JTable not appearing though populated from database -
i've populated jtable database. table not appearing. can not figure out problem code. can not understand whether problem layout or code block retrieving data database. not getting exception message. i've added frame.getcontentpane().add(scroll, borderlayout.center);
in code, still can not table. please see attached image getting.
import java.awt.eventqueue; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultset; import javax.swing.jframe; import javax.swing.jscrollpane; import java.awt.borderlayout; import javax.swing.jtable; import javax.swing.table.defaulttablemodel; import controller.db_con; public class jtable { private jframe frame; private jtable table; string[] columnnames = {"id", "name", "username", "contact", "gender"}; /** * launch application. */ public static void main(string[] args) { eventqueue.invokelater(new runnable() { public void run() { try { jtable window = new jtable(); window.frame.setvisible(true); } catch (exception e) { e.printstacktrace(); system.out.println(e.tostring()); } } }); } /** * create application. */ public jtable() { initialize(); } /** * initialize contents of frame. */ private void initialize() { frame = new jframe(); frame.setbounds(100, 100, 450, 300); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().setlayout(new borderlayout(0, 0)); table = new jtable(); frame.getcontentpane().add(table, borderlayout.center); defaulttablemodel model = new defaulttablemodel(); model.setcolumnidentifiers(columnnames); table.setautoresizemode(jtable.auto_resize_all_columns); table.setfillsviewportheight(true); jscrollpane scroll = new jscrollpane(table); frame.getcontentpane().add(scroll, borderlayout.center); scroll.sethorizontalscrollbarpolicy( jscrollpane.horizontal_scrollbar_as_needed); scroll.setverticalscrollbarpolicy( jscrollpane.vertical_scrollbar_as_needed); try { connection sqlcon = db_con.getsqlconnection(); preparedstatement ps = sqlcon.preparestatement("select id,name,username,contact,gender temp_tbl"); int = 0; resultset rs = ps.executequery(); while(rs.next()) { string id = rs.getstring("id"); string name = rs.getstring("name"); string username = rs.getstring("username"); string contact = rs.getstring("contact"); string gender = rs.getstring("gender"); model.addrow(new object[]{id, name, username, contact, gender}); i++; } } catch(exception ex) { system.out.println(ex.tostring()); } } }
you add jtable
frame, add jscrollpane
never add jscrollpane
...
a component can reside within single container, when jscrollpane scroll = new jscrollpane(table);
, removing jtable
frame.
add frame.getcontentpane().add(scroll, borderlayout.center);
after you've created jscrollpane
you never apply tablemodel
jtable
table.setmodel(model); frame.getcontentpane().add(scroll, borderlayout.center);
Comments
Post a Comment