Custom table header renderer

I am trying to make a custom table header. I have seen some examples on the web such as
<mx:DataGridColumn width="150" dataField="SalePrice"
                headerRenderer="myComponents.RendererDGHeader"/>
where that class is a Box
I also tried to inline it as such:
<mx:DataGridColumn draggable="false" editable="true" headerText="Source RNC" headerStyleName="tableHeader" dataField="sourceRNC">
     <mx:headerRenderer>
          <fx:Component>
               <mx:DataGridItemRenderer>
                    <s:Group/>    
               </mx:DataGridItemRenderer>
             </fx:Component>
     </mx:headerRenderer>
</mx:DataGridColumn>
In both these cases I get the following:
VGroup declaration must be contained within the <Declerations>
tag since it does not implement mx.core.IUIComponent
Now clearly it does. Is this a bug or am I doing something
wrong. My goal is for the table's header to have a combo
box and a text field below the header's name to put filter
options on the column(like hide values <5) etc
Thanks, I know I have been posting a lot of questions lately

By using s:MXDataGridItemRenderer, your renderer is now using Spark, and in Spark, clipping is not available by default.  You have to set clipAndEnableScrollbars=true on the layout.  Headers are asked for height if variableRowHeight=true, but not width. The width is determined by the DG columns.
Alex Harui
Flex SDK Developer
Adobe Systems Inc.
Blog: http://blogs.adobe.com/aharui

Similar Messages

  • Custom table header

    Hi all!
    Actually it seems pretty easy but I cannot find an answer in my mind. The problem is simply controlling column widths of multiple JTables with only one table header (consider we add lots of tables with same number of columns in boxlayout (and glued to borders of same container), well handling dragging thing is relatively easy since we may override columnMoved(TableColumnModelEvent e) in JTableHeader but there is nothing like something for resizing column widths or just I cannot see). Is there a way to reach column widths(I dunno maybe some kind of array or get function)?
    do I have to create an custom Event for resizing widths?
    I'm open to any abstract ideas, well do not try to explain things as a source code(If you want you definitely can do but it's kind of burden and it's not the best way to ask for "help" also this way is better for my programming skills, just tell me function or things to extend or implement)
    Anyway, it would be pretty good to learn how to detect a change in a table's column widths(which event, etc...)
    thanks for your helps:))

    to be more precise if there is someone just like me, lookin for this:
    package ComponentDisplayer;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableColumnTest extends JFrame
         public TableColumnTest()
              JTable north = new JTable(5, 10);
              //north.setPreferredScrollableViewportSize(north.getPreferredSize());
              JTable south = new JTable(5, 10);
              //south.setPreferredScrollableViewportSize(south.getPreferredSize());
              south.setColumnModel( north.getColumnModel() );
              south.setTableHeader(north.getTableHeader());
              JPanel jp=new JPanel();
              jp.setLayout(new BoxLayout(jp, BoxLayout.PAGE_AXIS));
              jp.add(north.getTableHeader());
              jp.add(north);
              jp.add(south);
              jp.remove(north);
              /*JScrollPane spsouth=new JScrollPane(south);
              spsouth.setSize(south.getColumnModel().getTotalColumnWidth(),south.getRowCount()*south.getRowHeight());
              spsouth.setMaximumSize(new Dimension(south.getColumnModel().getTotalColumnWidth(),south.getRowCount()*south.getRowHeight()));
              JScrollPane spnorth=new JScrollPane(north);
              spnorth.setSize(north.getColumnModel().getTotalColumnWidth(),north.getRowCount()*north.getRowHeight());
              spnorth.setMaximumSize(new Dimension(north.getColumnModel().getTotalColumnWidth(),north.getRowCount()*north.getRowHeight()));
              jp.add( spnorth);
              jp.add( spsouth);
              north.setValueAt(new String("north"), 0, 0);
              south.setValueAt(new String("south"), 0, 0);
              getContentPane().add(jp);
         public static void main(String[] args)
              TableColumnTest frame = new TableColumnTest();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • Customized table cell renderer doesn't work after table data model changed

    Hi:
    I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
    Thanks

    I am having the same problem. Has anybody solved this issue?
    Thanks

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    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 % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

  • Table header renderer and editor

    Hi,
    I am making a customised table, in which the column headers are required to be JButton components.I want to catch action events on the headers.Can anyone suggest how should i go about it?
    thanx,
    regards.

    This isn't as easy as it should be because of how the header is drawn. It doesn't create individual header components, it uses one component like a rubber stamp to draw the headers. So it isn't as simple as just sticking in some buttons in the proper place.
    Here is a pretty good example that might get you started:
    http://www2.gol.com/users/tame/swing/examples/JTableExamples5.html

  • Custom multiline table header

    I was trying to set JPanel with two inner components (JTextField and JLabel) as header renderer. When I put this component to JFrame text field is editable, but when it appears in my custom table header it is disabled or not focusable, that part I couldn't figure out. I thought that I can find where all header components are and make them enabled/focusable, but I couldn't figure that out either.
    Please help!!
    :-|

    A renderer is simply used to paint the contents of the header;
    it is not a child of the JTableHeader or anything like that. If
    you want the text field in the renderer to be editable, you are
    going to have to handle that yourself by taking care of
    all the necessary events, etc.

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

  • Customized table renderer

    I have written my own table cell renderer based somewhat on jdk?s DefaultTableCellRenderer - taking into account all performance issues mentioned in the Note section of JDK doc for that class.
    My renderer extends JPanel , contains a few JTextField components and the function getTableCellRendererComponent returns simply ?this? reference.
    In my JTable derived class in function addItem() I am iterating through all my data in the model. For every data item I am calling renderer?s getTableCellRendererComponent to initialize renderer component and then I ask that component for its preferred size (calling getPreferredSize) saving the biggest width found so far.
    Somehow the renderer component always returns to me the width that is correct for the very first data item from model.
    Below is fragment of my code, any idea what is wrong with my code?
    JD
    * This method picks good column sizes.
    * If all column heads are wider than the column's cells'
    * contents, then you can just use column.sizeWidthToFit().
    private void initColumnSizes()
    MyTableModel model = (MyTableModel)actionTable.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    int maxCellWidth = 0;
    for(int j = 0; j < model.getRowCount(); j++)
    for (int i = 0; i < model.getColumnCount(); i++)
    column = actionTable.getColumnModel().getColumn(i);
    comp = actionTable.getTableHeader().getDefaultRenderer().
    getTableCellRendererComponent(null, column.getHeaderValue(),
    false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;
    comp = actionTable.getDefaultRenderer(model.getColumnClass(i)).
    getTableCellRendererComponent(actionTable, model.getValueAt(j, i),
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;// !!!!
    maxCellWidth = Math.max(maxCellWidth, Math.max(headerWidth, cellWidth));
    column.setPreferredWidth(maxCellWidth);

    The renderer components are just used for drawing purposes.
    Therefor, you can not iterate through them to find the widest of them for your data, because in most cases, there will only be a single one for your whole table.
    You need to iterate through the data of your model and use that as a basis for calculating the width of each column, not the cellrenderer.

  • Missing Table Header

    Hi,
    Can someone tell my why I can't see my table headers. I have placed the table inside the JScrollPane but it still doesn't work.
    package tablepractice;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class TableFrame
        private JScrollPane scrollPane;
        private TableData tableData;
        private JTable table;
        private JPanel tablePanel;
        public TableFrame()
            tablePanel = new JPanel();
            tableData = new TableData();
            table = new JTable(tableData);
            TableColumnModel tcm = table.getColumnModel();
            TableColumn tc = tcm.getColumn(TableData.DOB);
            MultiLineHeaderRenderer mlhr = new MultiLineHeaderRenderer();
            tc.setHeaderRenderer(mlhr);
            scrollPane = new JScrollPane(table);
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            tablePanel.add(scrollPane);
            createAndShowGUI();
        public void addComponentsToPane(Container pane)
            pane.setLayout(new GridBagLayout());
            GridBagConstraints constraints = new GridBagConstraints();
            constraints.fill = GridBagConstraints.HORIZONTAL;
            constraints.gridx              = 0;
            constraints.gridy              = 0;
            constraints.gridheight         = 4;
            constraints.gridwidth          = 5;
            pane.add(tablePanel, constraints);
        private void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame frame = new JFrame("");
            frame.setDefaultLookAndFeelDecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set up the content pane.
            addComponentsToPane(frame.getContentPane());
            //Display the window.
            frame.pack();
            frame.setResizable(true);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    new TableFrame();
    ["code"]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Well the basics of displaying a table is straight forward:
    JTable table = new JTable(5, 10);
    JScrollPane scrollPane = new JScrollPane( table );
    getContentPane().add( scrollPane );
    So start with simply displaying a table and then add in you customizations to see where the problem is. For example:
    1) Why do you create a 'tablePanel' and add the scroll pane to the tablePanel which you add to the contentPane. This is unnecessary.
    2) Try your code without the GridBagLayout
    3) You are using a custom header renderer. Try you code without the renderer.
    4) You are overriding the viewport size.
    Start simple add complexity and determine where the problem is rather than asking a generic 'whats wrong" question.

  • Proble with Custom JTable Header

    Hi
    I want create Custom JTable with JTextField on column header, so that user can enter some text. As of now i am able to create the text box on header using custom TableCellRenderer but i am not able to make it editable.....
    Please help me. if any one need more info, pls let me know.

    KetuRai wrote:
    Then what should i do to achieve this functionality. Do any one have sample code?
    Or other alternative to achieve this.I don't know If this is the best way but my approach is using a InputDialog and a custom renderer.
    just click on the table header and input a text. Good Luck!
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    public class TableHeaderDemo {
        public void createAndShowUI() {
            JFrame frame = new JFrame("Click Table Header to change text");
            String[] columnName = {"CheckBox Column", "Data Column"};
            Object[][] data = {{"Data 1", "Data 2"},
            {"Data 3", "Data 4"}, {"Data 5", "Data 6"}};
            final JTable myTable = new JTable(data, columnName);
            myTable.getTableHeader().setDefaultRenderer(new MyRenderer());
            myTable.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    int col = myTable.getTableHeader().columnAtPoint(e.getPoint());
                    String str = javax.swing.JOptionPane.showInputDialog("Enter a text: ");
                    myTable.getColumnModel().getColumn(col).setHeaderRenderer(new MyRenderer(str));
                    myTable.getTableHeader().revalidate();
                    myTable.getTableHeader().repaint();
            JScrollPane scrollPane = new JScrollPane(myTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.getContentPane().add(scrollPane);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        class MyRenderer implements TableCellRenderer {
            JTextField text = new JTextField();
            MyRenderer(String str) {
                text.setText(str);
            MyRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                text.setBorder(BorderFactory.createRaisedBevelBorder());
                text.setBackground(Color.BLUE);
                text.setForeground(Color.WHITE);
                text.setHorizontalAlignment(JTextField.CENTER);
                return text;
        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TableHeaderDemo().createAndShowUI();
    }

  • Clicking on table header throws exception

    I'm using Windows Look and Feel. I made a table and applied the custom renderer to the table header. When I click the table header it throws a NullPointerException relating to the plaf.
    javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler.mouseClicked(Unknown Source)+
    Anybody any Idea. Adding the mouse Listener solves this problem but I dont want to use the listeners just for that reason.

    Take a look here:
    http://www.codeguru.com/java/articles/218.shtml

  • Table Cell Renderer Problem

    I've created a JTable and filled it with data. I created my own header renderer so that I could have more control over the font of the header. I did the same with the cells of the table. Before I created the cell renderer, the cell and row selection (the highlighting of the selections) worked fine. Once I created and implemented the cell renderer, I can set the font the way I want, but the cell no longer highlights the selected rows. It's selecting the rows (my System.out.println in getTableCellRendererComponent() comes back with data). I'm not sure what I'm doing wrong. Here's some of the code....
    runTable = new JTable(tableModel);
    runTable.setBackground(Color.white);
    runTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    CellRenderer cellRenderer = new CellRenderer();
    // Set column 1's header
    String[] header1 = {"Time"," Of ","Day"};
    TableColumn col1 = runTable.getColumnModel().getColumn(0);
    col1.setHeaderValue(header1);
    col1.setCellRenderer(cellRenderer);
    String[][] parms = zoomplot.zmenubar.getParmSel();
    TableColumn col;
    for (int i = 0; i < parms.length; i++) {
    String[] header = new String[3];
    header[0] = parms[0];
    header[1] = " (" + parms[i][1] + ") ";
    header[2] = "Rate " + parms[i][2];
    col= runTable.getColumnModel().getColumn(i + 1);
    col.setHeaderValue(header);
    // col.setMaxWidth(100);
    col.setCellRenderer(cellRenderer);
    class CellRenderer extends JLabel
    implements TableCellRenderer {
    Color background = null;
    public CellRenderer() {
    // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    // setOpaque(false);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
         int row, int col) {
    removeAll();
    invalidate();
    add(Box.createVerticalGlue());
    setText((String)value);
    setFont(Utils.courierBold11);
    setHorizontalAlignment(SwingConstants.CENTER);
    setAlignmentX((float)0.5);
    if (isSelected) {
    this.setBackground(Color.black);
    // System.out.println("Row " + row + ", Col " + col + " is selected");
    return this;
    public void setBackground(Color back) {
    background = back;
    super.setBackground(back);
    I even tried to "manually" set the highlighting in getTableCellRendererComponent() ...
    if (isSelected) {
    this.setBackground(Color.black);
    but that didn't work either. Any Ideas..... Thanks.....

    When creating a custom renderer it is generally easier to extend the DefaultTableCellRenderer as it already has the custom code to do row highlighting, border selection etc. Also it has been optimized to paint faster.
    In your particular case it looks like your don't even need to do that. Just create a DefaultTableCellRenderer and change a few of its properties. Something like:
    // Override default renderer for a specific column
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( JLabel.CENTER );
    centerRenderer.setFont(...);
    table.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );

  • How to create a custom table in the below format

    Dear Friends
              can any one please let me know hot to create a custom table as below
    outpatient
    |employeeno | class | startdate | enddate | spouse |1stchild | 2nchild|  Rate | amount|
    My FO wants to enter in the SM30 as above ......i.e he wants to have spouse ,1st child and 2nd child under one group........so he asking me to make as one group
    and give a heading as outpatient.........similary i have to give for in patient.
    Please could any one tell is it possible.
    regards
    syamala...

    Under the SAP forums section, there is ABAP development and in That there is ABAP General.
    SAP forums > ABAP development > ABAP General.
    Post in that forum.
    Regards
    AK
    Please reward if helpful

Maybe you are looking for

  • How to use iTunes gift card on family Share plan

    My teen age son is on our Family Share Plan and he has an iTunes gift card he wants to use to download songs.  I can't figure out a way to set this up unless I remove him from the plan and then add him back in after he has made the purchase.  Any bet

  • How do I create / print a unique form ID?

    I have created a simple work order. I have the need of assigning the work order an ID of some kind. I'm not really concerned about the ID topology. The ID should not be incremented for page copies. So let's say I had a hypothetical ID of 9000 and I p

  • Client Change options in SCC4 (SAP ECC 6.0)

    Hi, Our SAP Development system SCC4 settings are as mentioned below: 1.Changes and transports for client-specific objects : Automatic recording of changes 2.Cross-client object changes : Changes to repository and cross-client customizing allowed 3.Pr

  • WLPS/WLCS 3.5 and Campaign Mananger 1.1 Ships!

    All, We recently put WLPS and WLCS 3.5 on the web. These new releases add new features and run on WLS 6.0 allowing you to use new WLS features, such as two-phase commit across different databases. http://www.bea.com/products/weblogic/commerce/whatsne

  • Instal CS4 in windows 7

    I have Indesign CS4, Windows XP version, and want to instal on my new Windows 7 laptop. Two questions - am I allowed to have two installations (single user licence), and will it run under Windows 7?