Centering text in a cell in a JTable

Hi,
I have a program that reads in data from a text file and display it in a JTable. My problem is that the data in each cell is not centered, it is left justified within that cell.
How can I fix this.
--kirk                                                                                                                                                                                                                                                                                                                                                                                                                                            

To align a text inside a cell you have to go through the rendering classes of a Jtable. You can do lots of formatting by using a render class. Heres my code that i use.
1. The first code aligns your data centered inside the cell.
2. The second code aligns it like code1 but has an additional character to be printed beside your data inside the text.
///////////// TO USE THE RENDER CODE IN YOUR APPLICATION /////
TableColumn col1 = table.getColumnModel().getColumn(1);
col1.setCellRenderer( new SimpleRenderer());
or
TableColumn col1 = table.getColumnModel().getColumn(1);
col1.setCellRenderer( new SimpleRenderer( "$" ));
///////////// RENDER CODE IS HERE //////////////
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.*;
public class SimpleRenderer extends JLabel implements TableCellRenderer
     Border unselectedBorder = null;
     Border selectedBorder = null;
     String text = "";
     Color foreColor = Color.black;
     Color backColor = new java.awt.Color( 217,217,255 );
     Color selectedColor = new java.awt.Color( 217,217,255 );
     public SimpleRenderer()
     super();
     setHorizontalAlignment( JLabel.CENTER );
     setOpaque( true );
     } // end of CONSTRUCTOR
     public SimpleRenderer( Color foreGround, Color backGround )
     super();
     setHorizontalAlignment( JLabel.CENTER );
     setOpaque( true );
     this.foreColor = foreGround;
     this.backColor = backGround;
     } // end of CONSTRUCTOR
     public SimpleRenderer( String data )
     super();
     text = data;
     setHorizontalAlignment( JLabel.CENTER );
     setOpaque( true );
     } // end of CONSTRUCTOR
     public Component getTableCellRendererComponent(
          JTable table, Object object, boolean isSelected, boolean hasFocus,
                                                                                int row, int column)
     try
          if ( backColor != null )
               if ( (row % 2 ) == 1 )
                         setBackground( backColor );
               else
                         setBackground( Color.white );
          if ( foreColor != null )
               setForeground( foreColor );
          if ( hasFocus )
               if ( isSelected )
                         setBackground( selectedColor );
               else
                         setBackground( Color.white );
          String newData = "" + object;
          if ( newData.trim().equals( "" ))
               setText( "" );
          else
               setText( text + " " + object );
          if (isSelected)
          if (selectedBorder == null)
               Border border, raisedBevel, loweredBevel;
               raisedBevel = BorderFactory.createRaisedBevelBorder();
               loweredBevel = BorderFactory.createLoweredBevelBorder();
               Border colorLine = BorderFactory.createLineBorder(Color.red);
               border = BorderFactory.createCompoundBorder( raisedBevel,loweredBevel);
               selectedBorder = BorderFactory.createCompoundBorder( border, colorLine);
          setBorder(selectedBorder);
          else
          if (unselectedBorder == null)
                    unselectedBorder = BorderFactory.createMatteBorder(0,0,0,0,
                    table.getBackground());
          setBorder(unselectedBorder);
     catch( ClassCastException e )
     return this;
     } // end of GETTABLECELLRENDERERCOMPONENT method.
     public void setForeColor( Color data )
     foreColor = data;
     } // end of SETFORECOLOR method.
     public void setBackColor( Color data )
     backColor = data;
     } // end of SETBACKCOLOR method.
} /** end of CLASS **/
/////////////

Similar Messages

  • How do I change the colour of text in a cell in a JTable?

    I am trying to change the color of the text in a single cell in a JTable. I have tried not adding a cell renderer and it changes the colour of text in all cells.
    I have tried adding a cell renderer to the table and it does the same ie all cells text colour changes.
    I am able to add a cell renderer to a column and it changes all the cells in the column.
    I cannot figure out how to change just one single cell's text colour without effecting the other cells.

    Ok, so if i create my own cell renderer do I set it as the default renderer for the whole table i.e.
    table.setDefaultRenderer(MyCellRenderer, renderer);
    Does this set one cell renderer for the whole table or is there an individual one for each cell?

  • Getting right end of text displayed in cells of a JTable column

    Hey All,
    Platform: WinXP, Java 5.0.
    I have a simple one-column table whose cells contain pathnames of user-selected files. The pathnames may be quite long, and when they're too long for the fixed width of the column (the containing JFrame is not resizable), I want the trailing (right) end of the pathnames to visible (so the filenames are visible) and for elipsis to be used on the left side (omitting root directory, etc., if need be). I can't figure out how to do this. I've tried many different approaches. Currently I use a class that extends TableCellRenderer, but no combination of alignment settings in this class seems to do the trick.
    I've noticed that in the case of JTextFields, this manner of display seems to be the default, no matter what alignment setting I choose. I can't seem to get the desired effect with the display of cells in my JTable though.
    Anyone have any suggestions?
    Thanks in advance.

    Great job camickr,
    That did just what I wanted; you get the points for sure! I will say that It's surprising to me that Swing leaves so much work in calculation to be done for this simple idea.
    Btw, I also want to mention here that there's another forum issue I raised and you responded to recently, and you never quite answered my question there:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=5160875
    That's got 10 pts riding on it too, if you care to revisit the issue...
    Thanks very much for the good work on the CellRenderer.

  • Styled Text in Table Cell

    Hi,
    I've got this problem: I'd like to insert a styled text in some cells of a JTable.
    The text should be composed of two kinds of Font, to emphasize some characters in it.
    Suppose I've done a class Test, that extends JPanel. In this class I've done a method appendChar(String c, boolean bol). With this method I can add a JLabel with only a single char (String of length 1) at a time. If bol is true, it emphasizes the char; if false, it uses the "default" font. For example:
    "this is an example"
    This class works fine, but I don't have any idea on how I could be able to insert a Test instance in a JTable cell.
    I think I should create a class that implements TableCellEditor, or extends DefaultCellEditor.. but I don't know how this should be done.
    If there is some other way to have some styled text in a table cell, tell me!

    Hi,
    AFAIK, the default renderer for a table cell is a JLabel in which you can display styled text using html. You would need to provide a custom editor only if the default textfield doesn't fulfil your needs. For rendering, you need to override the renderer.
    Cheers,
    vidyut

  • JTable - Dynamic wrapping of text in a cell.

    Hello,
    Can anyone tell me how to dynamically wrap the text in a particular cell of a JTable if it is to long to be displayed on one line? I don't care if it affects the row height. Basically, I have a table with 3 columns, the thrird of which is a "notes" column and allows up to 500 characters to be displayed. When the text is too long the table truncates it with an elipsis (...) and the user can't see the rest. I would like the text to wrap within the cell (even if the height has to change) so that the user can read the entire note more easily.
    Thank you,
    G Poole

    You should probably repost this in the swing forum

  • JTable - Wrapping text in a cell.

    Hello,
    Can anyone tell me how to dynamically wrap the text in a particular cell of a JTable if it is to long to be displayed on one line? I don't care if it affects the row height, in fact I would like the row height to be automatically adjusted to fit the text.
    Basically, I have a table with 3 columns, the third of which is a "notes" column and allows up to 500 characters to be displayed. When the text is too long the table truncates it with an elipsis (...) and the user can't see the rest. I would like the text to wrap within the cell (changing the row height) so that the user can read the entire note more easily. In addition, and I realize this may add a significant wrinkle, my client does not want to see a scrollbar just the whole note.
    Has anybody been able to do this?
    Thank you,
    G Poole

    i didn't like the code in that article, it seemed too messy. here's what i did for my application:
        static class CardObjectRenderer extends DefaultTableCellRenderer {
            private int minHeight = -1;
            private final JLabel label = new JLabel();
            private final JTextArea textArea = new JTextArea();
            public CardObjectRenderer() {
                textArea.setLineWrap(true);
                textArea.setWrapStyleWord(true);
            public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
                Component c = null;
                switch (column) {
                    case 0 : // the image
                        ImageIcon icon = (ImageIcon) value;
                        minHeight = Math.max(minHeight, icon.getIconHeight());
                        label.setIcon(icon);
                        c = label;
                        break;
                    case 2 : // the help
                    case 1 : // the answer
                        String text = (String) value;
                        textArea.setText(text);
                        minHeight =
                            Math.max(minHeight, textArea.getPreferredSize().height);
                        c = textArea;
                        break;
                    default :
                        throw new RuntimeException("invalid column! " + column);
                // the final column in my table
                if (column == 2) {
                    if (table.getRowHeight(row) != minHeight) {
                        table.setRowHeight(row, minHeight);
                    minHeight = -1;
                return c;
        }i use a single instance of this cell renderer for every cell in my table, because i know exactly what is going in there. that is, i have a table model which reflects the column order i have here, etc.
    the thing that kills the cpu is the call to table.setRowHeight(int row, int height)... you need to check that you actually need to set it before you before you do. if you simply set it each time then your renderer gets called again and again and again. you can check it very simply:
        if (table.getRowHeight(row) != minHeight) {
            table.setRowHeight(row, minHeight);
        }(note that the text height still isn't perfect, but it suffices for my requirements)
    hope that helps some of you.
    cheers,
    chris

  • How to insert textfield in a cell of a jtable ?

    Hi,
    i m not sure how to insert a textfield into a cell of a jtable which already contains some text in the cell .. Can anyone juz show mi a simple program to do this ??? thanks in advance =)

    Hi Michael,
    i get wad u r trying to say ermm actually i did that already. But wad i need to do is such that in a cell, there will b some text displayed (which i have done so) but i also need to add an additional box for user to enter the values n in this case i haf choosen to add the jtextfield box .. But i m not sure how to ... sorry for the misunderstanding ~~~ n thanks for ya reply =)

  • Centering texts with DefaultTableCellRenderer

    Hi,
    I 've created a JTable and now I am trying to center the text in the cells of the table.
    I am using an AbstractTableModel for this table and the data are store in a vector.
    I tried to extends DefaultTableCellRenderer like this but it did not work because (I think) of the vector.
    Here a snippet:
    class centerTextRenderer extends DefaultTableCellRenderer{
    public centerTextRenderer(){
    setHorizontalAlignment(CENTER );
    public void setValue( Object value){
    setText( value.toString() );
    Does anyone have a suggestion?
    --kirk123

    Your class looks OK (you don't even need to override the setValue() method). Did you tell your table to use your renderer?
    table.setDefaultRenderer(Object.class, new CenterTextRenderer());
    Note: the Java convention is to use upper case characters for all words in a class name.

  • Export to excel with formatting was autowrapping text in a cell

    Export to excel with formatting was autowrapping text in a cell without having to check the can grow option.  When the can grow option is checked it does wrap the text however it spans multiple rows, which causes complications when trying to sort. 
    It worked in:
    ProductVersion=10.0.0.533
    ProductName=Crystal Enterprise 10 Embedded
    Doesnt work in:
    Crystal Reports 10.0 Service Pack 6
    After the upgrade the reports did not autowrap, b/c the "can grow" option was not checked.  I believe this was fixed by "ADAPT00305137 Patch ID: 36479914
    Description:
    When users export to Excel 97-2000 with the page-based format, text fields are wrapped, even when the "can grow" feature in the
    Designer is turned off." .   After we turn the option to grow on it does wrap however it spans across multiple rows.  So I guess my question is there a way for it not to span multiple rows when wrapping text?
    Edited by: dforde on Jan 27, 2010 11:12 PM

    I could be wrong, but I believe the export to excel option exports the database values, and the export to HTML exports the values seen in the sheets. If the database values are stored as seconds, the Excel will see them as seconds, and the data will have to be formatted properly in Excel.
    I haven't toyed around with Excel exports that much, but it might be possible to set up a template or macro in excel that would have the proper formatting, and use it when opening the Disco export.

  • Multi-coloured text in table cell

    I have a table where individual cells can have multi-coloured text. To do this I use html when I set the text in a cell renderer. It works fine. However, when the column width is too narrow for the text then the text is wrapped. If the text is not html then the text is not wrapped.
    How can I keep the different colours but make sure the text is not wrapped?
    Thanks

    I never want the text to wrap even if the column width is too small for the text.
    If the text of the renderer was set to abcdefghijklmnand the column is only large enough to show the first 10 chars then the user (obviously) would only see the first 10 chars.
    If I now set the text to <html>ab<font color="#ff0000">cde</font>fghijklmn</html> then, assuming the column is wide enough, the user will see all the text but cde is shown in red.
    However, if the column width is now changed so there is only room to show the first 10 chars then the user will only see abcde not as I would hope abcdefghij

  • Different color text in one cell

    How do I set a color for a group of words within a cell leaving the rest of the words black?
    I can make all the text within a cell the same color but when I select the words I want to be a different color the color selector in the toolbar goes away and only fx, Cancel and Accept buttons are available.

    If it is simple text, not the result of a formula, select the words you want to change and select another color from the toolbar or the color panel. That is, unless I didn't understand your request. I don't know where you are seeing Accept, Cancel and Fx.

  • 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

  • How to get the coordinate of a cell in the jtable?

    How to get the coordinate of a cell in the jtable?
    How to get the point of a cell in the jtable?
    Thanks for help!

    getCellRect(...);

  • How to enable JScrollPane in a cell of the JTable

    Hi,
    I am able to place the components into the cell of the JTable. But I am unable to interact with the components like JTable or JComboBox after inseting them into a cell of the JTable.
    This was the one of the Scenario:
    Step 1: I created One JTable named as "insertTable"and adding to JScrollPane
    Step 2: I'm able to inserted the newly created JTable ("insertTable") in to a cell of another JTable(like table inserting a table) using TableCellRenderer.
    here was the problem. I am able to insert the newly created table into the cell. the "insertTable" size is greater the Cell size. So, the "insertTable" is appering with Horizantal and Vertical Scrollbars because the "insertTable" is added to JScrollBar. but I am unable to move the scrollbars.
    please any one help me for this.

    you still didn't try to learn the difference between cellEditor vs cellRenderer - as you were advised to do more than once in recent posts.
    If you do, the answer will be obvious (to you :-). As long as you don't there's nothing to help
    Cheers
    Jeanette

  • If Number = than then display text from another cell

    Hi
    I'd appreciate it if anyone can help me with this please.
    I am putting together a gradebook type spreadsheet. I would like to display the text from another cell if the number entered in another cell is greater than or less than a certain number.
    So - if the number in cell A is equal to or greater than 70 then the text displayed in cell B equals the text contained in cell C
    Hope this makes sense.
    Many thanks in advance.
    regards,

    Hello Lee,
    The Numbers User Guide PDF available from the Numbers Help menu as a download is good reading for beginners. As a reference document, the iWork Formulas and Functions User Guide is also valuable.
    The function you need is called "IF", and the syntax is: IF "logic-expression" is true, then do this, else do this. As a calculation in a cell, that would have the form: =IF("Cell A" is equal to or greater than 70, then display the content of cell C, else display "something else") You need to provide the "something else", which can be a null string, "", if you wish.
    As you will find when you read the guide, the cells all have row and column address components where the column is identified by a letter of the alphabet and the row by a number. So If your data is in A1, your text string in B1 and your expression is in C1, you would write in C1:
    =IF(A1>=70, B1, "")
    Does this help?
    Jerry

Maybe you are looking for

  • Help Me!!!!! Iphone changing and not recognizing Apple ID

    Few days ago I got a new laptop after not having one for a year...all of my old programs, info all that got transfered onto new computer. So I plug in my Iphone in order to synch up all my music from my Itunes that had been on my broken laptop. Not o

  • Preview misaligned on 24" monitor

    I have Bridge v 2.1.1.9 on Vista, all up to date. 24 inch monitor. I usually use the view which has a large preview window occupying most of the screen with a horizontal row of thumbnails at the bottom and various windows such as folders, keywords, f

  • IOCTL's from a static library linked to KMDF driver

    Hi, Im trying to build a static library that can be used across multiple KMDF drivers. The library needs to send IOCTL's to another driver to access required functionality.  The library does not have access to the Wdf device object/objects of the KMD

  • ISE 1.0.4 - platform migration

    Does anyone know if you can backup and restore to unlike hardware. I am in a situation where we are working fine with 3355 as admin nodes and policy nodes but need to get more horsepower as we reach the endpoint limit. I will be at right around 13,00

  • Everything is in german

    My itunes opened up in german today. how do i get it back to engllish?