java - Make JTable rows fill the entire height of JScrollPane -
i've got jtable inside jscrollpane inside jpanel. make rows of jtable fill entire height of jpanel. like, if have 10 rows, strech out in height direction , fill entire jpanel, , and if add 10 more rows, rows should resize fit 20 rows in jpanel.
i've managed make jscrollpane fill entire height of panel, table cells stay @ fixed size. there way this? suppose might possible fire event upon resizing window , set row height using window height , number of rows, sounds lot of work if there easier way happy :)
in fact, initial guess comments (or things jtable#setfillsviewportheight) don't here: affect height of table itself, not height of table cells.
additionally, handling of cell heights bit tricky, , there may many corner cases, considering own cell renderer, row margins or fact may manually modify heights of individual rows (which internally causes construction of dedicated model manages these row heights).
for simplest case, componentlistener
sets global row height of table based on space available in enclosing scroll pane might option:
import java.awt.dimension; import java.awt.event.componentadapter; import java.awt.event.componentevent; import javax.swing.jframe; import javax.swing.jscrollpane; import javax.swing.jtable; import javax.swing.swingutilities; public class tablefillviewportheight { public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { createandshowgui(); } }); } private static void createandshowgui() { jframe f = new jframe(); f.setdefaultcloseoperation(jframe.exit_on_close); string[] columnnames = { "first name", "last name", "sport" }; object[][] data = { {"kathy", "smith", "snowboarding" }, {"john", "doe", "rowing" }, {"sue", "black", "knitting"}, {"jane", "white", "speed reading" }, {"joe", "brown", "pool" } }; final jtable table = new jtable(data, columnnames); final jscrollpane scrollpane = new jscrollpane(table); table.addcomponentlistener(new componentadapter() { @override public void componentresized(componentevent e) { table.setrowheight(16); dimension p = table.getpreferredsize(); dimension v = scrollpane.getviewportborderbounds().getsize(); if (v.height > p.height) { int available = v.height - table.getrowcount() * table.getrowmargin(); int perrow = available / table.getrowcount(); table.setrowheight(perrow); } } }); f.getcontentpane().add(scrollpane); f.setsize(500,500); f.setlocationrelativeto(null); f.setvisible(true); } }
but note ... "pragmatic" approach solving this, , tested (and intended for) simplest case of default table. more elegant , flexible solution might involve more effort.
Comments
Post a Comment