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()
and getSelectedColumn()
methods out of the box, so no need to write the for
loops 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
. When JTable
s need to render a cell, they pass all the information about that cell (its value, whether or not it is selected, etc.) along to a TableCellRenderer
. There is a DefaultTableCellRenderer
installed by default, which renders your cells as JLabels
. You can set your own renderer using setDefaultRenderer()
. In your case, it should be very easy to extend DefaultTableCellRenderer
, override getTableCellRendererComponent()
to call super()
, and then once super()
returns, set the font to bold if the cell is selected.
The javadoc for JTable
has 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.