java - Formatting Integers in JTable Column Cells With Commas -
i have price column displays integers in plain format 1000000. know how can format commas without affecting value when retrieving table.getvalueat()?
is there method table.setcolumncellformat(decimalformat)?
you need custom tablecellrenderer
can format value way need it. see using custom renderers more details
import java.awt.borderlayout; import java.awt.component; import java.awt.eventqueue; import java.text.numberformat; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtable; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; import javax.swing.table.defaulttablecellrenderer; import javax.swing.table.defaulttablemodel; public class test { public static void main(string[] args) { new test(); } public test() { eventqueue.invokelater(new runnable() { @override public void run() { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) { ex.printstacktrace(); } jframe frame = new jframe("testing"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.add(new testpane()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } }); } public class testpane extends jpanel { public testpane() { defaulttablemodel model = new defaulttablemodel(0, 1); (int index = 10000; index < 11000; index++) { model.addrow(new object[]{index}); } jtable table = new jtable(model); table.getcolumnmodel().getcolumn(0).setcellrenderer(new numbertablecellrenderer()); setlayout(new borderlayout()); add(new jscrollpane(table)); } public class numbertablecellrenderer extends defaulttablecellrenderer { public numbertablecellrenderer() { sethorizontalalignment(jlabel.right); } @override public component gettablecellrenderercomponent(jtable table, object value, boolean isselected, boolean hasfocus, int row, int column) { if (value instanceof number) { value = numberformat.getnumberinstance().format(value); } return super.gettablecellrenderercomponent(table, value, isselected, hasfocus, row, column); } } } }
Comments
Post a Comment