JTableHeader's CellRenderer

I am implementing a JTable with both column header and row header. The row header is implemented as a JList residing in JScrollPane's rowHeaderView. I used the column header's default renderer to create components for the JList's listCellRenderer, so the row header has the same appearance as the column header.
The table looks perfect in default L&F. But in Liquid L&F., it looks ugly. The row header has the appearance of flat plain JLabel, but the column header looks like JButton with mouse-over effect. It seems to me that Liquid L&F does not use its default TableCellRenderer to create column header. My question is: what TableCellRenderer is used by Liquid L&F to create column header, and how can I get it?
Jimmy

Hi Daniel
When I solved this problem I wrote own renderer for table header.
public class MyRenderer extends DefaultTableCellRenderer
final int CELL_PADDING = 1;
ImageIcon icon1;
ImageIcon icon2;
ImageIcon activeIcon;
int sortingCol;
boolean ascSorting;
public MyRenderer()
     super();
public void setSortingCol(int col, boolean asc)
     sortingCol = col;
     ascSorting = asc;
public void paint(Graphics g)
     if (activeIcon != null)
     {  // draw image at the right side of the cell
          int imageOffsetX, imageOffsetY;
          g.setColor(getBackground());
          g.fillRect(0, 0, getWidth(), getHeight());
          imageOffsetY = (getHeight() - activeIcon.getHeight(this)) / 2;
          imageOffsetX = getWidth() - activeIcon.getWidth(this) - CELL_PADDING;
          g.drawImage(activeIcon, imageOffsetX, imageOffsetY, this);
          setSize(imageOffsetX, getHeight());
     super.paint(g);
public Component getTableCellRendererComponent(JTable table, Object value,
  boolean isSelected, boolean hasFocus, int row, int column)
     if (ascSorting == column)
          activeIcon = (ascSorting ? icon1 : icon2);
     else activeIcon = null;
     return super.getTableCellRendererComponent( table,  value,   isSelected,  hasFocus,  row,  column);
}Good luck.

Similar Messages

  • JTableHeader Animation

    I want to make the JTableHeader of my table animate the way a regular button does when click - flat,lowerd when pressed and high poped-up when released.
    I tried making a TableCellRenderer for the header and it works, the Header doesnt animate like a button. Nothing happens when i click it. Still remains flat.
    Here is the code:
    package tabledemo;
    import javax.swing.*;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.net.URL;
    public class ButtonHeaderRenderer extends JButton implements TableCellRenderer {
         static URL picUrl = ClassLoader.getSystemResource("smile.gif");
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                      boolean isSelected, boolean hasFocus,
                                                      int row, int column){
            LookAndFeel.installColorsAndFont(this,"TableHeader.background",
                                             "TableHeader.foreground",
                                             "TableHeader.font");
            LookAndFeel.installBorder(this,"TableHeader.cellBorder");
            setIcon(new ImageIcon(picUrl));
            setText((String)value);
            return this;
    }The icon and text show in the table header, but no animation.
    I was thinking maybe i can do something if i extend the JTableHeader class. I did that and i can change the dimensions of the columns with it but i dont know how to make the button animate here either.
    Here is the extended JTableHeader class:
    package tabledemo;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumnModel;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.*;
    public class JTableHeaderMouseEvents extends JTableHeader {
        String[] columnNames = {"FirstName","Lastname","Progress"};
        public JTableHeaderMouseEvents(TableColumnModel tcm){
            super(tcm);
            this.setPreferredSize( new Dimension( 70, 18  ) );
            addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent event){
                    int i = columnAtPoint(event.getPoint());
                    int column = getColumnModel().getColumn(i).getModelIndex();
                   // JOptionPane.showMessageDialog(null, "You pressed "+columnNames[column] + " column");
    }Maybe in the mousePressed/Released method of MouseAdapter i can use some method to programatically change the button effects?
    Any tips are appreciated.

    I saw the same problem when I try to put a JComboBox as a column's header. Just set the renderer is not enough, the button won't animate. I can think of two solutions.
    1. Do the animation manually.
         JTableHeader th = table.getTableHeader();
         th.addMouseListener( yourMouseListener);
    in yourMouseListener, you define have the component
    repaint itself, with shadow or without shadow.
    2. Make the header editable, just like the editable cells.
    Try this:
    import javax.swing.*;
    import javax.swing.table.*;
    * @version 1.0 08/21/99
    public class EditableHeaderTableColumn extends TableColumn {
    protected TableCellEditor headerEditor;
    protected boolean isHeaderEditable;
    public EditableHeaderTableColumn() {
    setHeaderEditor(createDefaultHeaderEditor());
    isHeaderEditable = true;
    public void setHeaderEditor(TableCellEditor headerEditor) {
    this.headerEditor = headerEditor;
    public TableCellEditor getHeaderEditor() {
    return headerEditor;
    public void setHeaderEditable(boolean isEditable) {
    isHeaderEditable = isEditable;
    public boolean isHeaderEditable() {
    return isHeaderEditable;
    public void copyValues(TableColumn base) {
    modelIndex = base.getModelIndex();
    identifier = base.getIdentifier();
    width = base.getWidth();
    minWidth = base.getMinWidth();
    setPreferredWidth(base.getPreferredWidth());
    maxWidth = base.getMaxWidth();
    headerRenderer = base.getHeaderRenderer();
    headerValue = base.getHeaderValue();
    cellRenderer = base.getCellRenderer();
    cellEditor = base.getCellEditor();
    isResizable = base.getResizable();
    protected TableCellEditor createDefaultHeaderEditor() {
    return new DefaultCellEditor(new JTextField());
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * @version 1.0 08/21/99
    public class EditableHeader extends JTableHeader
    implements CellEditorListener {
    public final int HEADER_ROW = -10;
    transient protected int editingColumn;
    transient protected TableCellEditor cellEditor;
    transient protected Component editorComp;
    public EditableHeader(TableColumnModel columnModel) {
    super(columnModel);
    setReorderingAllowed(false);
    cellEditor = null;
    // The columnModel is changed. It also exists in JTable.
    recreateTableColumn(columnModel);
    public void updateUI(){
    setUI(new EditableHeaderUI());
    resizeAndRepaint();
    invalidate();
    protected void recreateTableColumn(TableColumnModel columnModel) {
    int n = columnModel.getColumnCount();
    EditableHeaderTableColumn[] newCols = new EditableHeaderTableColumn[n];
    TableColumn[] oldCols = new TableColumn[n];
    for (int i=0;i<n;i++) {
    oldCols[i] = columnModel.getColumn(i);
    newCols[i] = new EditableHeaderTableColumn();
    newCols.copyValues(oldCols[i]);
    for (int i=0;i<n;i++) {
    columnModel.removeColumn(oldCols[i]);
    for (int i=0;i<n;i++) {
    columnModel.addColumn(newCols[i]);
    public boolean editCellAt(int index){
    return editCellAt(index);
    public boolean editCellAt(int index, EventObject e){
    if (cellEditor != null && !cellEditor.stopCellEditing()) {
    return false;
    if (!isCellEditable(index)) {
    return false;
    TableCellEditor editor = getCellEditor(index);
    if (editor != null && editor.isCellEditable(e)) {
    editorComp = prepareEditor(editor, index);
    editorComp.setBounds(getHeaderRect(index));
    add(editorComp);
    editorComp.validate();
    setCellEditor(editor);
    setEditingColumn(index);
    editor.addCellEditorListener(this);
    return true;
    return false;
    public boolean isCellEditable(int index) {
    if (getReorderingAllowed()) {
    return false;
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.isHeaderEditable();
    public TableCellEditor getCellEditor(int index) {
    int columnIndex = columnModel.getColumn(index).getModelIndex();
    EditableHeaderTableColumn col = (EditableHeaderTableColumn)columnModel.getColumn(columnIndex);
    return col.getHeaderEditor();
    public void setCellEditor(TableCellEditor newEditor) {
    TableCellEditor oldEditor = cellEditor;
    cellEditor = newEditor;
    // firePropertyChange
    if (oldEditor != null && oldEditor instanceof TableCellEditor) {
    ((TableCellEditor)oldEditor).removeCellEditorListener((CellEditorListener)this);
    if (newEditor != null && newEditor instanceof TableCellEditor) {
    ((TableCellEditor)newEditor).addCellEditorListener((CellEditorListener)this);
    public Component prepareEditor(TableCellEditor editor, int index) {
    Object value = columnModel.getColumn(index).getHeaderValue();
    boolean isSelected = true;
    int row = HEADER_ROW;
    JTable table = getTable();
    Component comp = editor.getTableCellEditorComponent(table,
    value, isSelected, row, index);
    // if (comp instanceof JComponent) {
    // ((JComponent)comp).setNextFocusableComponent(this);
    return comp;
    public TableCellEditor getCellEditor() {
    return cellEditor;
    public Component getEditorComponent() {
    return editorComp;
    public void setEditingColumn(int aColumn) {
    editingColumn = aColumn;
    public int getEditingColumn() {
    return editingColumn;
    public void removeEditor() {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
    editor.removeCellEditorListener(this);
    requestFocus();
    remove(editorComp);
    int index = getEditingColumn();
    Rectangle cellRect = getHeaderRect(index);
    setCellEditor(null);
    setEditingColumn(-1);
    editorComp = null;
    repaint(cellRect);
    public boolean isEditing() {
    return (cellEditor == null)? false : true;
    // CellEditorListener
    public void editingStopped(ChangeEvent e) {
    TableCellEditor editor = getCellEditor();
    if (editor != null) {
    Object value = editor.getCellEditorValue();
    int index = getEditingColumn();
    columnModel.getColumn(index).setHeaderValue(value);
    removeEditor();
    public void editingCanceled(ChangeEvent e) {
    removeEditor();
    // public void setReorderingAllowed(boolean b) {
    // reorderingAllowed = false;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.*;
    * @version 1.0 08/21/99
    public class EditableHeaderUI extends BasicTableHeaderUI {
    protected MouseInputListener createMouseInputListener() {
    return new MouseInputHandler((EditableHeader)header);
    public class MouseInputHandler extends BasicTableHeaderUI.MouseInputHandler {
    private Component dispatchComponent;
    protected EditableHeader header;
    public MouseInputHandler(EditableHeader header) {
    this.header = header;
    private void setDispatchComponent(MouseEvent e) {
    Component editorComponent = header.getEditorComponent();
    Point p = e.getPoint();
    Point p2 = SwingUtilities.convertPoint(header, p, editorComponent);
    dispatchComponent = SwingUtilities.getDeepestComponentAt(editorComponent,
    p2.x, p2.y);
    private boolean repostEvent(MouseEvent e) {
    if (dispatchComponent == null) {
    return false;
    MouseEvent e2 = SwingUtilities.convertMouseEvent(header, e, dispatchComponent);
    dispatchComponent.dispatchEvent(e2);
    return true;
    public void mousePressed(MouseEvent e) {
    if (!SwingUtilities.isLeftMouseButton(e)) {
    return;
    super.mousePressed(e);
    if (header.getResizingColumn() == null) {
    Point p = e.getPoint();
    TableColumnModel columnModel = header.getColumnModel();
    int index = columnModel.getColumnIndexAtX(p.x);
    if (index != -1) {
    if (header.editCellAt(index, e)) {
    setDispatchComponent(e);
    repostEvent(e);
    public void mouseReleased(MouseEvent e) {
    super.mouseReleased(e);
    if (!SwingUtilities.isLeftMouseButton(e)) {
    return;
    repostEvent(e);
    dispatchComponent = null;
    Here is my source code for using it:
    EditableHeaderTableColumn column0 = (EditableHeaderTableColumn)columnModel.getColumn(0);
    ComboRenderer renderer = new ComboRenderer(items);
    column0.setHeaderRenderer(renderer);
    // setHeaderEditor is provided by EditableHeaderTableColumn
    column0.setHeaderEditor(new DefaultCellEditor(combo));
    I can create DefaultCellEditor using a combobox. But you need to create the ButtonEditor, because DefaultCellEditor constructor won't take JButton.
    Good luck!

  • Animated gif in a JButton which is a CellRenderer...

    I'm currently dealing with quite a huge thing...
    My cellRenderer is here to give a button aspect, this button has 3 kind of icons in fact :
    a cross when the line is ready to be treated
    a loading animation while in treatment... and here is the problem
    a tick whe the line has been treated
    i see the loader (but not always...) and not animated at all ...
    I change the states of the button in aother class, which has its own thread....
    .. as for no as see the lines being ticked line by line, cool, but if the loader could move between the 2 step, it would be perfect..
    Here is my class :
    * Create a special cell render for the first column of the images table
    * This cell render let us display a JButton associated with the given file in order
    * to permit its deletion from the tablelist
    * @author Gregory Durelle
    public class DeleteCellRender extends JButton implements TableCellRenderer , Runnable{
         private static final long serialVersionUID = 1L;
         int row;
         JTable table;
         public DeleteCellRender(){
             this.setIcon(Smash.getIcon("cross.png"));
              this.setBorderPainted(false);
              this.setForeground(Color.WHITE);
              this.setOpaque(false);
              this.setFocusable(false);
         public Component getTableCellRendererComponent( JTable table, Object value,boolean selected, boolean focused, int row, int column) {
              this.setBackground(table.getBackground());
              if(((DataModel)table.getModel()).getImageFile(row).isSent()){
                   this.setIcon(Smash.getIcon("tick.png"));//Smash is my main class & getIcon a static method to retrieve icons throug getRessource(url) stuff
                   this.setToolTipText(null);
              else if(((DataModel)table.getModel()).getImageFile(row).isSending()){
                   this.setIcon(Smash.getIcon("loader.gif")); //HERE IS THE PROBLEM, IT SHOULD BE ANIMATED :(
                   this.setToolTipText(null);
                   this.row=row;
                   this.table=table;
                 Thread t = new Thread(this);
                 t.start();
              else{
                   this.setIcon(Smash.getIcon("cross.png"));
                   this.setToolTipText("Delete this image from the list");
              return this;
         public void run() {
              while(true){
                   repaint();//SEEMS TO DO NO DIFFERENCE...
    }I tried to add a no-ending repaint but it does not make any difference... so if the Runnable annoy you, consider it deosn't exist ;)
    Someone has any idea of how to make an animated gif in a JButton which is in fact a CellRenderer ??....
    .. or maybe a better idea to make the loader appearing at the place of the cross, before the appearition of the tick....
    Edited by: GreGeek on 11 juil. 2008 23:04

    whooo :( you mean making a customized button ?
    like : public class MyButton extends AbstractButton{
       public void paintComponents(Graphics g){
          ...//img1 - wait 15ms - img2 - wait15ms - img3 - etc
    }that would be a solution, but i was pretty sure it would be possible to do more simple, and that i only forgot a very small thing to make it work...

  • Unable to set background colour JTableHeader in Java 1.6_18

    We're moving our application from Java 1.4.2 to 1.6_18, so far without major problems but there's some small issues with the GUI. Originally we'd change the background colour of the JTableHeader, but in 1.6_18 that doesn't seem to work. Instead of colouring the complete header it just seems to draw an outline. It kind of gives the impression that there's something on top of the table header which hides the coloured background.
    The code below shows what I'm trying to do, and gives different results when compiled in Java 1.4.2 and Java 1.6_18. It makes no difference whether I'm using the UIManager or setting the background directly on the JTableHeader.
    The application still works fine of course, but it bugs me that I can't work out what the problem is, so any suggestions would be greatly appreciated! I've already had a look at bug [6521138|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6521138], but it makes no difference whether a new JTableHeader is set, so I think it's different. Also, the workaround for bug [4776303|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4776303] has no effect so I think that doesn't apply either.
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                // Doesn't give the expected result in Java 1.6_18, the background remains white-ish with only a coloured border.
                // UIManager.put("TableHeader.background", Color.GREEN);
                // UIManager.put("TableHeader.foreground", Color.BLUE);
            } catch (Exception exception) {
                exception.printStackTrace();
            final JFrame frame = new JFrame();
            frame.getContentPane().add(createPanel());
            frame.getContentPane().setLayout(new FlowLayout());
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        private static JPanel createPanel() {
            final JPanel panel = new JPanel();
            final DefaultTableModel model = new DefaultTableModel(3, 2);
            final JTable table = new JTable(model);
            // Tableheaders.
            final TableColumnModel columnModel = table.getColumnModel();
            columnModel.getColumn(0).setHeaderValue("First");
            columnModel.getColumn(1).setHeaderValue("Second");
            // Doesn't give the expected result in Java 1.6_18, the background remains white-ish with only a coloured border.
            table.getTableHeader().setBackground(Color.GREEN);
            table.getTableHeader().setForeground(Color.BLUE);
            final JScrollPane scrollPane = new JScrollPane(table);
            panel.add(scrollPane);
            scrollPane.setSize(400, 100);
            panel.setSize(500, 500);
            panel.setPreferredSize(panel.getSize());
            return panel;

    Hillster wrote:
    Ah yes, when I change that setting the background of the table header indeed gets the expected background colour. Unfortunately it also makes my desktop look hopelessly outdated :-( And I can't really expect my end-customers to change their settings just to run my little application. Still, I suppose this proves that the problem lies in the L&F?Seconded Jeanette's sentiment, this is definitely a feature, not a problem. You want system LaF, you get System LaF, with all the bells and whistles. If you're sure you don't want the system embellishments, you could consider using my [_default table header cell renderer_|http://tips4java.wordpress.com/2009/02/27/default-table-header-cell-renderer/].
    db

  • TextArea In CellRenderer doesn't initialize

    I'm new to AS3 so I'm not sure if this is something I'm doing
    wrong or a bug in the component...
    I have a List component and I'm using a movieclip as a custom
    cellRenderer - it's class extends MovieClip & implements
    ICellRenderer. In this movieclip I'm trying to add a TextArea
    component to display some scrolling text. When I do this the
    textarea initially displays with no background or border - only the
    text is visible. The text is also the width of the default
    textarea, not the width I've specified, it overflows the textarea
    with no scrollbars, and it uses Times as it's font. In other words
    it's clearly not performing the initial arrangement/layout of the
    component's UI.
    If I click in the textarea and try to edit the text it
    suddenly snaps into the proper layout - background and border
    appear, the size is correct, the font changes and the scrollbars
    appear - so something in the act of editing is triggering the
    arrangement which doesn't get performed initially.
    I've tried this both with the component placed on stage in
    layout and added programmatically in AS with the same results. If I
    add it to the root level of the stage it works properly, but as
    soon as I use it in any way in the cellRenderer movieclip I get
    this odd behavior. Is there something I need to implement (a call
    or event maybe) in the constructor for my cellRenderer in order to
    trigger the initial layout of textareas in it?

    Thanks for posting this. I was having a problem where the text in my TextArea object would dissapear when testing on a mobile device. If I had a TextArea on the home view, it would display fine, but on any other view it would just flash for a second then dissapear. Switching the skinClass to the mobile textAreaSkin solved this problem.

  • Problem with JTableHeader Render

    Hello,
    I am using JTableHeader renderer as below:
    TableHeaderRender headerRender;
    fixedModel.addColumn("");
                   TableColumnModel colModel = Table.getColumnModel();
                   for(int i=0; i<colModel.getColumnCount(); i++ )
                        colModel.getColumn(i).setHeaderRenderer(headerRender);
    And the renderer is as below:
    class FixedTableHeaderRender extends DefaultTableCellRenderer
              JLabel label = null;
              String[] selectList= {"Item1","item 2", Item 3", "Item 4"};
              JComboBox ColStatBox= new JComboBox(selectList);
    public FixedTableHeaderRender()
    super();
    label = new JLabel();
    label.setOpaque(true);
    label.setBorder(new LineBorder(Color.black));
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setVerticalAlignment(SwingConstants.CENTER);
    ColStatBox.setSelectedIndex(0);
    ColStatBox.setEnabled(true);
    ColStatBox.setAutoscrolls(true);
    ColStatBox.addActionListener(new ActionHandler(){
    public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected,boolean hasFocus, int row,int column)
         Component comp= null;
         if(column==0)
              comp=ColStatBox;
         else
              label.setText("100");
              comp=label;
         return comp;
    Now in this for First column header the JComboBox is displayed and for rest of the column the label is displayed.
    But in this, the JComboBox is not working i.e. I am not able the browse through the list. If I want to select any item (Item 4), its not allowing me to select.
    How to make it enable and function normally?
    Do reply.
    Thanks and regards,
    Sheetal

    I've amended your code as shown. Some points:
    1) Not sure what all the scroll bar stuff is for, I've removed it.
    2) The method DefaultTableModel.addColumn is too crude. If you look at the JDK source it calls fireTableStructureChanged(). This has the effect of recreating the column model, which in turn resets all the widths. It will also clear out any renderers/editors you had set up within the TableColumn instances inside the TableColumnModel (if any). Those setup by column class would be OK (I think).
    I didn't look into the remainder of your problem, hopefully you are OK now...
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import javax.swing.table.DefaultTableModel;
    public class MyJTable extends JFrame
    DefaultTableModel model;
    JButton addBtn;
    JTable table;
    JScrollBar scrollBar;
    JScrollPane scrollPane;
         public MyJTable()
              getContentPane().setLayout(new BorderLayout());
              Object[] header= {"1", "2"};
              model= new DefaultTableModel();
              model.setDataVector(null,header);
               table = new JTable(model);
               table.getTableHeader().setReorderingAllowed(false);
               table.getTableHeader().setResizingAllowed(true);
               table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
               scrollBar=new JScrollBar();
              scrollBar.setOrientation(1);
              scrollBar.setBlockIncrement(1);
              scrollBar.setMinimum(0);
              scrollBar.setMaximum(50);
              scrollBar.setUnitIncrement(1);
              scrollBar.setVisibleAmount(1);
              table.add(scrollBar);
              scrollPane=new JScrollPane(table);
              scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
               addBtn=new JButton("Add Column");
               addBtn.addActionListener(new ActionHandler());
               getContentPane().add(scrollPane, BorderLayout.CENTER);
               getContentPane().add(addBtn, BorderLayout.SOUTH);
         class ActionHandler implements ActionListener
              //@Override
              public void actionPerformed(ActionEvent ae)
                   // TODO Auto-generated method stub
                   if(ae.getSource()==addBtn)
                        //model=(DefaultTableModel)table.getModel();
                        //model.addColumn("A");
                        //model.fireTableStructureChanged();
                        TableColumnModel tcm = table.getColumnModel();
                        TableColumn newCol = new TableColumn();
                        newCol.setHeaderValue("A");
                        tcm.addColumn(newCol);
          * @param args
         public static void main(String[] args)
              MyJTable frame = new MyJTable();
                  frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                      System.exit(0);
                  frame.setSize( 300, 400 );
                  frame.setVisible(true);
    }

  • Selecting a column in the JTableHeader

    Hi all,
    I am currently working on an application where the user (by d n' d or cut n' paste) should be able to add data to a table. It works fine to add data to the table and display it by using a renderer, but it seems to be impossible to add data to the header. The header won't get selected when clicking on it (and thus never receives the focus...). I have tried various ways of using mouse listeners, overriding the isFocusTraversable() in JTableHeader, setting table.setColumnSelectionAllowed(true), and header.setRequestFocusEnabled(true), but nothing is working. How on earth can I select a column header?

    You definitely will have to roll your own: as is JTableHeader does not support the notion of selection.
    To do so, you will need to change several things:
    1. make the XXTableHeaderUI aware of selection (it always sends false for both isSelected and hasFocus when it repaints the renderer)
    2. have a custom headerRenderer that respects the flags selected/focus
    3. make some object responsible for sending notification if the value for the columnHeader does change - as is the columnNames are stored in the TableModel, but nothing happens when they are changed; so easiest would be to make a customTableModel responsible for firing some event.
    4. make the header listen to the changes.
    As you see, it's quite involved. Good luck
    Jeanette

  • Layout malfunction with a custom JList cellrenderer

    Hello everybody! I have encountered a strange problem: I've got a JPanel that uses GridBagLayout with an image (map) on the right side, and two JLists on top of one another on the left side. They both have a custom cellrenderer that displays rows of varying heights depending on the amount of members in a family. Everything works just fine, until the lower list is updated as a result of a ListSelectionEvent that occurs in the upper one, which in turn results in a cell containing many a family of more than 1 person being added to the lower JList. This is when the two JLists become as narrow as the vertical scrollbars, and the image is resized to take all the space. This is reversed as soon as the lower list only contains cells of "normal" height. However, the upper JList only contains cells of double the normal height. Go figure? If anybody happens to know what is causing the behaviour, let me know!
    // nmd

    Try to specify ipadx attribute of GridBagConstraint for both lists. It will specify minimal size of list.
    regards,
    Stas

  • Is it possible to set a hand cursor on an image in the JTableHeader?

    I want to change the mouse cursor to a hand when the user rolls over a sort button image that is contained within the table header.
    I have customized (quite heavily) the JTableHeader so that I can activate a filter popup and a sort action by clicking in the JTableHeader for any given column.
    I know that the JTableHeader renderer is basically a snap shot of the components that are defined within the renderer, but there must be some way to capture the mouse rolling over the sort icon, and give the user a hand cursor to let them know they can click in that area.
    My header is defined as JPanel. Within the JPanel, I have one icon to indicate whether the column is required, another one to indicate whether it is a look up value, another icon to let the user sort, and another icon to let the user filter. Also, I have a JLabel to hold text (for the label).

    I've spent a few hours now trying to figure this out and nothing is working.
    One of the things I tried was adding a component listener to the component returned by getTableCellRendererComponent. My hope was that component must be sized before it is painted into the header. If I was able to capture the size of the component, I could store the coordinates of the individual components...However, I wasn't able to capture any of these events.
    Also, I tried to override the paint method in the UI class and retrieve the coordinates of the sub components as they are painted into the header. This resulted in some odd painting behavior.
    As I started thinking more and more about it, I was wondering if it is possible to rework the header so that it does not employ renderers and headers. I understand that the components are "painted" into the header instead of added to the header, because performance would suffer otherwise. However, this is just a header.
    It would be so much better if I could stick some components in each column header and interact with these components in the normal manner. I looked at the JHeaderTable code and the associated UI class and don't know where to start.
    Again, is it possible to subclass JTableHeader and make it so that I can add components to each component header so that I can interact with it, instead of having this non-interactive picture of a component at the top of the header?

  • Hide white background in CellRenderer cells

    Hi
    I am developing an application and making use of a list component. I have set the List to use a custom cellrenderer.
    I need the list to have rounded corners but the problem is that where my custom cell corners are transparent I can see a default white cell underneath instead of the background.
    I found this discussion seemed to be relevant http://supportforums.blackberry.com/t5/Tablet-OS-SDK-for-Adobe-AIR/TileList-CellRenderer-h as-white-background/td-p/781843
    But when I add this function to my cellrenderer class I get  compiler error
    override public function set data(data:Object):void{
        super.data = data;
        // Set the default skin to be invisible. This is a bit
        // easier than creating a new skin, if your goal is
        // to hide the white background.
        this.skin.visible = false;
    1119: Access of possibly undefined property skin through a reference with static type MarksCellRenderer.
    Can anyone tell me how to hide the defualt white cell background?
    Thanks
    Graeme

    If the white background is coming from the default List skin, you can physically edit List_skin MovieClip in the Component Assets in the library to make it transparent.
    Kenneth Kawamoto
    http://www.materiaprima.co.uk/

  • Cellrenderer doesn't refresh upon Scroll

    I'm finding that the only way I can refresh a datagrid
    containing jpegs, rendered with cellrenderer, is by setting a
    scroll event on the datagrid, then resizing the column to the same
    value inside this event's function.
    Is this a known problem?

    No, it's not just you. I manage approx 96 computers with ARD 3.2 running on a Mac Pro with 10.5.4 server.
    I have this issue after running a task on multiple computers. For instance - I install an update on 15 eMacs, takes a few minutes, task is reported as completed. If I go back to the main computers list, it only shows as many as can fit on the screen (about 50), no scroll bar, but status bar still shows 96 computers. You can navigate below the bottom of the list using the arrow keys, but you won't see the computers being highlighted. +A will select all the computers too, but you won't see them, or the scroll bar until you quit and restart.
    I have had to do this already about 5 times just today, as I have different machines needing different updates, and like to perform the tasks individually.
    Note that this doesn't happen to me after a quick task like remote shutting down or logging out a machine, its only after I have sent an install task to more than one machine.
    As for screen refreshes, they don't seem to work during a task - If I am watching a list of machines installing an application update, I have to highlight the machines over and over, to make the progress refresh. +Y doesn't work.

  • JTable - custom JTableHeader with UP, DOWN sorting icon

    This is my code to create a custom JTableHeader.
    class MyHeaderRenderer extends DefaultTableCellRenderer {
    public MyHeaderRenderer() {
    setIcon(new ImageIcon("1.png"));
    setHorizontalAlignment(SwingConstants.CENTER);
    setBackground(Color.YELLOW);
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel> (tableModel);
    table.setRowSorter (sorter);
    table.getColumnModel().getColumn(2).setHeaderRenderer(new MyHeaderRenderer());After setting a custom header renderer, the default UP and DOWN sort image
    is not displaying in the table header. How can I show those images.
    Thanks in advance.

    Hi Ashish,
    In Table properties once you map any method to onSort event, the sort icons will appear automatically. But in your case its not working. I suggest you check the portal theme you are using.
    If you manage to get the icon deom some where
    To set the icon go to Theme Editor >Complex Elements>Tables--> Under Sort Icons you can browse for the icons and set it.
    Where you can find the icon ?
    Under Theme Editor --> Theme Transport --> Under Export theme. You can download your theme from here, unzip and look for the icon under "YourThemeFolder\ur.zip\common\tableview"
    Please try this if you are unble to find the icon, let me know
    Regards,
    Shibin

  • Pass parameters into CellRenderer

    Hello!
    I want to pass parameters into CellRenderer.
    How can I do that?

    Found solution!
    Create method, that set my Bean in CellRenderer, in what I keep my values, and call this method when create my CellRenderer. Than Use MyBean inside CellRenderer when it render cell.
    JSP:
    <hbj:tableView id="NewTable" model="LotsBean.ModelLots"
              design="TRANSPARENT"
              headerVisible="false"
              footerVisible="false"
              fillUpEmptyRows="false"
              selectionMode="NONE"
              visibleFirstRow="1"
              rowCount="16"
              width="100%" >
              <%  MyCellRenderer MyCell = new MyCellRenderer();
                     MyCell.setST(MyBean);
                     NewTable.setUserTypeCellRenderer(MyCell); %>
         </hbj:tableView>
    CellRenderer class:
         public void setST(user_registration_bean Bean){
              MyBean = Bean;

  • JTableHeader

    Hello,
    How can I increase the width of a column header.
    I am using JTableHeader class to create the header and now i want to increase the width of the column and the column itself.
    Thanks in advance.
    Regards,
    suri

    I'm not an expert but I think you can do it with a TableColumnModel
    TableColumnModel tcm = yourtable.getColumnModel();
    TableCellRenderer renderer = new TableCellRenderer();
    tcm.getColumn(0).setCellRenderer(renderer); //specify which column you want to set
    tcm.getColumn(0).setPreferredWidth(10); //specify the  width you want for that columnHope it helps.

  • JTableHeader + columns

    Hello to all!!!!!
    I speak spanish
    I am working with a jTable in which the idea is to take information from a DB and to show it by this component. But it is that the columns of the table can be changed of position and be changed the size of them. So that this does not happen I read in the API in the JTableHeader class the methods setReorderingAllowed() and setResizingAllowed() which handle this, but I can?t to know, of how they are used since I have proven several forms and throws errors, this is what I make:
    TableModel dataModel = new AbstractTableModel() {
    final String[ ] columnNames = { "Name", "Last name", "Pastime", "Years of Practices", "Soltero(a)" };
    Object[][ end ] dates = {
    { "Mary", "Campione"," To ski ", new Integer(5), new Boolean(false) },
    { "Lhucas", "Huml"," To slide ", new Integer(3), new Boolean(true) },
    { "Kathya", "Walrath"," To climb ", new Integer(2), new Boolean(false) },
    { "Marcus", "Andrews"," To run ", new Integer(7), new Boolean(true) },
    { "Angela", "Lalth"," To swim ", new Integer(4), new Boolean(false) } };
    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return data.length; }
    public String getColumnName(int col) { return columnNames[col ]; }
    public Object getValueAt(int row, int col) { return data[row][col ]; }
    public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); }
    JTable jTable1 = new JTable(dataModel);
    JTableHeader to tableheader = jTable1.getTableHeader(); tableheader.setReorderingAllowed(false);
    JScrollPane jScrollPane1 = JTable.createScrollPaneForTable(jTable1);
    and the other form is to change:
    JTableHeader to tableheader = jTable1.getTableHeader(); tableheader.setReorderingAllowed(false);
    By:
    jTable1.getTableHeader().setReorderingAllowed(false);
    With first it throws the following error to me:
    invalid method declaration; return type required and illegal start of type.
    With second form: malformed passes + the same expression.
    In addition, I am working with JBuilder2, that comes with JDK 1.1
    How work these metodos and the JTableHeader class, Will be problem of my JDK of which it does not allow east type me of declarations? Why it throws these errors to me? Who me can throw a hand, beforehand many thanks.

    I attempted to use Darryl's Default Table Header Cell Renderer, but I was unable (it requires java 1.6).
    I modified the code to make a very simple renderer. It does the job apropriately, but the header cell does not change its color (to red or white) unless the window is resized. Here is my very simple renderer (based on Darryl's one). What am I missing now?
    Thanks once more,
    Federico
    public class MyDefaultTableHeaderCellRenderer extends DefaultTableCellRenderer {
         public String jorl = "hola";
         public boolean tmp = false;
         public MyDefaultTableHeaderCellRenderer() {
              setHorizontalAlignment(CENTER);
              setHorizontalTextPosition(LEFT);
              setOpaque(true);
         public Component getTableCellRendererComponent(JTable table, Object value,
                                                                   boolean isSelected, boolean hasFocus, int row, int column) {
              super.getTableCellRendererComponent(table, value,
                                                           isSelected, hasFocus, row, column);
              if(table.isColumnSelected(column)) {
                   setBackground(java.awt.Color.red.darker());
              } else {
                   setBackground(java.awt.Color.white);
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              return this;
    }

Maybe you are looking for

  • Definition could not be found

    I am getting a couple of error when I try to use a component as a itemrender for my tile list. Both of these mxml files are in the same folder. I am getting the following errors. 1120 Access of undefinded property PropertyThumb 1172 Definition Proper

  • Bug or feature: Finder's sidebar and shared drives

    I don't know if this is a bug or an incomplete feature. I have a Windows fileserver on the network. In Finder if I go to afp://<ipaddress> and authenticate with name and password I get a window with the list of available Apple shares. So far so good,

  • Very basic questions about SMC

    I've never used SMC before and I have some basic questions. I'm trying to set up the Sun Management Colsole to manage LDAP users in accordance with the instructions in Tom Bialaski's book LDAP IN THE SOLARIS OPERATING ENVIRONMENT. My questions are: 1

  • Adobe Encore CS4 crashes during Render Progress

    After creating entire menu without any problems ( there is occasional encore system crash...) I go to File and then Render Project. Rendering process start with rendering of my audio file and then it goes to "Rendering menu" and crashes every time! I

  • How to set a perspective to a page ?

    Hi. I already know how to set a perspective for an item but I didn't find how to do this for a whole page. Does somebody knows how to do that ? Thanks Donald