To change the font of a selected row in a Jtable

Hello,
Is it possible to change the font of a selected row in a jtable?
i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
thank you.

String will be left justified
Integer will be right justified
Date will be a simple date without the time.
As it will with this renderer.Only if your custom renderer duplicates the code
found in each of the above renderers. This is a waste
of time to duplicate code. The idea is to reuse code
not duplicate and debug again.
No, no, no there will be NO duplicated code.
A single renderer class can handle all types ofdata.
Sure you can fit a square peg into a round hole if
you work hard enough. Why does the JDK come with
separate renderers for Date, Integer, Double, Icon,
Boolean? So that, by default the rendering for common classes is done correctly.
Because its a better design then having code
with a bunch of "instanceof" checks and nested
if...else code.This is only required for customization BEYOND what the default renderers provide
>
And you would only have to use instanceof checkswhen you required custom
rendering for a particular classAgreed, but as soon as you do require custom
renderering you need to customize your renderer.
which you would also have to do with theprepareRenderer calls too
Not true. The code is the same whether you treat
every cell as a String or whether you use a custom
renderer for every cell. Here is the code to make the
text of the selected line(s) bold:
public Component prepareRenderer(TableCellRenderer
renderer, int row, int column)
Component c = super.prepareRenderer(renderer, row,
, column);
     if (isRowSelected(row))
          c.setFont( c.getFont().deriveFont(Font.BOLD) );
     return c;
}It will work for any renderer used by the table since
the prepareRenderer(...) method returns a Component.
There is no need to do any kind of "instanceof"
checking. It doesn't matter whether the cell is
renderered with the "Object" renderer or the
"Integer" renderer.
If the user wants to treat all columns as Strings or
treat individual columns as String, Integer, Data...,
then they only need to override the getColumnClass()
method. There is no change to the prepareRenderer()
code.
Have you actually tried the code to see how simple it
is?
I've posted my code. Why don't you post your solution
that will allow the user to bold the text of a Date,
Integer, and String data in separate column and then
let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Vector;
public class TableRendererDemo extends JFrame{
    String[] headers = {"String","Integer","Float","Boolean","Date"};
    private JTable table;
    public TableRendererDemo() {
        buildGUI();
    private void buildGUI() {
        JPanel mainPanel = (JPanel) getContentPane();
        mainPanel.setLayout(new BorderLayout());
        Vector headerVector = new Vector(Arrays.asList(headers));
         Vector data = createDataVector();
        DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
            public Class getColumnClass(int columnIndex) {
                return getValueAt(0,columnIndex).getClass();
        table = new JTable(tableModel);
//        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
        table.setDefaultRenderer(String.class, new MyTableCellRenderer());
        table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
        table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
        table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
        JScrollPane jsp = new JScrollPane(table);
        mainPanel.add(jsp, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    private Vector createDataVector(){
        Vector dataVector = new Vector();
        for ( int i = 0 ; i < 10; i++){
            Vector rowVector = new Vector();
            rowVector.add(new String("String "+i));
            rowVector.add(new Integer(i));
            rowVector.add(new Float(1.23));
            rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
            rowVector.add(new Date());
            dataVector.add(rowVector);
        return dataVector;
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            public void run() {
                TableRendererDemo tableRendererDemo = new TableRendererDemo();
                tableRendererDemo.setVisible(true);
        SwingUtilities.invokeLater(runnable);
    class MyTableCellRenderer extends DefaultTableCellRenderer{
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
             super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if ( isSelected){
                setFont(getFont().deriveFont(Font.BOLD));
            else{
                setFont(getFont().deriveFont(Font.PLAIN));
            if ( value instanceof Date){
                SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                setText(formatter.format((Date)value));
            if(value instanceof Number){
               setText(((Number)value).toString());
            return this;
}Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
Cheers
DB

Similar Messages

  • Change the font of a selected text

    First of all sorry for my english because i'm spanish. I'm doing a simple text editor 100% compatible with all the web browsers. The editor must to have the option of change the font of a selected text. I don't know how to do this. Thank you.

    you should look at examples that are provided with swing package, there are some simple texteditors, and then of course you should start thinking in AWT to make your editor compatible with all browsers as you wanted...
    if you want to use TextArea in your editor then you must remember that in one textarea you can use only one Font at the time... as well as you may not use different colors for different parts of text, but with such textarea you may create thing like Notepad in windows.
    L.

  • The columns of a selected row in a JTable

    Hello guys,
    I am trying to loop through the columns of a selected row in a JTable. Any ideas how i can do that?
    Thanks in advance for your replies.
    Antana.

    there is getValueAt(int row, int column) method in JTable.
    will this help you?
    and please post swing related queries to swing forum.
    --Azodious_                                                                                                                                                                                                                                                                                                           

  • Change the background color of selected row in adf table

    Hi,
    Can somebody guide me in changing the background color of a row when its being selected. In my ADF table, one of the column is of type Command Link. So whenever i click this command link on any particular row that complete row color should change as an indication of that row being selected.
    Please guide me to do this. I referred to other forum posts, but they couldnt meet my need.
    Thanks
    ri

    Hi Frank,
    you're right. This should work. But the result is not perfect from my point of view.
    I use
    <af:table ...>
      <af:column ...>
        <af:outputText value="#{row.col1}" inlineStyle="#{row.mystyle}"/>
      </af:column>
    </af:table>and I get e.g. this in HTML:
    <table ...>
      <tr>
        <td class="af_column_cell-text OraTableBorder1111"><span style="font-weight:bold;">qqq</span></td>
      </tr>
    </table>while I would prefer to get somethig like this:
    <table ...>
      <tr>
        <td style="font-weight:bold;"><span>qqq</span></td>
      </tr>
    </table>, which looks much smarter. Is it possible?
    Thanks,
    Alexandre.

  • How do I change the colour of a selected cell in a jTable?

    I have a Jtable that displays URL names in one column. There are several problems I'm having. The effect I'm trying to achieve is this:
    When the user runs the mouse over the URL name the cursor should change into a hand (similar to what happens in an HTML hyperlink). I'm aware that the Cursor class can set the cursor graphic so i figure that i need a listener of some sort on each cell (so the cursor can change from an arrow to a hand) and also one to indicate when the cursor is not on a cell (so that it can change from a hand back into an arrow). Is this the right track?
    Also, I've looked at the DefaultTableCellRenderer class (which, as i understand it, is responsible for how each cell in the jtable is displayed) for a method that will allow me to set the background of a selected cell (or row or column). I require this because each time i select a cell (or row) it becomes highlighted in blue. I would rather it just remained white and changed the cursor to a hand. I know there exists a method for setting the background for an unselected cell but none for a selected cell. Again, I'm not sure if I'm going down the right track with this approach.
    Lastly, if the cell has been selected (by a mouse click) the font of the writing in the cell (i.e. The name of the URL) should change. This shouldn't be too much of a problem I think.
    I do not expect anyone to provide code to do all of this but some general pointers would be extremely helpful as I do not know if I'm thinking on the right track for any of this. Having some (limited) experience with Swing I doubt there is a simple way to do this but I can only hope!
    Thanks.
    Chris

    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    there you can find some examples with CellRenderer's and so on ...
    have fun

  • Change the color of a particular row in a jtable

    I have a jtable and i want to change the color of one particular column and few rows to blue and underline the text depending on some condition. In my view class if a condition is true
    for( count=0;count<grdTest.getRowcount;count++)
    if(some condition true)
    grdTest.getColumnModel().getColumn(0).
    setCellRenderer(new MyTestCellRenderer(count));
    And my cell renderer
    public class MyTestCellRenderer extends DefaultTableCellRenderer {
    int rowIndex=-1;
    public MyTestCellRenderer(int rowcount) {
    super();
    rowIndex=rowcount;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value,
    isSelected, hasFocus, row, column);
    if(row == rowIndex)
    setText("<html> <u> <font color='blue'>" + value.toString());
    return this;
    This is behaving very wierd . If suppose there are 50 rows and all of them have the condition true then only the last one in the row color is changes.
    However if only one out othe say10 has the condition true then it changes the color and underlines the particular row,column.
    Is there any other way to do this or what i am doing wrong
    Thanks

    if(row == rowIndex)Your code is a shambles because of the lack of tags, but I don't believe I see anything being called when this boolean condition is not true. That would be a problem.                                                                                                                                                                                                                                                                                                                                                                                                           

  • Overriding the SelectionForegroundColor of a selected row in a JTable

    Hi
    First, apologize for my poor English.
    I looked for a similar topic in the forum, but coudn't find one.
    What I want to achieve is this :
    upon data contained in a column, I want the foreground color of the row to be gray. To do this, I write my own TableCellRenderer and it works perfectly except for the unique selected row of the table (single selection model) whose foreground color is the table's selectionForegroundColor.
    I found a workaround...but the code is awful and leads to OutOfMemoryErrors.
    Here is the code :
    <
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column) {
         boolean isGrayColored = false;
         // some process to set whether the foreground color should be gray
         if (isGrayColored) {
              //table.setSelectionForeground(Color.gray);
              setForeground(Color.gray);
         } else {
              //table.setSelectionForeground(Color.black);
              setForeground((isSelected) ? table.getSelectionForeground() : table.getForeground());
         if (table != null && value == null && isSelected && hasFocus) {
              return this;
         } else {
              return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    >
    If I uncomment the lines "table.setSelectionForeground(..", I got the expected result.
    Thanks for your help
    Regards,

    Try this:
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
             if (isSelected && hasFocus) {
                setForeground(Color.black);
             } else {
                setForeground(Color.gray);
             setText((value==null)?"":""+value);
             return this;
          };o)
    V.V.
    PS: If it helps, don't forget the dukes!

  • How can i change the color of an entire row of a JTable ?

    Hi all,
    I have a JTable with 4 columns; I have to change the background color of the rows which have a certain value contained on the fourth column.
    So, if a row has, on its fourth column, a particular value...this row must change background color.
    Any suggestion ?
    Cheers.
    Stefano

    Hi,
    this is a good solution that works fine for me :
    the Object "resources" is a List of String.
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
              JLabel retValue;
              retValue = ( JLabel ) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              if (column == 0) {
                   String s = (String)table.getModel().getValueAt(row, 3);
                   if ( !"".equals(s) && resourcers.contains(s) ) {
                             setBackground(table.getSelectionBackground());
                   } else {
                             setForeground(table.getForeground());
                             setBackground(table.getBackground());
         return retValue;
    Cheers.
    Stefano

  • Jtable: How to change the color of an entire row?

    How can I change the color on an entire row in a Jtable based upon the value in one of the cells in that row.
    For example: Lets say:
    I have 5 rows. Each row has 4 columns.
    If column 4 has a value "A" in any of the rows, all the text in that row should be red.
    If column 4 has a value "B" in any of the rows, all the text in that row should be blue.
    Just point me in the right direction and I will try to take it on from there.
    Thanks

    In the future, Swing related questions should be posted in the Swing forum.
    But there is no need to repost because you can search the Swing forum for my "Table Prepare Renderer" (without the spaces) example which shows how this can be done.
    But first read the tutorial link given above.

  • When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the test and change the font, it does not change it properly?

    When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the text and change the font, it does not change it properly? This is making it impossible to amend.

    Hi Janedance1,
    If the PDF that you converted already has searchable text, please try disabling OCR as described in this document: How to disable Optical Character Recognition (OCR) when converting PDF to Word or Excel. (If the PDF was created from a scanned document and doesn't already have searchable text, disabling OCR isn't a great option, as the text won't be searchable/editable in the converted Word doc.)
    Please let us know how it goes.
    Best,
    Sara

  • How to Change the Font Size in Module Pool Selection Screen?

    Hi,
    There is a module pool, and I need to change the font size mentioned in the selection screen. Could you plaese tell me, how will I be able to do that?

    Hi ,
    If you are asking for text field , then check the options avaliable in Display tab of Attributes.
    Hope this helps you.

  • Rs to do, and I selected the font for each 4s clip - now I want to change the font - is there a way to change all fonts on clips in one go?

    Hi I am new to iMovie - and made a 35min film - quite pleased with it - I sub-titled it right through coz we work with deaf people - wanted my first movie to be accessible. Now I want to change the font on each clip - can I do this in one step - and change all the sub-titles to a different font - thanks a lot, Jane

    Maybe some one else can pipe up with a solution, but this would literally take 2 seconds to do for a new project.  And you can create a "template project" that includes this "text" clip.  Save this project and then to a get info and check "stationary pad."  When you double click on this file, fcp will open with a copy of this project and you just need to do a save as. 
    I've been working with computer editing systems for longer than i can remember and at a certain point you just have to adapt your workflow to the limitations of the software.  

  • Crash when changing the font, when will the bug finally eliminated ???

    It is known that muse constantly crashed since 2014.2 update, why is nothing done?

    Updated to 2014.2 about 3 or 4 days ago... this morning, while trying to put the finishing touches on my client's website, I began experiencing this problem. It is so frustrating!!!
    Though this is an annoying route to take, I was able to change the font by selecting all text within a box, then copying it, deleting it, and pasting it back in the box after selecting the new font that I wanted.
    HOWEVER, for some reason, you can't change fonts 2x or more in a row. If you have more than one change, you must do something else in between. Meaning, go through the copy & paste thing that I said... then edit something other than a font (if you don't have to do this, do it anyway and then undo it...) before editing another font.
    Hopefully Adobe will help us out on this one soon... good luck!

  • How can I change the font and color of an email signature?

    How can i change the font and color of an email signature?

    Mail > Preferences > Signature
    Highlight the Signature.
    Click Format in the menu bar and select " Show Fonts".
    Select the Font.
    Highlight the Text.
    Click Format in the menu bar and select " Show Colors".
    Select the color.
    Mail > Preferences > Composing > Message Format:  Rich Text
    Best.

  • How do I change the font on this new 27" IMac I have just bought for 2200.00 and can't read as the font is far too small.I have contact lens and but have to strain with face close to the screen to see the words. What a major rip off disappointment ,

    I have spent hours trolling through help lines to change the font from minature text  which I cannot see on my new 27" screen. Why does something so simple have to be so complicated ???this computer is supposed to be the be all to end all..just setting it up with printer , router etc has been a nightmare as the print is so small I need to have my eyes 2 inches from the screen to read anything ..What have they done ?

    Not an ideal solution, but some users change the setting in: System Preferences>Displays, select the Scaled button and choose another resolution.
    If you are within 14 days of purchased you can return the computer for a refund if you dislike it that much as Apple do have a good returns policy (so long as you purchased from Apple and not a reseller).

Maybe you are looking for