Skip to main content

Font in Jtable

1 reply [Last post]
shobhit
Offline
Joined: 2004-09-27

Hello everybody,
Sir i m using a JTable component.i have appended a menu item font .by pressing font menu a dialog box is called by that user can select Font-Type,Style and size.Now i want --by pressing ok bttn selected range of cell's font should be changed according to selected style,Size and type.i have problem that setFont() can only be applied to Component object.and a cell is not a component object.
for that i m trying to use
Component cell=DefaultTableCellRenderer.getTableCellRendererComponent(.......),but it is not returning component for particular cell. how can i do it.
Pls keep in mind i m using DefaultTableModel. How can i do it.pls help me out from that problem.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
shan-man
Offline
Joined: 2006-02-17

Hi Shobhit,

There are two approaches you could consider here. Both of them will require you to keep your own mapping of row/column to font. Let's say you create some data structure to store this information and you implement the following methods:

Font setFontFor(int row, int col, Font font)
Font getFontFor(int row, int col)

Here's how you could use it:

When you need to change the font of particular cells, save the mapping by calling setFontFor() for each cell that you want to change.

To pick this information up in JTable, do one of the following:

1) Write a custom table cell renderer and set the font within the renderer. Something like this would do:
[code]
class MyRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component comp = super.getTableCellRendererComponent(table,
value,
isSelected,
hasFocus,
row,
column);

// this is where you set your custom font
Font f = getFontFor(row, column);
if (f != null) {
comp.setFont(f);
}

return comp;
}
}
[/code]
You would then install this using JTable.setDefaultRenderer().

2) The second approach I actually like better as it leaves JTable's default renderers alone. Instead of providing a custom renderer, you override JTable.prepareRenderer() to customize the font of the rendering component. This approach would look like this:
[code]
class FontTable extends JTable {
public Component prepareRenderer(TableCellRenderer renderer,
int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);

// this is where you set your custom font
Font f = getFontFor(row, column);
if (f != null) {
comp.setFont(f);
}

return comp;
}
}
[/code]
And of course, you could override prepareEditor() too to customize the font of editable cells.

Hope this all helps :)
Shannon