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.

Similar Messages

  • 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

  • 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

  • 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?

  • 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

  • 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;
    }

  • Rollover effects in custom JTableHeader

    My application requires JTable to have headers that span multiple columns. As this feature does not have native support in JTableHeader, the only way I am aware to achieve this functionality is to create a subclass of JTableHeader, and a subclass of BasicTableHeaderUI, with a custom paint method that invokes header's (or column's) TableCellRenderer in the required size and shape. There are examples for how this can be done in various places.
    When this technique is applied, and the customized JTableHeader is inserted into a JTable, the multi-column effect becomes functional, but the appearance of the headers is changed from the PLAF default to a plain replacement. This can be circumvented by pulling the cell renderer from the table's original header, and inserting it into the new header. At this point, the original PLAF appearance is preserved, but the rollover effects are absent.
    Can anyone suggest a modification that would restore the rollover effects, or more generally, a technique to make a JTableHeader span multiple columns while preserving all original elements of the PLAF?

    Lieve -
    Could you help me out?  I believe I'm trying to do something similar. I'm attemtping to create accordion navigation whereby:
    There are 5 bars running from top to bottom on the left side of the screen (numbered from 1-5).
    On the right side is the canvas.
    Pressing Bar #2 (a button) will cause the whole button (2) to slide to the extreme right and buttons 1,3,4, and 5 will be next to each other on the left.
    On the right side (the canvas) - will be content for page 2
    Pressing the #5 button will cause button 2 to move to the left with buttons 1,2, 3, and 4 - and #5 button will be on the extreme right. The canvas will show content for page 5.
    Hope this makes sense. Is this doable all within Cp 7?
    Many thanks!
    Kevin
    Message was edited by: kevin_stagg

  • Making a JTableHeader Sortable Renderer for Windows

    I have implemented sorting for a spreadsheet (using the Tame Library). The user can sort by a partciluar column by sorting on the Table Header cell for that column. I replaced the JTableHeader default cell renderer (which is based on Jlabel) with a different renderer basd on a JButton because I need to get it to respond to event, show it has been pressed and so on.
    Functionally this works fine but using JButtons on Windows with Windows LAF doesnt look anything like the table headers you get on something like Windows Explorer. Has anybody managed to create a renderer which looks more like the Windows Explorer stuuf please.

    use TableSorter(version 2.0 02/27/04)
    The JavaTM Tutorial
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    public class TestPanel extends JPanel {
      public TestPanel() {
        super(new BorderLayout());
        TestModel model = new TestModel();
        TableSorter sorter = new TableSorter(model);
        JTable table = new JTable(sorter);
        sorter.setTableHeader(table.getTableHeader());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        model.addTest(new Test("name1", "asdfasd"));
        model.addTest(new Test("name2", "qerqwerwq"));
        model.addTest(new Test("named", ""));
        model.addTest(new Test("namec", "zxcvxzcvzxcv"));
        model.addTest(new Test("nameb", "fasdfasd"));
        model.addTest(new Test("namea", ""));
        model.addTest(new Test("name0", "12341234"));
        model.addTest(new Test("name0", ""));
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
      class TestModel extends javax.swing.table.DefaultTableModel {
        public static final String NUMBER  = "aaa";
        public static final String MASTER  = "sss";
        public static final String COMMENT = "ddd";
        private String[] columnNames = {NUMBER, MASTER, COMMENT};
        private final Vector list = new Vector();
        public boolean isCellEditable(int row, int column) {
          if(column<1) {
            return false;
          return true;
        public void addTest(Test tst) {
          list.add(tst);
          Integer num = new Integer(list.size());
          Object[] obj = {num, tst.getName(), tst.getComment()};
          super.addRow(obj);
        public Test getTest(int index) {
          Integer num = (Integer)getValueAt(index, 0);
          return (Test)list.elementAt(num.intValue()-1);
        public int getColumnCount() {
          return columnNames.length;
        public String getColumnName(int col) {
          return columnNames[col];
      class Test {
        private String name;
        private String comment;
        public Test(String name_, String comment_) {
          name = name_;
          comment = comment_;
        public void setName(String str) {
          name = str;
        public void setComment(String str) {
          comment = str;
        public String getName() {
          return name;
        public String getComment() {
          return comment;
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        try{
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch (Exception e) {
          throw new InternalError(e.toString());
        final JFrame frame = new JFrame("title");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TestPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

  • JTableHeader and Mac L&F

    I want to change the background color of my header on my JTables running on a Mac. I've tried table.getHeader().setBackground(myColor) but that doesn't work. So I thought it might be a L&F thing. I tried the following:
    UIManager.getDefaults().put("TableHeaderUI","javax.swing.plaf.basic.BasicTableHeaderUI");and then set the background color. That didn't work either. Does anyone know how to change the background color of a JTableHeader withhin the Mac Aqua L&F?
    I'm using using Java 5.

    icons appear on them (an X for Cancel and check mark for OK)What version of Windows?
    I've never seen this under XP (classic skin).

  • Assigning mouse listener to JTableHeader

    Can anyone point me to an example or know how to assign a mouselistener to the individual column headers in JTable Header?

    I haven't tried to set a mouse listener for individual columns, but here is how you can set a listener for the entire header and check which column was clicked:
    JTableHeader tableHeader = table.getTableHeader();
    tableHeader.addMouseListener( new MouseAdapter()
         public void mouseClicked(MouseEvent e)
              TableColumnModel columnModel = table.getColumnModel();
              int column = columnModel.getColumnIndexAtX( e.getX() );
              if (e.getClickCount() == 1 && column == 0)
                   do something for column 0
    });

  • JTableHeader mouseClick

    Hi
    I have a JTable with diffrent columns. I want to sort the table by clicking on the header. I cant add a listener on 1 singel header column, just the whole header. So when i get the event Im unable to locate witch column to order by.
    Maybe Ive just looked at it too long lol, so can anyone help me out?
    This is from my MouseListener
              public void mouseClicked(MouseEvent e) {
                   JTableHeader tblh =  (JTableHeader) e.getSource();
                   System.out.println(tblh.getName());
                   System.out.println(tblh.toString());
                   System.out.println("Yeah! Click in header");
              }

    public void mouseClicked(MouseEvent e) {
         JTableHeader tblh =  (JTableHeader) e.getSource();
         TableColumnModel cm = tblh.getColumnModel();
         int viewColumn = cm.getColumnIndexAtX(e.getX());
         int modelColumn = cm.getColumn(viewColumn).getModelIndex();
    }Note that there are two different column indeces floating around since a JTable allows you to change the order of the columns.
    Btw, there is a TableSorter tutorial somewhere among Sun's Swing tutorials. I'm sure you can find it if you search for it on google.

  • 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!

  • JTableHeader problem

    I have a custom JTableHeader and a MouseListener on the header because when i click the header i show an arrow icon that follow the order of the data.
    The header works fine since i resize the column:when i resize the icon appear on all the column but i want i t only on the cliccked column.
    public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent( table,  value, isSelected,  hasFocus,  row, column);
                 this.setBorder(BorderFactory.createEtchedBorder());
                this.setOpaque(false);
              //  System.out.println("COLUMN " + column + " COLSELECTED "  + colSelected);
                if(!usingResizeCursor())
                  if(colSelected == column)
                       if (getCurrentOrder() == ORD_CRESC) {
                              setText(table.getColumnName(column));
                              Icon icon = new ImageIcon(getClass().getResource(URLROWUP));
                              setIcon(icon);
                              this.setIconTextGap(10);
                              revalidate();
                       else
                             setText(table.getColumnName(column));
                             Icon icon = new ImageIcon(getClass().getResource(URLROWDOWN));
                             setIcon(icon);
                             this.revalidate();
                    else
                      Icon icon = new ImageIcon(getClass().getResource  (URLROWEMPTY));
                      setIcon(icon);
                      setText(table.getColumnName(column));
                      this.revalidate();             
                 return this;
            }

    This section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting]How to Use Tables has a working example of a TableHeader with sort icons.

  • Sharing the same JTableHeader for several JTables

    Hello,
    I would like to know if it is possible to have a JTableHeader common to several JTables.
    For instance the resizing of a column in the common header should resize the corresponding column for all the JTables.
    Thanks for your help !
    Joel

    Except there's a bug introduced in 1.4x (1.3 works fine) that disables resizing of the columns in all the tables except the last into which the shared columnModel is set.
    To workaround, subclass JTable and override columnMarginChanged:
        JTable table = new JTable()
        // including the following will fix the bug
          public void columnMarginChanged(ChangeEvent e) {
            if (isEditing()) {
              removeEditor();
            TableColumn resizingColumn = null;
            if (tableHeader != null) {
              resizingColumn = tableHeader.getResizingColumn();
            if (resizingColumn != null) {
              if (autoResizeMode == AUTO_RESIZE_OFF) {
                resizingColumn.setPreferredWidth(resizingColumn.getWidth());
              } else {    // this else block is missing in jdk1.4 as compared to 1.3
                doLayout();
                repaint();
                return;
            resizeAndRepaint();
          private int viewIndexForColumn(TableColumn aColumn) {
            TableColumnModel cm = getColumnModel();
            for (int column = 0; column < cm.getColumnCount(); column++) {
              if (cm.getColumn(column) == aColumn) {
                return column;
            return -1;
        };Greetings
    Jeanette

Maybe you are looking for

  • Jerky import & playback with 10.3.9 and QT 7.0.2

    Posting new topic as follow-on from prior topic. Sorry if making a hash of this, but pretty new to Discussions, Apple and iMovie! Have tried fixes offered by David Babsky (many thx!!), but no impact. David pointed me to discussions on "Jerky" playbac

  • How can I transfer the iPhone weather app to the iPad?

    I really like the quick, unadorned, temperatures plus daily weather symbols of the iPhone's built-in weather app. How do I transfer that app to the iPad? I've tried all sorts of weather apps--and generally find that using a Safari bookmark to the Wea

  • How to create web interface whose name includes _ (underscore)

    Hi Experts, In my project we are creating web interface. The steps are as below: 1) Run transaction code upspm and copy the planning folder 2) Save the planning folder as web enabled planning folder 3) Generate web interface for step 2. Here I have t

  • Cursor changes to X shape at certain sizes

    I currently am running Photoshop CS6 on Windows 7. When I am using the Brush or Pencil tools, sometimes the Cursor will change to a curved X shape. This appears to happen at certain sizes (between 65px to250px) and then goes back to the normal circle

  • Opening numbers file on iPhone

    I have created a numbers file on my mac, then uploaded it to iCloud. When I try and open the file in Numbers on my iPhone, I get the message "....an unknown error occurred spreadsheet couldn't be imported..." I have tried different spreadsheets and e