JTable rows listener

I have this Jtable in my program. Suppose I want to double-click on a row in the table, and this is supposed to cause a listener to respond depending on which row is clicked. what type of listeners do I need to add to the Jtable?

    myTable.addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent me) {
     if (me.getClickCount()!=2) return;
     int row = myTable.rowAtPoint(me.getPoint());
     System.out.println("Row="+row);

Similar Messages

  • Changing JTable Row Color OnMouseOver

    Hello everybody,
    is it possible to change JTable Row Color when Mouse passes over it ??
    THanks!

    Yes...
    You have to override the table cell renderer and set the color of the rows based on flag.
    The flag can be turned on/off in a mouse motion listener of the table.

  • Add JTable Row Headers At The End Of The Rows(At Right)?

    hi all
    i got this example for adding JTable Row Headers,but it adds the headers at the left(beginning of the row)
    and i want to add the headers at the end of the row(at right),any ideas how to do that?
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.AbstractListModel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    * @version 1.0 11/09/98
    class RowHeaderRenderer extends JLabel implements ListCellRenderer {
      RowHeaderRenderer(JTable table) {
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
      public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {
        setText((value == null) ? "" : value.toString());
        return this;
    class RowHeaderExample extends JFrame {
      public RowHeaderExample() {
        super("Row Header Example");
        setSize(370, 150);
        ListModel lm = new AbstractListModel() {
          String headers[] = { "Row1", "Row2", "Row3", "Row4"};
          public int getSize() {
            return headers.length;
          public Object getElementAt(int index) {
            return headers[index];
        DefaultTableModel dm = new DefaultTableModel(lm.getSize(), 4);
        JTable table = new JTable(dm);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(18);
        JList rowHeader = new JList(lm);
        rowHeader.setFixedCellWidth(50);
        rowHeader.setFixedCellHeight(18);
        rowHeader.setCellRenderer(new RowHeaderRenderer(table));
        JScrollPane scroll = new JScrollPane(table);
        scroll.setRowHeaderView(rowHeader);
        getContentPane().add(scroll, BorderLayout.CENTER);
      public static void main(String[] args) {
        RowHeaderExample frame = new RowHeaderExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setVisible(true);
    }

    fixed by:
    list.setBackground(table.getTableHeader().getBackground());here's the full code:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.ComponentOrientation;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.DefaultListModel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.JTableHeader;
    * @version 1.0 11/09/98
    class RowHeaderRenderer extends JLabel implements ListCellRenderer {
      JTable table;
      RowHeaderRenderer(JTable table) {
        this.table = table;
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
      public Component getListCellRendererComponent(JList list, Object value,
          int index, boolean isSelected, boolean cellHasFocus) {
        list.setBackground(table.getTableHeader().getBackground());
        setText((value == null) ? "" : value.toString());
        return this;
    class RowHeaderExample extends JFrame {
      public RowHeaderExample() {
        super("Row Header Example");
        setSize(370, 150);
        setLocationRelativeTo(null);
        DefaultListModel lstModel = new DefaultListModel();
        lstModel.addElement("Row 1");
        lstModel.addElement("Row 2");
        lstModel.addElement("Row 3");
        lstModel.addElement("Row 4");
        DefaultTableModel dm = new DefaultTableModel(lstModel.getSize(), 4);
        JTable table = new JTable(dm);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setRowHeight(18);
        JList rowHeader = new JList(lstModel);
        rowHeader.setFixedCellWidth(50);
        rowHeader.setFixedCellHeight(18);
        rowHeader.setCellRenderer(new RowHeaderRenderer(table));
        JScrollPane scroll = new JScrollPane(table);
        scroll.setRowHeaderView(rowHeader);
        table.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        getContentPane().add(scroll, BorderLayout.CENTER);
      public static void main(String[] args) {
        RowHeaderExample frame = new RowHeaderExample();
        frame.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        frame.setVisible(true);
    }

  • Grouping and UnGrouping of JTable Rows?

    Hi,
    Has somebody done Grouping and UnGrouping of JTable Rows as we find in MS-Excel.
    Thanks & regards
    blue

    Hi,
    Have anyone done something like this.
    If u r not clear about the requirement:
    Please see the screenshot uploaded at below url:
    [http://www.geocities.com/coolneela/GroupableTable.JPG]
    As shown the screenshot i want the Group 1 ,2,3 to be expandable and hideable i.e should behave like a Jtree node.....In rest of the column User can enter any input i.e for the columns A,B,C..
    thanks & regards
    Neel

  • Sort jTable rows by column as Integer value

    Hi all,
    I have problem with sort jTable rows. I have some columns and in first are integer data. jTable sort that as String value..1,10,11,12....2,21, ...
    How can I do that?
    Thanks

    In the future, please post Swing questions to the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    What does the TableModel's getColumnClass method return for that column?

  • Getting ClassCastException When Trying To Color JTable Row?

    hi there
    i'm trying to set color for JTable Rows Using the method prepareRenderer
    and get the values of the second column which contains integer values
    and if it contain 0 integer value set the color row as red
    its already works and the row with 0 is set to red but when i try to select any cell in the table
    i'm getting
    java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integerat prepareRenderer
    although the second row which i'm trying to test it's values is Integer not String????????????
    here's the code:
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);
                             if(type!=null)                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        else
                        c.setBackground(Color.white);
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class,java.lang.String.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                        String editingValue = (String)getCellEditorValue();
                    if(!editingValue.equals("")){
                 try
                int i = Integer.parseInt(editingValue);
                catch(NumberFormatException nfe)
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;          
                    else{                                             
                     getComponent().requestFocusInWindow();
                     fireEditingCanceled();
                     JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                  return false;              
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

    hi again camickr
    i changed the stopCellEditing as you mentioned
    changed the getCellEditorValue to return an integer
    and give exception and error message if the value can't be converted into integer(non numeric)
    but the problem is when i run the program and change the value in any cell with numeric values
    or with non numeric or not changing the value and press enter
    it give the error message meaning it cannot convert the value to integer
    even if enter an int or don't change the value ????????
    here's what i did
    import javax.swing.border.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class Column_Filter {
      static JTable table;
    static DefaultTableModel dtm;  
        public static void main(String[] args) {
             String[]columns={"Name","Number","Price"};
             Object[][]data={  {"a",new Integer(5),new Integer(200)}
             ,{"b",new Integer(7),new Integer(400)}
             ,{"c",new Integer(0),new Integer(100)}
             ,{"d",new Integer(8),new Integer(800)}
             ,{"e",new Integer(3),new Integer(300)}         
             dtm=new DefaultTableModel(data,columns);
                        table=new JTable(dtm){
                      public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
                             public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                        Component c = super.prepareRenderer(renderer, row, column);
                        if (!c.getBackground().equals(getSelectionBackground()))
                             Integer type = (Integer)getModel().getValueAt(row, 1);                                                            
                             c.setBackground(type==0 ? Color.RED : Color.WHITE );
                        return c;
             TableColumnModel columnModel = table.getColumnModel();
             TableColumn col1 = columnModel.getColumn(1);         
             col1.setCellEditor(new TableEditor());
             TableColumn col2 = columnModel.getColumn(2);
             col2.setCellEditor(new TableEditor());
             table.setPreferredScrollableViewportSize(new Dimension(280,160));
             JScrollPane scroll=new JScrollPane(table);
             JLabel label=new JLabel("Column Stuff",JLabel.CENTER);
             JPanel panel=new JPanel();
             panel.add(scroll);
            JFrame frame=new JFrame("Column Stuff");
            frame.add(label,BorderLayout.NORTH);
            frame.add(panel,BorderLayout.CENTER);
            frame.setSize(300,300);
            frame.setResizable(false);
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 table=new JTable();     
                   table.setModel(new DefaultTableModel(new Object [][][] {},new String [] {"Name", "Number","Price"}) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.Integer.class,java.lang.Integer.class
                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
          class TableEditor extends DefaultCellEditor
              TableEditor()
                   super( new JTextField() );               
                setClickCountToStart(0);
              public boolean stopCellEditing()
                   try
                        Integer editingValue = (Integer)getCellEditorValue();
                   catch(ClassCastException exception)
               //when i enter any value in any cell this code is executed even i enter an int or don't change the value
                ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));       
                getComponent().requestFocusInWindow();      
                JOptionPane.showMessageDialog(null,"Data Input Error","Error",JOptionPane.ERROR_MESSAGE);
                return false;
                   return super.stopCellEditing();
                   public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   ((JComponent)c).setBorder(new LineBorder(Color.BLACK));
                   return c;
         }

  • How to get String form java JTable row?

    Hello everybody,
    Can anybody tell me how to get value as String form java JTable row?

    I found solution:
            table.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent evt) {
                    if (evt.getClickCount() == 2){
                        int col = table.getSelectedColumn();
                        int row = table.getSelectedRow();
                        String tableUrl = ((String)table.getModel().getValueAt(row, col));
                        ur.openUrl(tableUrl);
            });

  • Dinamic JTable Rows Height

    Hi!
    Is it possible to change dinamically and automatically JTable row height depending on a cell content to display it correctlly wraping the text?
    In some of my cells content is too long and It's difficult to display it properly ...
    Thanks!

    This link might help:
    http://www.javaspecialists.co.za/archive/GUI.html

  • How to get event from selected JTable row

    Whenever a JTable row is selected, i want to get an event to get the row index of the selected row and read the row data. Which listenere do i have to implement and where is the correspoinding addXXXListener() method in JTable?

    here ya go...
    <table>.getSelectionModel().addListSelectionListener(...);Josh Castagno
    http://www.jdc-software.com

  • Making JTable rows not editable

    i need to make a jtables rows and columns to not be editable, but i also need it to be able to be selectable. i know one way to do it is to extend defaulttablemodel and overwrite the iscelleditable method, but the problem is that i'm already extending jframe. is there any other way to do this keeping jframe extended, because i need it to be extended?
    thanks for the help

    JTable table = new JTable(..){
      public boolean isCellEditable(int row, int column){
        return false;
    };

  • A Listener For JTable Row Selection Changed?

    Never mind... Thought of a couple other things after I posted and found ListSelectionListener. This looks like it fulfills my requirement nicely. - cimmerian76
    >>>
    TableModelListener isn't what I am looking for here. Basically, I'm looking for something that behaves in a way that is analogous to
    TreeSelectionListener's valueChanged(...). Perhaps I'm looking in the wrong places, but the only things I've found were RowSet listener (not even close)
    and TableModelListener (not exactly what I'm looking for - I'm not concerned about data in the table changing).
    The tool I'm writing displays additional information about the object in the row selected in an adjacent panel.
    This display should change every time a user selects a different row.
    I can mimic the behavior I want using a mouse listener on the table, so this isn't an emergency.
    It's more about curiosity. If I can find something that produces this functionality directly, I would prefer to use that.
    <<<
    Message was edited by:
    cimmerian76

    Hi,
    you can use this to handle selection events for the table:
    yourTable.getSelectionModel().addListSelectionListener(... );
    Now e.g. the class containing your main can implement interface ListSelectionListener.

  • Double click on a JTable row.

    I got and run a sample about double click on a JTable and it works fine. This sample defines a TableModel as shown at the end this note.
    On the other hand, I have an application in which I have defined a JTable
    using the DefaultTableModel as follows :
    DefaultTableModel dtm = new DefaultTableModel(data, names);
    JTable table  = new JTable(dtm);  where data and names are String arrays.
    Of course the mouse listener stuffs have been also specified.
    table.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e){
          if (e.getClickCount() == 2){
             System.out.println(" double click" );
         } );Because the difference with the sample was the table model,
    I changed it with the DefaultTableModel class. At this point, the Double click does not work anymore.
    So I gues it should be an option which prevents double click to work.
    I thought of using mousePress() instead of mouseClick(), but it's very dangerous (I tried). . If by error the user clicks twice (instead of only once) the mousePress method is invoked twice for the same entry
    My question is now simple, may I use double click on a JTable with the default table model. If so, what I have to do ?
    Thanks a lot
    Gege
    TableModel dataModel = new AbstractTableModel() {
         public int getColumnCount() { return names.length; }
         public int getRowCount() { return data.length;}
         public Object getValueAt(int row, int col) {return data[row][col];}
         public String getColumnName(int column) {return names[column];}
         public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
         public void setValueAt(Object aValue, int row, int column) {
           data[row][column] = aValue;
         };

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ClickIt extends MouseAdapter
        public void mousePressed(MouseEvent e)
            JTable table = (JTable)e.getSource();
            Point p = e.getPoint();
            if(e.getClickCount() == 2)
                System.out.println("table.isEditing = " + table.isEditing());
            int row = table.rowAtPoint(p);
            int col = table.columnAtPoint(p);
            String value = (String)table.getValueAt(row,col);
            System.out.println(value);
        private JTable getLeftTable()
            final String[] names = { "column 1", "column 2", "column 3", "column 4" };
            final Object[][] data = getData("left");
            TableModel dataModel = new AbstractTableModel() {
                public int getColumnCount() { return names.length; }
                public int getRowCount() { return data.length;}
                public Object getValueAt(int row, int col) {return data[row][col];}
                public String getColumnName(int column) {return names[column];}
                public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
                public void setValueAt(Object aValue, int row, int column) {
                    data[row][column] = aValue;
            JTable table = new JTable(dataModel);
            return configure(table);
        private JTable getRightTable()
            String[] colNames = { "column 1", "column 2", "column 3", "column 4" };
            JTable table = new JTable(new DefaultTableModel(getData("right"), colNames));
            return configure(table);
        private Object[][] getData(String s)
            int rows = 4, cols = 4;
            Object[][] data = new Object[rows][cols];
            for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++)
                    data[row][col] = s + " " + (row*cols + col + 1);
            return data;
        private JTable configure(JTable table)
            table.setColumnSelectionAllowed(true);
            table.setCellSelectionEnabled(true);
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.addMouseListener(this);
            return table;
        private JPanel getContent()
            JPanel panel = new JPanel(new GridLayout(1,0,0,5));
            panel.add(new JScrollPane(getLeftTable()));
            panel.add(new JScrollPane(getRightTable()));
            return panel;
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(new ClickIt().getContent());
            f.pack();
            f.setVisible(true);
    }

  • Making a jtable row noneditable based on a value in a certain cell.

    I have a jTable (based on a database table) and one of the columns is OWNER. Is there a way to make an entire row noneditable based on the value in the OWNER column of the currently selected row?
    Here is the listener code that I have on the jTable. I want to be able to make the entire row noneditable if the value (of the currently selected row) of the OWNER column is "SYSTEM". If it is anything other than "SYSTEM" then the user would be able to change the values on the row.
    I can't override the isCellEditable method, because I only want the rows with the value of "SYSTEM" in the OWNER column to be noneditable.
    jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = jTable2.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
    if (lsm.isSelectionEmpty()) {
    //no rows are selected
    } else {
    int selectedRow = lsm.getMinSelectionIndex();
    if (jTable2.getValueAt(selectedRow, 1).equals("SYSTEM"))
    System.out.println("Selected Row: " + selectedRow);
    System.out.println("Owner Value: " + jTable2.getValueAt(selectedRow, 1));
    //Make all cells in this row non-updateable???
    //Need code to make the currently selected row noneditable
    disableRetailerAddToList();
    } else
    enableRetailerAddToList();
    Any direction for this problem would be greatly appreciated.

    I've resolved it with some help by using the following:
    NOT ([<plCall_Back_Required_ITAG>]=LookupValue("OCC_CUST_LOV_SR_3", "Yes") AND [<stCall_Back_Number_ITAG>] IS NULL)

  • How to bind JTable row height to the maximum height of a the columns

    Suppose i have a JTable. data setup is done. Thing is whenever data font size increases table row height should change. How?

    Add a PropertyChangeListener to the table to listen for a font change event. Then use the setRowHeight() method of the table.

  • Multiple Buttons in JTable Headers:  Listening for Mouse Clicks

    I am writing a table which has table headers that contain multiple buttons. For the header cells, I am using a custom cell renderer which extends JPanel. A JLabel and JButtons are added to the JPanel.
    Unfortunately, the buttons do not do anything. (Clicking in the area of a button doesn't appear to have any effect; the button doesn't appear to be pressed.)
    Looking through the archives, I read a suggestion that the way to solve this problem is to listen for mouse clicks on the table header and then determine whether the mouse clicks fall in the area of the button. However, I cannot seem to get coordinates for the button that match the coordinates I see for mouse clicks.
    The coordinates for mouse clicks seem to be relative to the top left corner of the table header (which would match the specification for mouse listeners). I haven't figured out how to get corresponding coordinates for the button. The coordinates returned by JButton.getBounds() seem to be relative to the top left corner of the panel. I hoped I could just add those to the coordinates for the panel to get coordinates relative to the table header, but JPanel.getBounds() gives me negative numbers for x and y (?!?). JPanel.getLocation() gives me the same negative numbers. When I tried JPanel.getLocationOnScreen(), I get an IllegalComponentStateException:
    Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    Can someone tell me how to get coordinates for the button on the JTableHeader? Or is there an easier way to do this (some way to make the buttons actually work so I can just use an ActionListener like I normally would)?
    Here is relevant code:
    public class MyTableHeaderRenderer extends JPanel implements TableCellRenderer {
    public MyTableHeaderRenderer() {
      setOpaque(true);
      // ... set colors...
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setLayout(new FlowLayout(FlowLayout.LEADING));
      setAlignmentY(Component.CENTER_ALIGNMENT);
    public Component getTableCellRendererComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     boolean hasFocus,
                                                     int row,
                                                     int column){
      if (table != null){
        removeAll();
        String valueString = (value == null) ? "" : value.toString();
        add(new JLabel(valueString));
        Insets zeroInsets = new Insets(0, 0, 0, 0);
        final JButton sortAscendingButton = new JButton("1");
        sortAscendingButton.setMargin(zeroInsets);
        table.getTableHeader().addMouseListener(new MouseAdapter(){
          public void mouseClicked(MouseEvent e) {
            Rectangle buttonBounds = sortAscendingButton.getBounds();
            Rectangle panelBounds = MyTableHeaderRenderer.this.getBounds();
            System.out.println(Revising based on (" + panelBounds.x + ", "
                               + panelBounds.y + ")...");
            buttonBounds.translate(panelBounds.x, panelBounds.y);
            if (buttonBounds.contains(e.getX(), e.getY())){  // The click was on this button.
              System.out.println("Calling sortAscending...");
              ((MyTableModel) table.getModel()).sortAscending(column);
            else{
              System.out.println("(" + e.getX() + ", " + e.getY() + ") is not within "
                                 + sortAscendingButton.getBounds() + " [ revised to " + buttonBounds + "].");
        sortAscendingButton.setEnabled(true);
        add(sortAscendingButton);
        JButton button2 = new JButton("2");
        button2.setMargin(zeroInsets);
        add(button2);
        //etc
      return this;
    }

    I found a solution to this: It's the getHeaderRect method in class JTableHeader.
    table.getTableHeader().addMouseListener(new MouseAdapter(){
      public void mouseClicked(MouseEvent e) {
        Rectangle panelBounds = table.getTableHeader().getHeaderRect(column);
        Rectangle buttonBounds = sortAscendingButton.getBounds();
        buttonBounds.translate(panelBounds.x, panelBounds.y);
        if (buttonBounds.contains(e.getX(), e.getY()) && processedEvents.add(e)){  // The click was on this button.
          ((MyTableModel) table.getModel()).sortAscending(column);
    });

Maybe you are looking for

  • Videos now Musik, help me

    Hi There When I last connected my Ipod Video (30GB) to my computer and opend the iTunes, it automatically started a "Optimization for the songs, so they play faster" or something like that. After that ALL my Videos on the iPod were treated like music

  • Tag Library Compile Warning

    Why does the weblogic jsp compiler wine about this standard tag library           descriptor DTD?           <?xml version="1.0" encoding="ISO-8859-1" ?>           <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library           1.1//

  • Sound blaster 5.1 Live! 16bit Windows vi

    Where do i find sound blaster 5. Li've! 6bit drivers for windows vista? i installed its driver from cd but that is only for win XP and i only hear the front speaker left and right ... what should i do ?Message Edited by quard on 02--20072:9 PM

  • CLDC 1.0 to 1.1?

    Hey everyone, I have CLDC 1.0 on my mobile phone, and i need to be able to get CLDC 1.1 due to sqrt and 3D programming...but i have not figured out how to do that...so does anyone know how to get CLDC 1.1 on your phone to update your phone's system T

  • PhpMyAdmin - Guide books?

    Hi, I wonder if someone could suggest a good guide book for using phpMyAdmin, - including setting up tables, relational database management, importing/exporting data and SQL queries. I'm thinking of purchasing a copy of 'Mastering phpMyAdmin 2.11 for