Buttons in JTables?

Hello,
Does anybody know how to put buttons and progress bars in JTable cells? is it possible? is there another component which I should use?
Many thanks
Alex

try to look on this
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender

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

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

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

  • Using the right mouse button with JTables

    Hi Folks,
    Can someone describe how to allow the right mouse button to select rows in a JTable? Or can someone tell me how to access the code which is activated when the RMB is clicked on a JTable so I can copy it.
    Thanks.

    Can you attach a screenshot?
    *http://en.wikipedia.org/wiki/Screenshot
    Use a compressed image type like PNG or JPG to save the screenshot and make sure that you do not exceed the maximum file size (1 MB).
    Make sure that you do not run Firefox in full screen mode (press F11 or Fn + F11 to toggle; Mac: command+Shift+F).<br />
    If you are in full screen mode then hover the mouse to the top to make the Navigation Toolbar and Tab bar appear.<br />
    You can click the Maximize button at the top right to leave full screen mode or right click empty space on a toolbar and use "Exit Full Screen Mode" or press F11.<br />

  • 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

  • Buttons in JTable?

    Hi,
    I've got a problem with using Buttons in a JTable. Everything works well except that if I select the tablefield with the Button the button is displayed pressed though the listener doesn't receive any click.
    How can I change this?
    Thanks,
    Mior

    You should write your own class extends JButton implements TableCellEditor or you can add MouseListener to JTable and
    get cell clicked by JTable.getComponentAt(Point) or
    JTable.getComponentAt(int x, int y)

  • OnMouseDown buttons within JTable Cells?

    I have written an app that uses a custom renderer to enable me to put an image in a cell and attach a custom editor to that image so that when it is clicked it pops up a JPanel. Trouble is, once the user clicks the button and the JPanel appears the image that was within the cell disappears and the cell is empty. How do I switch the image once clicked and display it in the clicked cell.
    Thanks

    When you click on the cell the editor is invoked and will display the data based on the editor, not the renderer.
    So, I'm guessing that in addition to displaying the popup, your editor must be responsible for displaying the original image.

  • Option Button in JTable?

    Hi, I read the Swing Tutorial for the JTable. Inside the tutorial, it says that Boolean is rendered with checkbox, however, can it be rendered as a RadioButton instead?
    Thanks

    Yes you can, check this out:
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html

  • Navigating using Tab button in JTable

    Hi All,
    I need to navigate inside a Jtable. I have hidden columns and some othercolumns which i need the tab to skip. Can you please suggest how to take care of that.
    Thanks in anticipation,

    I have hidden columns Then remove them from the table view by removing the column from the TableColumnModel
    and some othercolumns which i need the tab to skipThis posting shows how to create a custom Tab action for the table:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • Add button to a JTable

    i added a button a Jtable.but am not able to dispatch the mouse click event to the button. I am not seeing any change in the button when clicked....its not getting the focus. the code is as below:
    class TableButtonMouseListener implements MouseListener {
    private JTable table;
    private void forwardEventToButton(MouseEvent e) {
    TableColumnModel columnModel = table.getColumnModel();
    int column = columnModel.getColumnIndexAtX(e.getX());
    System.out.println("column "+column);
    int row = e.getY() / table.getRowHeight();
    System.out.println("row "+row);
    Object value;
    JButton button;
    MouseEvent buttonEvent;
    if(row >= table.getRowCount() || row < 0 ||
    column >= table.getColumnCount() || column < 0)
    return;
    value = table.getValueAt(row, column);
    if(!(value instanceof JButton))
    return;
    button = (JButton)value;
    buttonEvent =(MouseEvent)SwingUtilities.convertMouseEvent(table, e, button);
    button.dispatchEvent(buttonEvent);
    // This is necessary so that when a button is pressed and released
    // it gets rendered properly. Otherwise, the button may still appear
    // pressed down when it has been released.
    table.repaint();
    public TableButtonMouseListener(JTable table) {
    this.table = table;
    public void mouseClicked(MouseEvent e) {
    forwardEventToButton(e);
    public void mouseEntered(MouseEvent e) {
    //forwardEventToButton(e);
    public void mouseExited(MouseEvent e) {
    //forwardEventToButton(e);
    public void mousePressed(MouseEvent e) {
    forwardEventToButton(e);
    public void mouseReleased(MouseEvent e) {
    forwardEventToButton(e);
    pls help ....

    -> I am a first time user.that is y....
    What does that have to do with anything. As a first time user you should take the time to learn how to use the forum. In any forum, not just this one, it is common sense to search first before asking questions.
    -> but can u pls tell me y the button is nt getting the event
    Did you read the JTable API? It has a link to the Swing tutorial that explains how tables work. You need to understand the section on renderers. In general a renderer is a drawing of the button, it is not a real button so it doesn't receive events.
    The problem has nothing to do with the TableModel.

  • How to associate a button with the selection/unselection of a JTable?

    hi,
    how to associate a button with JTable in this manna? i want to disable a button once there is no selection in the JTable, and enable the button when there is a selection. to associate the selection it is easy: just make an eventAction for the button on the click in the JTable and check whether there is a selection. but how to do this with the unselection? hope anyone can give me any hint. thanx!

    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame {
        String[] head = {"One","Two","Three"};
        String[][] data = {{"1-1","1-2","1-3"},{"2-1","2-2","2-3"},{"3-1","3-2","3-3"}};
        JTable jt = new JTable(data,head);
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JScrollPane(jt));
         jt.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
             public void valueChanged(ListSelectionEvent lse) {
              if (lse.getValueIsAdjusting()) return;
              if (jt.getSelectionModel().isSelectionEmpty()) {
                  System.out.println("Nothing Selected");
              } else {
                  System.out.println("Something Selected");
         setSize(500,500);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • How to hightlight  the new  inserted data in the last low of JTable?

    Could somebody help me?
    i am doing the e-restaurant application system .
    When press the food button, the JTable will list out the order details.
    When the order is long, the scroll pane will show up.
    My problem is[ b] how to hightlight the new inserted data in the last low of JTable when the food button is press every time?The scroll pane will automatically scroll down the to the new insertted data.
    In the List, i get the effect like this command but in the JTable how?
    list.ensureIndexIsVisible(orderDetails.getSize()-1);
    thank in advance.
    Below is the snapshot of my coding:
    DefaultTableModel model=new DefaultTableModel(cells,columnNames);
    OrderModel sorter=new OrderModel(model);
    JTable table=new JTable(sorter);
    JScrollPane scrollPane=new JScrollPane();
    scrollPane.add(table);
    Object[] object={foodName, "1",price};
    model.addRow(object);
    sorter.fireTableDataChanged();
    sorter.fireTableStructureChanged();

    The right place to ask this one is "Swing Forum.
    http://forum.java.sun.com/forum.jspa?forumID=57

  • Dragging multiple rows in JTable - MUST use CTRL, or not?

    Hello all!
    I'm writing an app that needs to be able to drag multiple rows from a JTable. I have seen that I can do this by selecting multiple rows with the LEFT mouse button, while holding down the CTRL key, and then dragging (again, with the left mouse button).
    The problem is, since I'm holding down the CTRL key, this comes across as a DnDConstants.ACTION_COPY.
    I find that if I do multiple selection, then drag with the RIGHT mouse button (no CTRL key held down), then I get a DnDConstants.ACTION_MOVE, as I want.
    My question: Is there any simple way to enable dragging multiple JTable rows, using the LEFT mouse button, but WITHOUT holding down the CTRL key?
    I have been tasked with "making it act like Windows", which doesn't undo a multiple-selection when one clicks on an existing selected row until one lets go of the left mouse button; whereas JTables appear to change the selection to the clicked-upon row immediately, even if it is part of the existing selection.
    Any ways around this anyone knows, short of modifying the JTable or BasicTableUI itself?
    - Tim

    By the way, I just tested this assumption of mine, and found I was wrong if you're using default JTable drag and drop.
    However, I'm using my own implementation. I notice in a simple program without any drag and drop, I get the behavior I mentioned above, so I'm guessing this IS default JTable behavior, which is then modified by the built-in drag and drop support.
    So the trick will be, how to do what built-in drag and drop is doing, without using built-in drag and drop. :-)
    - Tim

  • JTable Focus Lost

    Hi All,
    I have a JTable with 6 columns and the last column has a button attached called EXPAND.
    Also I have another navigation buttons called Next, Back, Save and Refresh.
    Whenever I make changes to the cell and then click on the expand button of the 6th column, it saves my changes.
    but when i make changes to the cell and then click some where else (other than on the JTable) ...here for example on the Refresh button ...and then click on the expand button on JTable, I could not save my changes ...
    i.e. it is not invoking my focusLost ...Is there any work around for this problem ...
    I am posting my focus Lost code :
    public void focusLost(FocusEvent e) {
    if (jTable.getSelectedColumn() >= 0) {
    if (jTable.getColumnName(jTable.getSelectedColumn()).equalsIgnoreCase("Expand")) {
    saveData();
    Many Thanks
    Mahesh

    try tableChange Listener, something like this
    class TableListener
           implements TableModelListener {
          private JTable table;
          public TableListener(JTable table) {
          this.table = table;
          public void tableChanged(TableModelEvent e) {
             int editRow = table.getEditingRow();
             String value = table.getValueAt(editRow, 1).toString();
             if (e.getType() == TableModelEvent.UPDATE) {
                save();
    [/code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • Dbms_xmldom package results in ORA-31020

    Hi, I have the following procedure which compiles correct: CREATE OR REPLACE procedure vbk_selproc_doc is queryctx dbms_xmlquery.ctxtype; result varchar2(30000); header varchar2(1000); footer varchar2(1000); body varchar2(20000); line VARCHAR2(2000);

  • Firefox will not open Adobe PDF files on my mini Mac (I have reader x and the latest Quicktime versions)

    When I try to download a pdf file sometimes an error message appears and states can't down load file, Quicktime may need an extension. Other times the page just stays blank - nothing happens. This happens very frequently. I can open some pdf files in

  • How to create EncryptDocument Process ?

    I'm new to Adobe LiveCycle ES, and I'm now stuck with all tutorials dealing with pdf encryption because most of them are using the EncryptDocument process. But I didn't manage to find where this process creation with Workbench ES is explained. If som

  • Not picking up DHCP info from Windows wireless network

    Hey all, I posted once before and received zero replies, so here's hoping the second time is the charm. I have a building using HP ProCurve 420A wireless access points. There's a primary SSID that Powerbook users can see properly using Airport. The s

  • SPEND LIMIT ON PO

    Hi Experts, Good Morning... I need to write abap report on 70% spend limit on Purchase Order in SRM. What are the fields and tables i've to use. Kindly repLY... Regards