Buttons to JTable header...

I'm trying set the column headers in a JTable to be JButtons that can be selected to sort items in the table by that column. I've got the buttons in place with a call to setHeaderRenderer(TableCellRenderer) and calling my own renderer. But the button does nothing (i.e. won't even "click").
Ideas?

Check this link
http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html

Similar Messages

  • 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

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

  • Setting action listner to JTable header

    Hi,
    Does any one have any idea on how to set the action listner to column header? If you know the solution, please pass on.
    Thanks,
    Jeson.

    Hi friends,
    We found a way to add button to table header.Please find the below mentioned code. However, I am unable to set the tooltip. If you have any idea...still 5 dollars are available..
    Regards,
    Je.
    =======================================================================
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import javax.swing.ImageIcon;
    import javax.swing.BorderFactory;
    import javax.swing.SwingConstants;
    public class SimpleTableDemo extends JFrame {
    private boolean DEBUG = true;
    public SimpleTableDemo() {
    super("SimpleTableDemo");
    Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    String str1 = new String("First Name");
    String str2 = new String("Last Name");
    String str3 = new String("");
    String str4 = new String("# of Years");
    String str5 = new String("Vegetarian");
    Object[] columnNames = {str1, str2, str3, str4, str5};
    final JTable table = new JTable(data, columnNames);
    table.getColumn("").setHeaderRenderer(new IconColumnHeader("Month"));
    table.setPreferredScrollableViewportSize(new Dimension(500,130));
    if (DEBUG) {
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    printDebugData(table);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    private void printDebugData(JTable table) {
    int numRows = table.getRowCount();
    int numCols = table.getColumnCount();
    javax.swing.table.TableModel model = table.getModel();
    System.out.println("Value of data: ");
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + model.getValueAt(i, j));
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    SimpleTableDemo frame = new SimpleTableDemo();
    frame.pack();
    frame.setVisible(true);
    class IconColumnHeader extends JPanel implements TableCellRenderer {
    private JLabel label = null;
    private JButton jbn = null;
    /** Creates a new instance of IconColumnHeader
    This adds the specified Icon to the column header*/
    public IconColumnHeader(String nam) {
    setBorder(BorderFactory.createRaisedBevelBorder());
    jbn = new JButton(nam);
    ImageIcon dissicon = new ImageIcon("C:/images/auto1.gif");
    jbn.setIcon(dissicon);
    jbn.setName("Month");
    jbn.setToolTipText("Month");
    add(jbn);// = new JButton(nam));
    /** Returns the table cell renderer component
    * @param jTable main table
    * @param obj value
    * @param param boolean value
    * @param param3 boolean value
    * @param param4 table row
    * @param param5 table column
    * @return cell rendere component
    public Component getTableCellRendererComponent(JTable jTable, Object obj, boolean param, boolean param3, int param4, int param5) {
    /*label.setText(obj.toString());
    label.setHorizontalTextPosition(SwingConstants.LEFT);
    label.setVerticalTextPosition(SwingConstants.CENTER);
    return this;*/
    jbn.setText(obj.toString());
    jbn.setHorizontalTextPosition(SwingConstants.LEFT);
    jbn.setVerticalTextPosition(SwingConstants.CENTER);
    return this;
    ====================================================================

  • How can I stop iTunes from launching when I hit the button on my head phones

    On my MBP I have some head phones that have an inline mic with call answer button. The button on the head phones is fairly sensitive and I tend to bump it on accident often. When I hit the button iTunes is launched or if I have it open it starts music.
    Is there anyway to stop this from happening? This is driving me crazy!

    This problem has been an issue for a number of months and has led to frustration and public humiliation on countless occasions.
    When disconnecting from my Bose Soundlink at home (playing nothing) in order to taking my laptop on the run I open my laptop to find that the entire contents of my iTunes playlist is being belted in public. The subway, the library, my classroom is not the time or place for my laptop to make the decision to begin playing my music without permission. When at home and my Soundlink goes on standby I have nearly had a heart attack when my laptop spontaneously begins blaring my music when I wasn't even touching the thing.
    I love my Soundlink and I love my Mac but together the devices are causing no end of aggravation with no fix in sight. With each OS update I hope the problem is addressed but to no avail, it is getting tiresome that such a flaw isn't being fixed in a timely manner.

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

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

  • Assigning a child button to Accordion header

    I have an Accordion control with several panels. Each header
    has an icon and a title. I need to add a child button to the
    Accordion header (which is a Button itself and not a container, but
    it should be OK). I want to place it on te right side of the
    header. I create a 20 x 20 button and add it to the Accordion
    header, as a child. I want to place it on the right corner of the
    Accordion header, but I am unable to get accurate size measurements
    of the header. What I thought would work (using the Accordion
    derived custom class) would be ....
    for(var i:int=0; i<numChildren; i++)
    var header:mx.controls.Button = getHeaderAt(i);
    header.addChild(minusButton);
    super.measure();
    minusButton.x = header.measuredWidth - 20;
    but the measureed width always comes up as zero, as opposed
    to the actual width of the header? Any ideas what I am doing
    wrong?

    Set the button's "In" parameter to the same MIDI message your controller is sending.
    Now when the button receives a MIDI input with the matching message, it will trigger.
    You'll obviously need an environment cable path so that incoming MIDI can reach the button, by whatever means is appropriate.

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

  • Where are the home, refresh and X buttons in the header

    When I open my home page on the desktop, there are buttons that let me select home, refresh or X a download. I cannot find these buttons on the header or in the add-ons, etc.

    The '''''Home''''' button was relocated to the right of the Location/URL bar in a prior version. You can drag it to the position you want or get it from the Customize Toolbar window by looking at the following instructions.
    *Click this link --> https://support.mozilla.org/en-US/kb/how-do-i-customize-toolbars
    In Firefox 4 and newer versions, the '''''Go, Stop and Reload''''' buttons are combined in one button at the right end of the URL or Address bar. The button changes depending on the activity:
    *green Go arrow when typing in the address bar
    *red Stop ("X") button while page is loading
    *gray Reload (circular arrow) when page is finished loading.
    Separate buttons are possible:
    #Open Customize Toolbar window by clicking Firefox button > Option > Toolbar Layout '''''OR''''' clicking View > Toolbars > Customize if using the Menu Bar '''''OR''''' right-click in an empty space on a toolbar and choose Customize
    #<u>While the Customize window is open</u>, Stop and Reload buttons will show separated between the address bar and the search bar
    #<u>While the Customize window is open</u>, drag the buttons anywhere on the Navigation toolbar
    #*order Reload-Stop will combine into one button
    #*order Stop-Reload will remain separate buttons
    #*or drag a "Separator" from the Customize window between Reload-Stop and they will remain separate
    #click Done at bottom right of Customize window to finish
    #See: https://support.mozilla.org/en-US/kb/how-do-i-customize-toolbars
    '''If this reply solves your problem, please click "Solved It" next to this reply when <u>signed-in</u> to the forum.'''
    Not related to your question, but...
    You may need to update some plug-ins. Check your plug-ins and update as necessary:
    *Plug-in check --> http://www.mozilla.org/en-US/plugincheck/
    *'''''Adobe Shockwave for Director Netscape plug-in''''': [https://support.mozilla.org/en-US/kb/Using%20the%20Shockwave%20plugin%20with%20Firefox#w_installing-shockwave Installing ('''''or Updating''''') the Shockwave plugin with Firefox]
    *'''''Adobe PDF Plug-In For Firefox and Netscape''''': [https://support.mozilla.org/en-US/kb/Using%20the%20Adobe%20Reader%20plugin%20with%20Firefox#w_installing-and-updating-adobe-reader Installing/Updating Adobe Reader in Firefox]
    *Shockwave Flash (Adobe Flash or Flash): [https://support.mozilla.org/en-US/kb/Managing%20the%20Flash%20plugin#w_updating-flash Updating Flash in Firefox]
    *Next Generation Java Plug-in for Mozilla browsers: [https://support.mozilla.org/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox#w_installing-or-updating-java Installing or Updating Java in Firefox]

Maybe you are looking for

  • Problem with display of content in Windows XP - help!

    Hi, I recently created a Windows XP partition on my Mac using Boot Camp and am having a problem. Everything that I open in Windows is way too big and in some cases, it means that I can't access the whole page or scroll up or down. Even when I open Gm

  • Error 554-5.6.0 Corrupt message content... when sending emails to other users on same exchange server

    Hello I have a very strange problem at a customer from our company. The problem happens to only one user on the Exchange 2010 organization (SP3, no additional patches installed, Server is 2008 r2). When this specific user sends an email to one or mor

  • "Ghost files" when exporting to CD for PC or DVD player

    I'm exporting my photos from iPhoto and then burn them to a CD (for friends that are using PC or want to watch them on their DVD player) ghost files appears like duplicates. So if I burn 100 images it will be 200 when opening on a PC or on a DVD play

  • A very strange problem in netbeans

    i debug a project in netbeans,a a very strange problem happens. a member variable was different between wtk20 and wtk22.and the variable was changed many places so it's hard to trace! but there hasn't the problem when i debug project in jbuilderx!

  • FYI TDMS open and read on empty file gives no error's out

    I found that if you 'open' an empty (0 byte) file using TDMS open, you will not get any error messages when you open it, nor when you call functions such as "Get properties" or "List content", also no error when you close the TDMS file. If the file i