{"id":2792,"date":"2012-10-30T13:00:24","date_gmt":"2012-10-30T13:00:24","guid":{"rendered":"http:\/\/www.gubatron.com\/blog\/?p=2792"},"modified":"2012-10-30T14:26:57","modified_gmt":"2012-10-30T14:26:57","slug":"java-have-a-jtables-column-preferred-width-adjusted-to-perfectly-to-the-size-of-the-longest-string-in-the-model","status":"publish","type":"post","link":"https:\/\/www.gubatron.com\/blog\/java-have-a-jtables-column-preferred-width-adjusted-to-perfectly-to-the-size-of-the-longest-string-in-the-model\/","title":{"rendered":"Java: Have a JTable&#8217;s column preferred width adjusted perfectly to the size of the longest string in the model"},"content":{"rendered":"<p>Here&#8217;s a utility method I&#8217;ve coded for FrostWire&#8217;s partial download dialog. With it I&#8217;m able to adjust a JTable&#8217;s column by iterating over the table&#8217;s column model data and calculating the exact dimensions required to render the longest string found. You can specify a maximum width (to avoid some really long strings from screwing up the display) and some right padding in case you need some breathing room.<\/p>\n<p>Enjoy<\/p>\n<p>[java]<br \/>\n    \/**<br \/>\n     * It will adjust the column width to match the widest element.<br \/>\n     * (You might not want to use this for every column, consider some columns might be really long)<br \/>\n     * it assumes model and jtable != null<br \/>\n     *\/<br \/>\n    public static void adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table) {<\/p>\n<p>    \tif (columnIndex > model.getColumnCount()-1) {<br \/>\n    \t\t\/\/invalid column index<br \/>\n    \t\treturn;<br \/>\n    \t}<\/p>\n<p>    \tif (!model.getColumnClass(columnIndex).equals(String.class)) {<br \/>\n    \t\treturn;<br \/>\n    \t}<\/p>\n<p>    \tString longestValue = &#8220;&#8221;;<br \/>\n    \tfor (int row = 0; row < model.getRowCount(); row++) {\n    \t\tString strValue = (String) model.getValueAt(row, columnIndex);\n    \t\tif (strValue != null &#038;&#038; strValue.length() > longestValue.length()) {<br \/>\n    \t\t\tlongestValue = strValue;<br \/>\n    \t\t}<br \/>\n    \t}<\/p>\n<p>    \tGraphics g = table.getGraphics();<\/p>\n<p>    \ttry {<br \/>\n    \t\tint suggestedWidth = (int) g.getFontMetrics(table.getFont()).getStringBounds(longestValue, g).getWidth();<br \/>\n    \t\ttable.getColumnModel().getColumn(columnIndex).setPreferredWidth(((suggestedWidth > maxWidth) ? maxWidth : suggestedWidth)+rightPadding);<br \/>\n    \t} catch (Exception e) {<br \/>\n    \t\ttable.getColumnModel().getColumn(columnIndex).setPreferredWidth(maxWidth);<br \/>\n    \t\te.printStackTrace();<br \/>\n    \t}<\/p>\n<p>    }<br \/>\n[\/java]<\/p>\n<p>Note, make sure you invoke this guy only once, usually after the table has been first painted (you could override paint()) or after the model data has been updated (if it gets to be updated and you feel like autoadjusting a particular column)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here&#8217;s a utility method I&#8217;ve coded for FrostWire&#8217;s partial download dialog. With it I&#8217;m able to adjust a JTable&#8217;s column by iterating over the table&#8217;s column model data and calculating the exact dimensions required to render the longest string found. You can specify a maximum width (to avoid some really long strings from screwing up [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1],"tags":[583,1177,1176],"class_list":["post-2792","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-java","tag-jtable","tag-swing"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5Unzf-J2","jetpack-related-posts":[{"id":156,"url":"https:\/\/www.gubatron.com\/blog\/portscanner-only-60-lines-of-code\/","url_meta":{"origin":2792,"position":0},"title":"PortScanner &#8211; Only 60 lines of code","author":"gubatron","date":"May 19, 2005","format":false,"excerpt":"Hi, here's a simple port scanner I wrote today in Java. I needed to see something on my server, perhaps you can find it useful. I would say its pretty fast, you can tweak the number of threads and timeouts to adjust to your server\/connection. I did't do much testing\u2026","rel":"","context":"In &quot;Gubatron&quot;","block_context":{"text":"Gubatron","link":"https:\/\/www.gubatron.com\/blog\/category\/gubatron\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1928,"url":"https:\/\/www.gubatron.com\/blog\/droid-vs-nexus-1-who-can-calculate-md5-faster\/","url_meta":{"origin":2792,"position":1},"title":"Droid vs Nexus 1: Who can calculate MD5 faster?","author":"gubatron","date":"May 21, 2010","format":false,"excerpt":"Nexus 1 indeed. 17 files get their MD5 calculated on the Droid and 17 files get their MD5 hash calculated on the Nexus 1 Nexus 1 pwns. Here's the code in case you're curious. [java] public void onClick(View v) { _logTextView.setText(\"MD5 Benchmark on \" + Build.DEVICE + \"nn\"); if (GlobalVariables.APP_CONTEXT\u2026","rel":"","context":"In &quot;Android&quot;","block_context":{"text":"Android","link":"https:\/\/www.gubatron.com\/blog\/category\/android\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":980,"url":"https:\/\/www.gubatron.com\/blog\/javareflection-notes-invoking-a-static-main-method-from-a-dinamically-loaded-class\/","url_meta":{"origin":2792,"position":2},"title":"Java\/Reflection notes: Invoking a static main() method from a dinamically loaded class.","author":"gubatron","date":"November 22, 2008","format":false,"excerpt":"Maybe for some wild reason, your Java application will need to execute a pre launcher that won't know about the Main class it's supposed to invoke until it's being executed. For example, you have distributed your Java application but you used pack200 to compress your jars, and your new application\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1252,"url":"https:\/\/www.gubatron.com\/blog\/how-to-make-your-own-quick-dirty-hex-file-viewer-in-java\/","url_meta":{"origin":2792,"position":3},"title":"How to make your own Quick &#038; Dirty Hex File Viewer in Java","author":"gubatron","date":"April 18, 2009","format":false,"excerpt":"Update: You might want to read this new version of the code instead. Thanks ispak I was playing with a hex editor recently and then I thought it would be pretty easy to make a program to output what you see on a text editor. Here's a quick & dirty\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"Same file on HexEdit","src":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3634\/3452718760_995edb5218_o.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3634\/3452718760_995edb5218_o.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/farm4.static.flickr.com\/3634\/3452718760_995edb5218_o.png?resize=525%2C300 1.5x"},"classes":[]},{"id":1269,"url":"https:\/\/www.gubatron.com\/blog\/how-to-make-a-quick-dirty-hexviewer-updated\/","url_meta":{"origin":2792,"position":4},"title":"How to make a Quick &#038; Dirty HexViewer &#8211; Updated","author":"gubatron","date":"April 20, 2009","format":false,"excerpt":"After I received comments from ispak on Flickr I made a few fixes. ispak pointed out that it was a bad idea reading one byte at the time, also I had a gay ass try\/catch that didn't catch any exception :p So now I read 16 byte chunks, and I\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"HexViewer - r2","src":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/farm4.static.flickr.com\/3486\/3458529439_31357e0afe_o.png?resize=525%2C300 1.5x"},"classes":[]},{"id":2926,"url":"https:\/\/www.gubatron.com\/blog\/how-to-check-if-a-java-process-is-running-on-any-local-virtual-machine-programatically\/","url_meta":{"origin":2792,"position":5},"title":"How to check if a Java Process is running on any local Virtual Machine programmatically","author":"gubatron","date":"January 30, 2013","format":false,"excerpt":"Quick and dirty way to check if a Java Process is already running. Useful if you need to run cronjobs periodically and you don't know how long they might take, you can add this check at the beginning of your main, and it'll look for all the local virtual machines\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2792","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/comments?post=2792"}],"version-history":[{"count":3,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2792\/revisions"}],"predecessor-version":[{"id":2845,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/2792\/revisions\/2845"}],"wp:attachment":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/media?parent=2792"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/categories?post=2792"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/tags?post=2792"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}