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

Similar Messages

  • Clickable buttons in jtable

    Hi All,
    I'm trying to add a JButton to a JTable. There are a few scripts out there that show how to transfer a mouse event from jtable to a button that is placed in its cell. I've added to it a response to mousemoved method to highlight a button when the mouse is over the cell with the button. Unfortunately I have not seen a script that shows the "standard" response of the button as it works on standard jpanels (including a display of the button being pressed down). I wonder are those scripts out there and I missed smthing.
    I'm also wondering are there standard [free!!] converters from smthing like xml into jtables. may be not with all the functionality of html tables but with some of it. This would seem as a natural thing to write.
    Thanx in advance

    That's does not look inspiring so far. Let me rephrase the question. Is it true that I have to implement a custom jbutton that paints its pressed state to make the jbutton pressable in a jtable cell. Or I miss smthing in a standard implementation of jtable that would allow to do it w/o it.

  • 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

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

  • Making clickable buttons to open xml images in gallery

    I want to do an xml grid image gallery similar to http://www.republicofcode.com/tutorials/flash/as3gridgallery/
    However, instead of using thumbnails, I already have images on my site that I want to make clickable buttons to open the images in the gallery...how would I script these buttons?
    [link removed by moderator]

    If you want it to be similar to the one you link then use the images in the grid like in the one you linked.

  • 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

  • On firefox clickable buttons are not clickable for me eg the + to open new tab ,the sign in . register and other applications buttons on this page wont click yet the 2 blue change buttons are fine

    Question
    on firefox clickable buttons are not clickable for me eg the + to open new tab ,the sign in . register and other applications buttons on this page wont click yet the 2 blue change buttons are fine

    Top of Firefox window non-responsive, toolbars non responsive -- also see [http://kb.mozillazine.org/Problematic_extensions Problematic extensions]
    *caused by Yahoo Toolbar -- https://support.mozilla.com/questions/890908
    *caused by Babylon Toolbar -- https://support.mozilla.com/questions/890670

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

  • Can I make a cell in iWork 08 a clickable button?

    Is there a way to assign a cell to be a clickable button which would take you to another spreadsheet?

    The response is a simple : no.
    Yvan KOENIG (from FRANCE dimanche 12 octobre 2008 12:00:55)

  • Clickable button in Keynote?

    Hi, I'm wondering if I can create a clickable button in keynote that would then trigger a build-in effect such as dissolve. Is such a thing possible?

    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

  • Payment File generation

    Hi All, I am generating .txt file for payment details. The file will be directly uploaded on BNP web portal. This is to avoid cheque printing through SAP. The format of the file is as follows. PCC             123464                            0900910

  • Why does Keynote 09 started to crash on heavy presentations?

    I have always worked with big, heavy presentations, that includes text, images and videos, but a few weeks ago Keynote 09 is crashing when I try to opne it!!! I have my entire life in those presentation and can't even think about losing it! I have tr

  • Can't Restore Exchange 2010 Mailbox DB from HP Data Protector backup

    I'm trying to implement Exchange 2010, but I won't feel comfortable moving many users to it until I've successfully restored a mail database from tape backup.  So far, this hasn't worked out so well.  I'm using HP Data Protector for my backup solutio

  • Why on earth is there no free print ability?

    What gives?  If the only solution from the company is to buy someone ELSES print app ... seems to me they left out something.  Sort of like leaving off the mirrors in your car.  Why is there no real outrage here?  Doesn't anyone else WANT to use this

  • 10.6.7 and 2011-002 built in or seperate install?

    Hey guys, This should be a simple question, but is the 2011-002 security patch or the 001 included in the 10.6.7 update? Or is it a seperate install? I would  think its a seperate install but when i run apple update (i am running 10.6.7 server) it do