Highlight JTable Header

Hello,
I want to be able to change the color of a JTable header of a column ie highlight it when a user clicks on the table header. Is there a way to do this? I'vd done a google search but nothing seems to address this. Any help is much appreciated. Thanks.
vyang

Try this piece of code on for size. The HeaderRenderer class is far from complete but it should give you something substancial to work with. This renderer also using GradientPainting to give you an extra boost in terms of appearance.
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class HeaderRenderer extends DefaultTableCellRenderer implements
                MouseListener, MouseMotionListener {
    Color bg = new Color(242,242,255), fg = Color.black;
    Rectangle paintingRect = null,
        lpr = null; //last painted rect
    JTableHeader header = null;
    public boolean isOnCol = false, highlightClickedCol = false;
    private int paintingCol = -1, clickedCol = -1, currentCol = -1;
     * Buffer gradient paint.
    GradientPaint gp = null, hoverGradient, columnGradient;
     * The current sorting state of the columns
    SortOrder sortOrder = null;
    public HeaderRenderer() {
        super();
        setFont( getFont().deriveFont(Font.BOLD) );
        //setBackground( bg );
        setForeground( fg );
        setOpaque(false);
        setBorder( BorderFactory.createCompoundBorder (BorderFactory.createMatteBorder(0,0,1,1, new Color(200,200,230) ),
                        BorderFactory.createEmptyBorder(4,7,4,4)) );
        setHighlightClickedColumn(true);
    public void setColumnGradient(GradientPaint gp) {
        this.columnGradient = gp;
    public void setHoverGradient(GradientPaint gp) {
        this.hoverGradient = gp;
    public GradientPaint getColumnGradient() {
        return columnGradient;
    public GradientPaint getHoverGradient() {
        return hoverGradient;
    public void setHighlightClickedColumn(boolean b) {
        highlightClickedCol = b;
    public void paintComponent(Graphics g) {
        Rectangle rect = paintingRect;
        Graphics2D g2 = (Graphics2D)g;
            g2.setPaint(gp);
            g2.fillRect( 0, 0, rect.width, rect.height );
        FontMetrics fm = g.getFontMetrics();
        int strWidth = fm.stringWidth( getText() );
        /*if(currentCol == clickedCol) {
            if( sortOrder == SortOrder.ASCENDING )
                new ArrowIcon( ArrowIcon.UP ).paintIcon(this, g, strWidth + 15, 8);
            else if(sortOrder == SortOrder.DESCENDING )
                new ArrowIcon( ArrowIcon.DOWN ).paintIcon(this, g, strWidth + 15, 8);
        sortOrder = null;
        super.paintComponent(g);
    public void attachListener() {
        header.addMouseListener(this);
        header.addMouseMotionListener(this);
    public void mouseEntered(MouseEvent e) {
        isOnCol = true;
    public void mouseExited(MouseEvent e) {
        isOnCol = false;
        paintingCol = -1;
        header.repaint();
    public void mouseReleased(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {
        clickedCol = header.columnAtPoint( e.getPoint() );
    public void mousePressed(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {
       // isOnRow = true;
        paintingCol = header.columnAtPoint( e.getPoint() );
        paintingRect = header.getHeaderRect( paintingCol );
        header.repaint( paintingRect.x, paintingRect.y, paintingRect.width, paintingRect.height );
        if(lpr != null) {
            header.repaint(lpr.x, lpr.y, lpr.width, lpr.height);
        lpr = paintingRect;
    public void mouseDragged(MouseEvent e) {
        //isOnRow = true;
        paintingCol = header.columnAtPoint( e.getPoint() );
        paintingRect = header.getHeaderRect( paintingCol );
        header.repaint( paintingRect.x, paintingRect.y, paintingRect.width, paintingRect.height );
        if(lpr != null) {
            header.repaint(lpr.x, lpr.y, lpr.width, lpr.height);
        lpr = paintingRect;
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
         boolean hasFocus, int row, int col) {
        currentCol = col;
        if(header == null) {
            header = table.getTableHeader();
            attachListener();
        if(table.getRowSorter() != null && table.getRowSorter().getSortKeys().size() > 0 ) {
            java.util.List<? extends RowSorter.SortKey> keys = table.getRowSorter().getSortKeys();
            for(RowSorter.SortKey key: keys) {
                if(key.getColumn() == col) {
                    sortOrder = key.getSortOrder();
        Rectangle rect = table.getTableHeader().getHeaderRect(col);
        if( (isOnCol && paintingCol == col) || (clickedCol == col && highlightClickedCol)  ) {
            gp = new GradientPaint( rect.x, rect.y + rect.height, new Color(200,220,235),
                                rect.x, rect.y, new Color(230,235,250)  );
            setForeground( new Color(50,50,50) );
        } else {
            gp = new GradientPaint( rect.x, rect.y + rect.height, new Color(235,240,245) ,
                                    rect.x, rect.y, new Color(245,250,255) );
            setForeground( new Color(100,120,160) );
        paintingRect = rect;
        //JLabel renderer = new JLabel();
        setText( value == null ? "" : value.toString() );
        //setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
        //   brdr) );
        return this;
    public static void main(String[] args) {
        DefaultTableModel model = new DefaultTableModel(20,5);
        JTable table = new JTable( model );
            table.getTableHeader().setDefaultRenderer( new HeaderRenderer() );
        JFrame frame = new JFrame("Header Renderer Test");
            frame.add( new JScrollPane(table) );
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
}ICE

Similar Messages

  • How do i change the cursor on a jtable header when clicked for sorting?

    here is my question, how do i change the cursor on a jtable header when I click the header for sorting?
    I think it is suppose to be in the fragment of code where the header listener is implemented for sorting, but I'm not quite sure what is the exact component that holds everything so that i can change the cursor...
    below is what I've tried, but it doesn't seem to work... thank you
    public void addMouseListenerToHeaderInTable(JTable table) {
    final TableSorter sorter = this;
    final JTable tableView = table;
    tableView.setColumnSelectionAllowed(false);
    MouseAdapter listMouseListener = new
    MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    TableColumnModel columnModel =
    tableView.getColumnModel();
    int viewColumn =
    columnModel.getColumnIndexAtX(e.getX());
    int column =
    tableView.convertColumnIndexToModel
    (viewColumn);
    System.out.println("column = "+column);
    if (e.getClickCount() == 1 && column != -1) {
    System.out.println("Sorting ...");
    Cursor oldCursor =
    tableView.getRootPane().getCursor();
    System.out.println("oldCursor.getType()
    = "+oldCursor.getType());
    if (oldCursor.getType() !=
    Cursor.WAIT_CURSOR){
    JComponent parentPane =
    tableView.getRootPane();
    parentPane.getContentPane().setCursor
    (new Cursor(Cursor.WAIT_CURSOR));
    parentPane.setCursor(new Cursor
    (Cursor.WAIT_CURSOR));
    Cursor newCursor =
    parentPane.getCursor();
    System.out.println("newCursor.getType
    () = "+newCursor.getType());
    int shiftPressed = e.getModifiers(
    &InputEvent.SHIFT_MASK;
    boolean ascending = (shiftPressed == 0);
    //System.out.println("tableView.getRootPane()
    is "+tableView.getRootPane().getRootPane());
    sorter.sortByColumn(column, ascending);
    tableView.getRootPane().setCursor(new Cursor
    (Cursor.DEFAULT_CURSOR));
    //System.out.println("Done sorting");
    JTableHeader th = tableView.getTableHeader();
    th.addMouseListener(listMouseListener);
    }

    Hi,
    Try setting the cursor for the table header.
    table.getHeader().setCursor(Wait_Cursor);
    Bala.

  • How to add  ComboBox in Jtable Header

    Hello everyone,
    I want to add a Combox box in JTable Header .Basically it works as central access to whole table e.g. by selecting delete row in combo box then it should delete the current selected row.If somebody has any idea please share it.
    Thanks in advance.

    The individual headers are not Swing components and therefore do not respond to mouse events in the same way as Swing components. Why don't you just have a popup menu that is positioned over the currently selected row? If you want to apply an action to all selected rows then have a set of buttons placed above the table header.

  • JComboBox in the JTable Header - TableCellEditor problem

    Hi,
    I have added JComboBox into the JTableHeader. But I can't Edit that combobox. It is looking like an icon. I have added JPanel into the JTable Header Row. In JPanel i have added one JLable and JComboBox.
    Please any one of you give me the solution.
    Thanks,
    Shrini V.

    The table will display what ever value it has in its model. When you add the row, there is no data in the second column. You'll have to supply it.
    public void insertMyRowCombo (Object [] r,
                                      JComboBox c,
                                      JTable t) {
           // {"rut", "puntaje cas", "beneficio", "fecha inicio", "fecha termino", "monto"};
            DefaultTableModel tm = (DefaultTableModel) t.getModel();
            tm.addRow(r);
            TableColumn col = t.getColumnModel().getColumn(2);
            col.setCellEditor(new DefaultCellEditor(c));
            tm.setValueAt( c.getItemAt(0), 0, 2); //manually supply the value to col 2
        }ICE

  • Not able to edit the JTextField under the JTable header

    Hi,
    As per my requirement, i need to add the text field in JTable header for filtering the table records.
    i have added the text field but not able to enter any value (it is disabled).
    Can anyone please help me on this?

    Welcome to the forum.
    After reading how to format Code in this forum (SQL and PL/SQL FAQ ),
    please show us the code of your TableHeader implementation.
    bye
    TPD

  • Multiple Icon on Jtable header

    Hi All:
    Any one had used multiple icons on JTable header ? According to the user's clicking positon under one column, one of these icons should change such as changing from sorting up arrows to sorting down arrows.
    I got the mouse clicking position on the header and column, then depend on the location, I wanted to perfrom different things. But I have not figured out if I should call header renderer to perform the repaint or not ? If I use JTable header render, how should I confine the one column that change should happen? I don't want to have all columns repainted. If I treat each column indivisually, should I reconstruct the JTable ? I used SortableTableModel to create the JTable.
    Any help is appreciated.
    Regards

    Here's the idea. I didn't test thisclass JComponentCellRenderer extends JButton implements TableCellRenderer {
        public JComponentCellRenderer (ImageIcon ii) { super("",ii); }
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            setText(value.toString());
            return this;
    }and thentblChanges.getColumnModel().getColumn(0).setHeaderRenderer(new JComponentCellRenderer(new ImageIcon( "CheckBoxHeaderImage" )));

  • How to set height of JTable Header ?

    How to set height of JTable Header and set the text to another size ?

    You can set the font of the header as you can for any component. The font will dictate the preferred height of the header. If you don't like the preferred height, you can set that as well.
    // add table to a scroll pane or the header will not appear
    JTable table = new JTable(...);
    container.add(new JScrollPane(table));
    // get a reference to the header, set the font
    JTableHeader header = table.getTableHeader();
    header.setFont(new Font(...));
    // set the preferred height of the header to 50 pixels.
    // the width is ignored by the scroll pane.
    header.setPreferredSize(new Dimension(1, 50));Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Changing jtable header when moving down

    Hi,
    I would need changing Jtable header, when the cursor switches between lines
    How to do this ???
    Best Regards
    S.Ancelot

    1) You could create a second table header and replace the old one using scrollPane.setColumnHeaderView(...)
    2) Or, you could simply change the values in each TableColumn and then repaint the header.

  • Remove JTable header

    i created a small JFrame to test removing the JTable header
    the Sutation : a JTable in JScrollPane in JPannel.
    the Test as well as my program.
    i create Model in both cases. my won.
    the properties of the both components are almost the same.
    the diffrence : in the test JFrame look great.
    in my program it remains a small hieght from the Header about 2pixels. and i can see it.
    any help?
    thx

    i created a small JFrame to test removing the JTable
    header
    the Sutation : a JTable in JScrollPane in JPannel.I can follow you up to this point
    the Test as well as my program.? the test of what? and what did they do? you forgot a verb ...
    i create Model in both cases. my won.two cases ... which are they? and which is your case that won?
    the properties of the both components are almost the
    same.oh, two components ... and which are they?
    >
    the diffrence : in the test JFrame look great.which test?
    in my program it remains a small hieght from thewhere is the difference between a test of your program and your program?
    Header about 2pixels. and i can see it.
    any help?sorry, please explain clearly what your problem is.
    thxRommie.

  • How to make JTable Header to Blink?

    Hi Everybody...
    I need the code to blink the JTable Header in Java Swings..
    Im trying since long time...
    Please help me out...
    Thanks in Advance...

    I have posted it by mistakly...yeh, just like you mistakly cross-posted your other thread/s at javaranch.
    i think u dont think positivly..Oh I positivly know you're a fcukwit
    better for you to toodle off and try to write a Hello World app.

  • How to remove JTable header from JScrollPane?

    Hi!
    Does anyone know how to remove the JTable header from the JScrollPane the table is placed in? I tried calling
    scrollpane.setColumnHeader( null ) and
    scrollpane.setColumnHeaderView( null )
    but none of the above worked...
    Thanks!
    Fil

    Hi,
    The easiest way to do this is to put an extra layer between the table and the scrollpane as follows:-
    JPanel p = new JPanel(new BorderLayout());
    // Add it to the north rather than center so that the table background color
    // won't cover the empty part of the view port.
    p.add(table, BorderLayout.NORTH);
    JViewport v = tableScroll.getViewport();
    v.setView(p);
    where table is your JTable and tableScroll is your JScrollPane.
    Hope this helps,
    Ian

  • Check Box in JTable Header Changes

    Hi All,
    In JTable, we have JCheckBox as header. And respetive data also check box's (new Boolean() objects) i have given. When i select header check , all the data check boxes are getting selected. Later if unselect any data check box, Header check box should be deselected. I am not able to deselect Header check box, if the user unselect any data check box.
    So Please send sample program on this. And please try to solve my question.
    Thanks to All
    Mohan

    Cross-post: http://forum.java.sun.com/thread.jspa?threadID=5202809

  • Problem with JTable Header

    I want to show a JTable in a scrollPane , But i don't want to show its header.
    i have tried table.getHeader().setVisible(false) but it shows a gap on table top which is not desired.
    If anybody can help me.

    If I remember correctly, if u set the headervalues to null they wont show.

  • Highlight JTable Row with Right-Click

    How can I get a JTable to highlight a row when that row is right-clicked? Thanks, Jeremy

    table.addMouseListener(new MouseAdapter()
    public void mouseClicked (MouseEvent e)
    if(e.isMetaDown())
    int row = table.rowAtPoint(e.getX((), e.getY();
    table.setSelectionInterval(row, row);
    });Or something like that.

  • Clickable button in jtable header

    Here is a modification of camickr code to make buttons clickable in the jtable cells. The question is how to modify it to make them clickable in the table headers. It looks like there is quite a different behavior in cells and headers (naturally it probably should be this way). More specifically, I guess my question is how do you modify MyColHeaderRenderer class in the code below. Btw, this is also an example I've mentioned in one of the previous posts when a component responds to a press mouse event but not click event when first pressed.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    * @author
    public class Example4a extends JFrame {
        MyCell[][] data = {{new MyCell("A1"), new MyCell("A2")}};
        MyColHeader[] headers = {new MyColHeader("col 1"), new MyColHeader("col 2")};
        /** Creates a new instance of Example5 */
        public Example4a() {
            setTable();
            setSize(200, 200);
            setVisible(true);
            super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void setTable() {
            DefaultTableModel model = new DefaultTableModel(data, headers){
                public Class getColumnClass(int column) {
                    return MyCell.class;
            MyTable table = new MyTable(model);       
            JScrollPane scrollpane = new JScrollPane(table);
            JPanel top_panel = new JPanel();
            top_panel.setLayout(new BorderLayout());
            getContentPane().add(top_panel);
            top_panel.add(scrollpane, BorderLayout.CENTER);
        public static void main(String[] args) {
            Example4a ex = new Example4a();
        class MyTable extends JTable {
            public MyTable(TableModel model) {
                super(model);
                MyCellRenderer cell_renderer = new MyCellRenderer();
                MyColHeaderRenderer header_renderer = new MyColHeaderRenderer();
                TableColumnModel columnModel = getColumnModel();
                for(int i=0; i<columnModel.getColumnCount(); i++) {
                    TableColumn column = columnModel.getColumn(i);
                    column.setCellRenderer(cell_renderer);
                    column.setCellEditor(cell_renderer);
                    column.setHeaderRenderer(header_renderer);
                this.setRowHeight(50);
        class MyCellRenderer extends AbstractCellEditor
                implements TableCellRenderer, TableCellEditor {
            MyCell editCell;
            public MyCellRenderer() {
            public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return (MyCell)value;
            public Component getTableCellEditorComponent(
                    JTable table, Object value, boolean isSelected, int row, int column)  {
                editCell = (MyCell)value;
                return editCell;
            public Object getCellEditorValue() {       
                return editCell;
        class MyCell extends JPanel {
            String text;
            JButton button;
            public MyCell(String text_) {
                text = text_;
                setLayout(new GridBagLayout());
                button = new JButton(text);
                button.addMouseListener(new MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("cell button is clicked");
                    public void mouseEntered(MouseEvent e) {                   
                    public void mouseExited(MouseEvent e) {
                    public void mousePressed(MouseEvent e) {
                        System.out.println("cell button is pressed");                   
                    public void mouseReleased(MouseEvent e) {
                add(button, new GridBagConstraints(0, 0, 1, 1, 0, 100.0
                    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(10, 5, 10, 5), 20, 10));
        class MyColHeader extends JPanel {
            String text;
            JButton button;
            public MyColHeader(String text_) {
                text = text_;
                setLayout(new GridBagLayout());
                setBorder(BorderFactory.createEtchedBorder());
                button = new JButton(text);
                button.addMouseListener(new MouseListener() {
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("column header button is clicked");
                    public void mouseEntered(MouseEvent e) {                   
                    public void mouseExited(MouseEvent e) {
                    public void mousePressed(MouseEvent e) {
                        System.out.println("column header button is pressed");                   
                    public void mouseReleased(MouseEvent e) {
                add(button, new GridBagConstraints(0, 0, 1, 1, 0, 0.0
                    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(3, 0, 3, 0), 5, 0));
        class MyColHeaderRenderer implements TableCellRenderer {
            public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return headers[column];
    }

    draw a shape and ensure it is selected
    in the Inspector > hyperlink > enable as hyperlink > click slide button and enter the slide number
    place the object in slide 2 and create a dissolve to automatically build on entry for the object

Maybe you are looking for

  • RE: Video problems after disconnecting DVI to VGA adaptor...

    I was playing a game (C&C Generals) the other day on Vista with an external monitor connected via the DVI to VGA adaptor. During the game, I decided to move my MBP so I disconnected the adaptor. The screen started flickering and I had to reset the MB

  • Repeated connection/ connection lost with BT on No...

    Hi. I use a Nokia 8800 (2 years old), Win XP SP3, newest PC Suite. BT= Bluetooth is always on, supposed to sync when I come home (first connection!). How come I see all minutes "connected=home...", minute later "disconnected home..." This, I asume, i

  • HT1277 How can I re-set the default account in Mac Mail?

    I have two email accunts feeding into Mac Mail.  I want the system to default send from Account A, but it always defaults to Account B.  Thanks!

  • Odd address window behavior

    Mail Version 2.0.5 (746/746.2) This is how I have my Mail.app window arranged: I have the main Mail window open on the left, the address window on the right and the Activity Viewer window below the address window. If I right click > Edit Card on a na

  • Depreciation posted for wrong GL

    Hi Sap experts, My issue is "Depreciation posted for wrong GL" --(periods-4th,9th and 12) Here my client is maintained 01for book depreciation area and 11-for IFRS depreciation area Actually Depreciation posted as:-Depreciation a/c Dr 1000/-