Possible Duplicate:
Swing – Setting the color of a cell based on the value of a cell
I have a Spreadsheet class, containing a JTable and its TableModel.
And my main window contains this spreadsheet and a list of buttons, with for example a bold one.
I can successfully get the selected cell (see code below), but I have no idea of how to change its content and font, color etc.
public void actionPerformed(ActionEvent e)
{
int rowToUpdate = -1, columnToUpdate = -1;
for(int i = 0 ; i < tableToUpdate.getRowCount() ; i++)
for (int j = 0 ; j < tableToUpdate.getColumnCount() ; j++)
if(tableToUpdate.isCellSelected(i, j)){ rowToUpdate = i; columnToUpdate = j; }
if(rowToUpdate >= 0 && columnToUpdate >= 0)
{
if(e.getSource == boldButton)
{
// Here, how to change the bold of the cell(rowToUpdate,columnToUpdate)
}
}
}
Couple things: first, the code you wrote could be a lot simpler. JTable comes with
getSelectedRow()andgetSelectedColumn()methods out of the box, so no need to write theforloops yourself.That being said, if you are just trying to change the way that the selected cell is rendered, you probably don’t actually want to do any of this anyway. The way to change the how a cell is rendered is to use a
TableCellRenderer. WhenJTables need to render a cell, they pass all the information about that cell (its value, whether or not it is selected, etc.) along to aTableCellRenderer. There is aDefaultTableCellRendererinstalled by default, which renders your cells asJLabels. You can set your own renderer usingsetDefaultRenderer(). In your case, it should be very easy to extendDefaultTableCellRenderer, overridegetTableCellRendererComponent()to callsuper(), and then oncesuper()returns, set the font to bold if the cell is selected.The javadoc for
JTablehas a link to the JTable tutorial which has a special section on using custom renderers. That tutorial (along with a bunch of other great Swing tutorials) can be found at http://docs.oracle.com/javase/tutorial/uiswing/components/table.html.