java - Change background color of JTable row based on column value issue -
based on this question did this:
public class showticketplanning extends javax.swing.jframe { private static string prevticket=""; private static int color=1; public showticketplanning() { initcomponents(); (int = 0; < c.gamelist.size(); i++) { gameselectgamecb.additem(c.gamelist.get(i).printforlist()); } } private void gameselectgamecbactionperformed(java.awt.event.actionevent evt) { int ind = gameselectgamecb.getselectedindex(); if (c.gamelist.size() > 0) { defaulttablemodel tmodel = (defaulttablemodel) dbgplantbl.getmodel(); while (tmodel.getrowcount() > 0) { tmodel.removerow(0); } string columnnames[] = new string[c.dbglist.get(ind).getdrawdaylist().size()]; int gamedrawsize = c.dbglist.get(ind).getdrawdaylist().size(); (int z = 0; z < gamedrawsize; z++) { columnnames[z] = c.dbglist.get(ind).getdrawdaylist().get(z).getdrawnumber() + ":" + c.dbglist.get(ind).getdrawdaylist().get(z).getcdc() + ":" + es.daytoshortday(c.dbglist.get(ind).getdrawdaylist().get(z).getday()); } string datavalues[][] = {}; defaulttablemodel model = new defaulttablemodel(datavalues, columnnames); dbgplantbl.setmodel(model); (int t = 0; t < c.ticketlist.size(); t++) {//for tickets (int b = 0; b < c.ticketlist.get(t).getboardlist().size(); b++) { object[] ob = new object[gamedrawsize]; (int brpd = 0; brpd < c.ticketlist.get(t).getboardlist().get(b).getboardresultperdrawlist().size(); brpd++) { int d = c.ticketlist.get(t).getboardlist().get(b).getboardresultperdrawlist().get(brpd).getdrawindex(); if (c.dbglist.get(ind).ishasraffle()) { ob[d] = c.ticketlist.get(t).getticketrefname() + ":" + b + ":" + c.ticketlist.get(t).getboardlist().get(b).getboardresultperdrawlist().get(brpd).getnumberresult() + ":" + c.ticketlist.get(t).getboardlist().get(b).getboardresultperdrawlist().get(brpd).getraffleresult(); } else { ob[d] = c.ticketlist.get(t).getticketrefname() + ":" + b + ":" + c.ticketlist.get(t).getboardlist().get(b).getboardresultperdrawlist().get(brpd).getnumberresult(); } } model.addrow(ob); } } defaulttablemodel amodel = (defaulttablemodel) dbgplantbl.getmodel(); int tablesize = dbgplantbl.getrowcount(); //system.out.println("rows:"+tablesize); int tablecol = dbgplantbl.getcolumncount(); //system.out.println("cols:"+tablecol); (int r = 0; r < tablesize; r++) { (int col = 0; col < tablecol; col++) { if (amodel.getvalueat(r, col) == null) { } else { dbgplantbl.setdefaultrenderer(object.class, new showticketplanning.customrenderer()); dbgplantbl.getcelleditor(r, col).gettablecelleditorcomponent(dbgplantbl, dbgplantbl.getvalueat(r, col), true, r, col).setforeground(color.red); } } } //define column width.............. tablecolumnmodel tcm = dbgplantbl.getcolumnmodel(); (int = 0; < (tcm.getcolumncount()); i++) { tcm.getcolumn(i).setpreferredwidth(120); } dbgplantbl.setdefaultrenderer(object.class, new showticketplanning.customrenderer()); } }
class customrenderer extends defaulttablecellrenderer { public component gettablecellrenderercomponent(jtable table, object value,boolean isselected, boolean hasfocus, int row, int column) { component c = super.gettablecellrenderercomponent(table, value, isselected, hasfocus, row, column); if (value == null) { setbackground(new java.awt.color(255, 255, 255)); } else { stringtokenizer st2 = new stringtokenizer(value.tostring(), ":"); string ref = st2.nextelement().tostring(); if (prevticket.equals(ref)) { if (color == 1) { setbackground(new java.awt.color(204, 204, 204)); } else { setbackground(new java.awt.color(255, 255, 255)); } } else { if (color == 1) { color = 2; } else { color = 1; } if (color == 1) { setbackground(new java.awt.color(204, 204, 204)); } else { setbackground(new java.awt.color(255, 255, 255)); } } prevticket=ref; } return c; } }
so have tickets each ticket has more 1 board. , want change color per ticket.
result:
the colors correct, after scrolling colors become irregular following image.
note: each "ticket0, ticket1, ticket2" etc should have alternating colors.
feel free check out how snippet solves problem , apply in own program.
i'll have disclaim saying i'm not sure best way this, works in sense doesn't have odd behavior describing (row coloring getting messed when scrolling). added code account sorting events , inserting/deleting/updating rows.
my snippet keeps track of colors in array, once color established row doesn't establish again. renderer gets color color store.
for explanation of snippet does, see comments inside.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class tablewithalternatingcolorsexample { @suppresswarnings("serial") private static class alternatingcoloronkeyrenderer extends defaulttablecellrenderer { /* alternating colors */ public static final color color1 = new color(204,204,204); public static final color color2 = new color(255,255,255); /** model index of key column, ie model column key derived. */ public static final int modelkeycolid = 0; /** color store stores colors each row in view. * indexed view index retrieve color row in view. */ private arraylist<color> colorstore = new arraylist<>( ); /** reset colors in color store. */ public void resetallcolors() { colorstore = new arraylist<>(math.max(10,colorstore.size())); } /** reset colors in color store view index on. */ public void resetcolorsfrom(int row) { if(row==0) resetallcolors(); else { arraylist<color> retainedcolors = new arraylist<>(math.max(10,colorstore.size())); retainedcolors.addall(colorstore.sublist(0,math.min(row-1,colorstore.size()-1))); // copy retained colors colorstore = retainedcolors; } } /** determines key value cell value. */ private object getcellkeyval(object cellvalue) { return new stringtokenizer(cellvalue.tostring(),":").nextelement(); } /** retrieves key value row. */ private object getrowkeyval(jtable t,int viewrowid) { int modelrowid = t.convertrowindextomodel(viewrowid); // convert row view index model index index model object cellvalue = t.getmodel().getvalueat(modelrowid,modelkeycolid); // cell value model, because column might not present in view return getcellkeyval(cellvalue); } /** prepares color store row in view. * after calling method colors range [0,row] present in color store. * call method ensure <i>colorstore.get(row)</i> return color. */ private void preparecolorstore(jtable t,int row) { if(colorstore.size()>row) return; // color present row if(colorstore.isempty()) colorstore.add(color1); // if color store empty, start first color if(row==0) return; object curkeyval = getrowkeyval(t,colorstore.size()-1); while(colorstore.size()<=row) { // add colors until color present row object prevkeyval = curkeyval; curkeyval = getrowkeyval(t,colorstore.size()); if(prevkeyval.equals(curkeyval)) // compare key values between current , previous row colorstore.add(colorstore.get(colorstore.size()-1)); // add previous color in store when key values equal else if(colorstore.get(colorstore.size()-1)==color1) // reference compare because color instances fixed colorstore.add(color2); // add alternating color when key values differ else colorstore.add(color1); } } @override public component gettablecellrenderercomponent(jtable table,object value,boolean isselected,boolean hasfocus,int row,int column) { component c = super.gettablecellrenderercomponent(table,value,isselected,hasfocus,row,column); if(!table.isrowselected(row)) { preparecolorstore(table,row); // ensure color present row c.setbackground(colorstore.get(row)); // set color color store } return c; } }; private static jtable createtable() { vector<vector<object>> rowdata = new vector<>( arrays.aslist( new vector<>(arrays.aslist(new object[]{"ticket0:0::","ticket0:0::","ticket0:0::","ticket0:0::","ticket0:0::","ticket0:0::","ticket0:0::","ticket0:0::"})), new vector<>(arrays.aslist(new object[]{"ticket25:1::","ticket25:1::","ticket25:1::","ticket25:1::","ticket25:1::","ticket25:1::","ticket25:1::","ticket25:1::"})), new vector<>(arrays.aslist(new object[]{"ticket0:1::","ticket0:1::","ticket0:1::","ticket0:1::","ticket0:1::","ticket0:1::","ticket0:1::","ticket0:1::"})), new vector<>(arrays.aslist(new object[]{"ticket1:0::","ticket1:0::","ticket1:0::","ticket1:0::","ticket1:0::","ticket1:0::","ticket1:0::","ticket1:0::"})), new vector<>(arrays.aslist(new object[]{"ticket1:1::","ticket1:1::","ticket1:1::","ticket1:1::","ticket1:1::","ticket1:1::","ticket1:1::","ticket1:1::"})), new vector<>(arrays.aslist(new object[]{"ticket10:0::","ticket10:0::","ticket10:0::","ticket10:0::","ticket10:0::","ticket10:0::","ticket10:0::","ticket10:0::"})), new vector<>(arrays.aslist(new object[]{"ticket10:1::","ticket10:1::","ticket10:1::","ticket10:1::","ticket10:1::","ticket10:1::","ticket10:1::","ticket10:1::"})), new vector<>(arrays.aslist(new object[]{"ticket11:0::","ticket11:0::","ticket11:0::","ticket11:0::","ticket11:0::","ticket11:0::","ticket11:0::","ticket11:0::"})), new vector<>(arrays.aslist(new object[]{"ticket11:1::","ticket11:1::","ticket11:1::","ticket11:1::","ticket11:1::","ticket11:1::","ticket11:1::","ticket11:1::"})), new vector<>(arrays.aslist(new object[]{"ticket12:0::","ticket12:0::","ticket12:0::","ticket12:0::","ticket12:0::","ticket12:0::","ticket12:0::","ticket12:0::"})), new vector<>(arrays.aslist(new object[]{"ticket12:1::","ticket12:1::","ticket12:1::","ticket12:1::","ticket12:1::","ticket12:1::","ticket12:1::","ticket12:1::"})), new vector<>(arrays.aslist(new object[]{"ticket13:0::","ticket13:0::","ticket13:0::","ticket13:0::","ticket13:0::","ticket13:0::","ticket13:0::","ticket13:0::"})), new vector<>(arrays.aslist(new object[]{"ticket13:1::","ticket13:1::","ticket13:1::","ticket13:1::","ticket13:1::","ticket13:1::","ticket13:1::","ticket13:1::"})), new vector<>(arrays.aslist(new object[]{"ticket14:0::","ticket14:0::","ticket14:0::","ticket14:0::","ticket14:0::","ticket14:0::","ticket14:0::","ticket14:0::"})), new vector<>(arrays.aslist(new object[]{"ticket17:0::","ticket17:0::","ticket17:0::","ticket17:0::","ticket17:0::","ticket17:0::","ticket17:0::","ticket17:0::"})), new vector<>(arrays.aslist(new object[]{"ticket14:1::","ticket14:1::","ticket14:1::","ticket14:1::","ticket14:1::","ticket14:1::","ticket14:1::","ticket14:1::"})), new vector<>(arrays.aslist(new object[]{"ticket15:0::","ticket15:0::","ticket15:0::","ticket15:0::","ticket15:0::","ticket15:0::","ticket15:0::","ticket15:0::"})), new vector<>(arrays.aslist(new object[]{"ticket15:1::","ticket15:1::","ticket15:1::","ticket15:1::","ticket15:1::","ticket15:1::","ticket15:1::","ticket15:1::"})), new vector<>(arrays.aslist(new object[]{"ticket16:0::","ticket16:0::","ticket16:0::","ticket16:0::","ticket16:0::","ticket16:0::","ticket16:0::","ticket16:0::"})), new vector<>(arrays.aslist(new object[]{"ticket16:1::","ticket16:1::","ticket16:1::","ticket16:1::","ticket16:1::","ticket16:1::","ticket16:1::","ticket16:1::"})) )); vector<object> coldata = new vector<>(arrays.aslist(new object[]{"1:103:wed","2:106:sat","3:110:wed","4:110:sat","5:117:wed","6:120:sat","7:124:wed","8:127:sat"})); final jtable t = new jtable(rowdata,coldata); defaulttablecellrenderer tcr = new alternatingcoloronkeyrenderer(); enumeration<tablecolumn> e = t.getcolumnmodel().getcolumns(); while(e.hasmoreelements()) e.nextelement().setcellrenderer(tcr); // table columns share same alternatingcoloronkeyrenderer instance t.setautocreaterowsorter(true); /* when row sorter changes, reset colors in color store. * when row sorting changes, row view indices point different rows in model, color store needs reset. */ t.getrowsorter().addrowsorterlistener(new rowsorterlistener() { @override public void sorterchanged(rowsorterevent e) { ((alternatingcoloronkeyrenderer) t.getcolumnmodel().getcolumn(0).getcellrenderer()).resetallcolors(); // rows share same alternatingcoloronkeyrenderer instance, pick renderer first column , reset color store } }); /* add model listener listen inserted/deleted/updated rows. when rows inserted/deleted/updated, row colors change subsequent rows. * determines minimum view index inserted/deleted/updated rows, resets color store view index on. */ t.getmodel().addtablemodellistener(new tablemodellistener() { @override public void tablechanged(tablemodelevent e) { int minviewid; switch(e.gettype()) { case tablemodelevent.insert: case tablemodelevent.delete: minviewid = integer.max_value; for(int r=e.getfirstrow();r<=e.getlastrow();++r) { // determine minimum view index inserted/deleted rows int viewid=t.convertrowindextoview(r); // convert model index view index if(viewid>=0 && viewid<minviewid) // due filtering, possible inserted/deleted rows not visible in view (convert return -1 in case) minviewid=viewid; } if(minviewid!=integer.max_value) // if of inserted/deleted rows visible, reset color store minimum view index on ((alternatingcoloronkeyrenderer) t.getcolumnmodel().getcolumn(0).getcellrenderer()).resetcolorsfrom(minviewid); break; case tablemodelevent.update: int r = e.getfirstrow(); if(r==tablemodelevent.header_row) return; // outside scope example if(e.getcolumn()!=tablemodelevent.all_columns && e.getcolumn()!=alternatingcoloronkeyrenderer.modelkeycolid) return; // listen updates in key column minviewid = integer.max_value; for( ;r<=e.getlastrow();++r) { // determine minimum view index updated rows int viewid=t.convertrowindextoview(r); // convert model index view index if(viewid>=0 && viewid<minviewid) // due filtering, possible updated rows not visible in view (convert return -1 in case) minviewid=viewid; } if(minviewid!=integer.max_value) { // if of updated rows visible, reset color store minimum view index on & repaint ((alternatingcoloronkeyrenderer) t.getcolumnmodel().getcolumn(0).getcellrenderer()).resetcolorsfrom(minviewid); t.repaint(); // repaint necessary update events update colors in view } break; } } }); return t; } protected static jbutton createaddbutton(final jtable t) { jbutton button = new jbutton("add row randomly"); button.addactionlistener(new actionlistener() { @suppresswarnings("unchecked") @override public void actionperformed(actionevent e) { defaulttablemodel dtm = (defaulttablemodel) t.getmodel(); vector<object> newrow = new vector<>(arrays.aslist(new object[]{"ticket77:0::","ticket77:0::","ticket77:0::","ticket77:0::","ticket77:0::","ticket77:0::","ticket77:0::","ticket77:0::"})); int index = new random().nextint(t.getrowcount()+1); // random index insert if(index<t.getrowcount()) dtm.getdatavector().add(index,newrow); // use datavector defaulttablemodel insert else dtm.getdatavector().add(newrow); dtm.firetablerowsinserted(index,index); // notify view row inserted } }); return button; } public static void main(string[] args) { swingutilities.invokelater(new runnable() { @override public void run() { jframe f = new jframe(); f.setdefaultcloseoperation(jframe.exit_on_close); f.setlayout(new borderlayout()); jtable t = createtable(); f.add(new jscrollpane(t),borderlayout.center); f.add(createaddbutton(t),borderlayout.south); f.setsize(500, 500); f.setvisible(true); } }); } }
Comments
Post a Comment