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;
====================================================================

Similar Messages

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

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

  • 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 can i set action on UITaBar and get event from that

    Hi All,
    I m doing one apps in which i have to add three UITabBarItem and this is UITabBarSystemItem.
    Now i cannot understand that how can i set action and get event from the?
    And how can i set various views on three tab bar item.
    I have to use UITabBar means i have to use UINavigationController+UITabBar
    My code id
    tabBar =[[UITabBar alloc] initWithFrame:CGRectMake(0,370,320,50)];
    tabBar.backgroundColor =[UIColor blackColor];
    UITabBarItem *search =[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemSearch tag:0];
    UITabBarItem *recents =[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemRecents tag:1];
    UITabBarItem *favorites =[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorit es tag:2];
    tabBar.items =[[NSArray arrayWithObjects:search,recents,favorites, nil] retain];
    tabBar.selectedItem = search;
    [myView addSubview:tabBar];
    [tabBar release];
    I add a action:
    UITabBarItem *search =[[UITabBarItem alloc] InitWithTabBarSystemItem:UITabBarSystemItemSearch tag:0 action:@selector(select:)];
    So it error: Warning -no'InitWithTabBarSystemItem:tag:action:' method fount
    So any can help me regarding it?

    Thanks RickMaddy very much.
    I read and do with sample at the View Controller Programming Guide . But when run it only view TabBar with title but haven't got any TabBarItem on it. I searched a few example about TabBar and i did, but i want do a form with a button then press on button it view a form with 2 TabBarItem on TabBar and press each TabBarItem will show correlative form page 1, page 2.
    UITabBarController *tabBarControl = [[[UITabBarController alloc] initWithNibName:nil bundle:nil] autorelease];
    tabBarControl.title = @"Tab bar";
    ViewControl1 *view1 = [[[ViewControl1 alloc] initWithNibName:@"ViewControl1" bundle:nil] autorelease];
    ViewControl1 *view2 = [[[ViewControl1 alloc] initWithNibName:@"ViewControl2" bundle:nil] autorelease];
    tabBarControl.viewControllers = [NSArray arrayWithObjects:view1,view2,nil];
    [self.navigationController pushViewController:tabBarControl animated:YES];

  • 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" )));

  • Having trouble getting "Set action to take when logon hours expire" to work - Windows Server 2012

    I have a Windows Server 2012 server that allows remote desktop users (sessions are hosted on the server itself). I'm trying to enforce logon hours for these remote desktop users.
    I have specified logon hours for a user and confirmed that they work--they aren't allowed to logon when logon hours are disabled. However, they are allowed to continue a session past their logon hours limit if they are already signed in (which is fine, this
    is the default behavior).
    However, when I try to use the `Set action to take when logon hours expire` option (`User Configuration/Administrative Templates/Windows Components/Windows Logon Options/Set action to take when logon hours expire`), and set the behavior to "Logoff",
    nothing happens--the user can continue their session happily. I've tried applying this policy both for the user's group and for the local computer. I've run `gpresult` for the user and confirmed that the policy is apparently in place.
    I also naively tried the "Force logoff when logon hours expire" option, but that apparently doesn't apply to interactive logins (confusing!).
    Am I misapplying this setting, or do I need to take some other steps to get it to work? I'd be grateful for any input. Thanks!

    Hi,
    Sorry for the late response.
    We can log off and log on again to see whether the setting gets applied.
    According to
    Policy Settings that require a reboot or logon section in the following article, this setting needs a logon.
    Deploying Group Policy Using Windows Vista
    http://technet.microsoft.com/en-us/library/cc766208(v=WS.10).aspx
    Best regards,
    Frank Shen

  • Setting Actions with multimedia tool

    Anyone know where the documentation is on the video file types you can and can not set actions with when
    embedding and when streaming from a url in Pro 9 or Pro Extended 9?
    Thanks,
    sentient.usa

    Yes, putting a script that submits the form in the WillPrint action is sufficient - got it working after I found the JS for Acrobat API Reference. I haven't actually used Post before and I think I misread something when doing some research that gave me the wrong idea.
    Thanks.

  • Set the colum in JTable to NotEditable

    How can I set the colum in JTable so it's not editable. The table model is in the same class with the JTable.

        aTable.setModel(new DefaultTableModel(columnHeader, 0) {
          public boolean isCellEditable(int row, int col) {
            return (col != yourNonEditableColumn);
        });

  • 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 set Action of commandButton from javabean?

    Hi,
    How can I to set Action of commandButton from javabean with JSF 1.1?
    Thanks

    Try this:
    import javax.faces.component.html.HtmlCommandButton;
    Application application = FacesContext.getCurrentInstance().getApplication();
    HtmlCommandButton button = (HtmlCommandButton) application.createComponent(HtmlCommandButton.COMPONENT_TYPE);
    MethodBinding mb = application.createMethodBinding("#{mybean.action}", null);
    button.setAction(mb);

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

Maybe you are looking for