Jtable in Jpopupmenu

is it posoble to put a table in a jpopupmenu?

no.well, it is possible, but...
why on earth would one want to do a thing like this!exactly....
Actually, in 1.5, support for any components other than MenuElement implementations is broken - at least with regard to mouse events, which is pretty important. But in 1.4, I believe this would work fine.

Similar Messages

  • JTabbedPane,JTable in JPopupMenu

    Hai,
    In my applet, I have added JTabbedPane and JTable in JPopupmenu just like JPanel using Java 1.3. It works fine. Now when I run this applet using Java 1.5 plugin, if I click on that JTable or JTabbedPane over JPopupmenu it closed automatically. It works fine in Java 1.4 also.
    Any ideas...?

    Hai,
    Finally I got solution for this. If I use
    show(Component invoker, int x, int y) method it gives problem. So
    I have changed my code using setLocation(int x,int x) and then
    setVisible(true). It works fine.
    But Now I have got another problem. If I add JTextField over JPopupMenu, I couldn't edit that textfield.
    Anybody having solution for this?

  • JTable And JPopupMenu

    Hello, In a JTable i want when the user press the right button of the mouse to chose an action on JPopupMenu it automaticly select the row where the Press The Right Button.

    In your MouseListener you use table.getRowAtPoint(...) to get the row, then you can use table.setRowSelectionInverval(...) to select the row.

  • Adding JPopupMenu to JTable cell

    Hi,
    I am just wondering if I can add a JPopup menu to each cell in a JTable, so that a user can perform some tasks.For example , a user should be able to delete a table cell by choosing the delete menu item in the popup menu
    many thanks
    Ramesh

    Hi,
    Add JPopupmenu and add JMenuItems on that according to your requirement. Add MouseListener to your table and on mouseReleased event check whether you have clicked the right mouse. If right mouse is clicked, then show the popup menu that you have already created. I think the following code will help you.
    JPopupMenu lJPopupMenu = new JPopupMenu();
    JMenuItem lJMenuItem1 = new lJMenuItem();
    lJPopupMenu.add(lJMenuItem1);
    lJTable.addMouseListener(this);
    MouseReleased(java.awt.event.MouseEvent mouseEvent) {
    if(mouseEvent.isPopupTrigger()){
    lJPopupMenu.show(lJTable, mouseEvent.getX(), mouseEvent.getY());
    ActionPerformed of the JMenuItem, you write the code based on the requirement.

  • JTable and clipboard...

    Hi all!
    I'm trying to copy data from JTable to system clipboard. Here's my code that is
    supposed to do that except it doesn't work. Nothing happens. The system is
    Windows, rigth click invokes menu with only one position - COPY, which is served
    by a appopriate ActionListener. I want to copy entire table (all data):
    private class NotEditableTable extends JTable
    NotEditableTable(Object[][] data, Object[] columnNames)
    super(data, columnNames);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    setCellSelectionEnabled(true);
    getTableHeader().setReorderingAllowed(false);
    NotEditableTableEngine nete = new NotEditableTableEngine();
    this.addMouseListener(nete);
    public boolean isCellEditable(int row, int column)
    return false;
    private class NotEditableTableEngine extends MouseAdapter implements ActionListener
    public void mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    JPopupMenu menu = new JPopupMenu();
    JMenuItem menuitem = new JMenuItem(Lang.TABLE_COPY, new ImageIcon("res/Copy16.gif"));
    menuitem.addActionListener(this);
    menu.add(menuitem);
    menu.show(NotEditableTable.this, e.getX(), e.getY());
    public void actionPerformed(ActionEvent e)
    TransferHandler th = new TransferHandler(null);
    NotEditableTable.this.setTransferHandler(th);
    Clipboard clip = NotEditableTable.this.getToolkit().getSystemClipboard();
    th.exportToClipboard(NotEditableTable.this, clip, TransferHandler.COPY);
    }

    I also tried the code above with a simple JTextField, both with text selected and not.Did my sample code use the TransferHandler??? The simple way to do it for a JTextField would be
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection testData = new StringSelection( textField.getText );
    //StringSelection testData = new StringSelection( textField.getSelectedText );
    c.setContents(testData, testData);
    As for the table I said that the Ctrl-C KeyStroke will invoke the default Action to copy selected data from the JTable to the Clipboard. This can be tested manually by simply using Ctrl-C. If you want to invoke it in your program then you need to get the corresponding Action from the JTable and invoke the ActionPerformed method of the Action. You can try using the
    getActionForKeyStroke(...) method of JComponent to get the Action.

  • Need Help: JTable POP up menu in a CellEditor to display on a right click

    This was from a previous post:
    I am trying to make a POP menu in a JTextComponent that has a assigned JEditorPane for a HTMLDocument to make use of the HTMLEditorKit to allow modifying HTML by the POP up menu.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col >< 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        public JTextComponent jtext;
        JEditorPane editor;
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        public FileTableCellEditor()
        editor = new JEditorPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            // System.out.println("has focus: "+hasFocus+", isSelected: "+isSelected);
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected void fireEditingCanceled()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingCanceled(event);
            ///////////createPopupMenu///////////////
            protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.cutAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.copyAction)).setAccelerator(null);
            popup.add(getTextComponent().getActionMap().get(HTMLEditorKit.pasteAction)).setAccelerator(null);
            popup.addSeparator();
            popup.add(getTextComponent().getActionMap().get("font-bold"));
            popup.add(getTextComponent().getActionMap().get("font-italic"));
            popup.add(getTextComponent().getActionMap().get("font-underline"));
            //popup.add(getTextComponent().getActionMap().get("break"));
            return popup;
        public JTextComponent getTextComponent()
             return jtext;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
    }

    I got the pop up to work, I had to go back to and add a createActionTable editor that is a JEditorPane, vs the JTextComponent!
    Here is the latest version:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.HashMap;
    import javax.swing.*;
    import javax.swing.undo.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    import javax.swing.text.html.*;
    import javax.swing.undo.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class SimpleTableDemo extends JFrame {
        public SimpleTableDemo() throws Exception {
            final JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            TableColumn fileColumn = table.getColumnModel().getColumn(2);
            FileTableCellEditor editor = new FileTableCellEditor();
            fileColumn.setCellRenderer(editor);
            fileColumn.setCellEditor(editor);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                System.exit(0);
                table.setRowHeight(100);
            public static void main(String[] args) throws Exception {
                SimpleTableDemo frame = new SimpleTableDemo();
                frame.pack();
                frame.setVisible(true);
            class MyTableModel extends AbstractTableModel {
                String[] columnNames = {"First Name","Last Name","HTML File"};
                public Object[][] data;
                MyTableModel() throws Exception
                    data = createArray();
                private Object[][] createArray() throws Exception
                    Object[][] data = {{"One", "Andrews", createDoc("file1.html")}
                return data;
                private Document createDoc(String url) throws Exception
                    File file = new File(url);
                    URL baseURL = file.toURL();
                    InputStream in = baseURL.openStream();
                    InputStreamReader r = new InputStreamReader(filterTag(in));
                    HTMLEditorKit kit = new HTMLEditorKit();
                Document doc = kit.createDefaultDocument();
                kit.read(r,doc,0);
                return doc;
                } // workaround for HTMLEditorKit.Parser, cant deal with "content-encoding"
                private InputStream filterTag(InputStream in) throws IOException {
                    DataInputStream dins = new DataInputStream( in);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);
                    DataInputStream din = new DataInputStream(new BufferedInputStream(in));
                    while (din.available() > 0) {
                    String line = din.readLine();
                    String lline = line.toLowerCase();
                    if (0 <= lline.indexOf("<meta ")) // skip meta tags
                    continue;
                    bos.write( line.getBytes());
                    din.close();
                    return new ByteArrayInputStream( bos.toByteArray());
                public int getColumnCount() {
                    return columnNames.length;
                public int getRowCount() {
                    return data.length;
                public String getColumnName(int col) {
                    return columnNames[col];
                public Object getValueAt(int row, int col) {
                    return data[row][col];
                public Class getColumnClass(int c) {
                    return getValueAt(0, c).getClass();
                public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
    public class FileTableCellEditor extends JScrollPane implements TableCellEditor , TableCellRenderer
        JEditorPane editor = new JEditorPane();
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = new HTMLDocument();;
        private EventListenerList listenerList = new EventListenerList();
        private ChangeEvent event = new ChangeEvent(this);
        HashMap<Object, Action> actions;
        public FileTableCellEditor()
        getContentPane();
        editor.setContentType("text/html");
        doc=new HTMLDocument();
        editor.addMouseListener(new MouseHandler());
        editor.setEditorKit(kit);
        editor.setDocument(doc);
        editor.setEditable(true);
        editor.setCaretColor(Color.RED);
        getViewport().setView(editor);
        createActionTable(editor);
        makeActionsPretty();
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        public void makeActionsPretty(){
             Action a;
                      a=editor.getActionMap().get(HTMLEditorKit.cutAction);
                      a.putValue(Action.SHORT_DESCRIPTION,"Cut");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('X',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.copyAction);
                      a.putValue(Action.NAME,"Copy");
                      a.putValue(Action.SHORT_DESCRIPTION,"Copy");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('C',Event.CTRL_MASK));
                      a=editor.getActionMap().get(HTMLEditorKit.pasteAction);
                      a.putValue(Action.NAME,"Paste");
                      a.putValue(Action.SHORT_DESCRIPTION,"Paste");
                      a.putValue(Action.ACCELERATOR_KEY,KeyStroke.getKeyStroke('V',Event.CTRL_MASK));
        public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column)
            if (isSelected)
            table.editCellAt(row,column);
        table.editCellAt(row,column);
        return getTableCellEditorComponent(table,value,isSelected, row, column);
        public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column)
        editor.setDocument((Document)value);
        return this;
        public boolean isCellEditable(EventObject anEvent)
        { return true;
        public boolean shouldSelectCell(EventObject anEvent)
        { return true;
        public void cancelCellEditing()
        { fireEditingStopped();
        public boolean stopCellEditing()
        { return true;
        public Object getCellEditorValue()
        { return null;
        public void addCellEditorListener(CellEditorListener l)
        { listenerList.add(CellEditorListener.class, l);
        public void removeCellEditorListener(CellEditorListener l)
        { listenerList.remove(CellEditorListener.class, l);
        protected void fireEditingStopped()
        { Object[] listeners = listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2)
        ((CellEditorListener)listeners[i+1]).
        editingStopped(event);
        protected JPopupMenu createPopupMenu()
            JPopupMenu popup =new JPopupMenu();
            popup.add(getActionByName(DefaultEditorKit.cutAction));
            return popup;
        protected class MouseHandler extends MouseAdapter{
           public void mouseReleased(MouseEvent me){
               if(me.getButton()==MouseEvent.BUTTON3){
               Point p=me.getPoint();
               createPopupMenu().show((Component)me.getSource(),p.x,p.y);
        private void createActionTable(JTextComponent textComponent) {
            actions = new HashMap<Object, Action>();
            Action[] actionsArray = textComponent.getActions();
            for (int i = 0; i < actionsArray.length; i++) {
                Action a = actionsArray;
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name) {
    return actions.get(name);

  • JPopupMenu with JInternalFrame, popup menu doesn't work

    hi, i have this problem, as shown in the sample code at the end of this post.. basically, i have a table, and i added a JPopupMenu onto the table.. the popup menu works well when running the table class, though, when i call the table class in a JInternalFrame environment, the popup menu won't work.. anyone know why?
    ///Basic sample table code, when run this alone, the popup menu will work
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableBasic extends JPanel
         private JTable table;
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        { new Date(), "B", new Integer(2), Boolean.FALSE },
                        { new Date(), "C", new Integer(9), Boolean.TRUE },
                        { new Date(), "D", new Integer(4), Boolean.FALSE}
              table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public void createPopupMenu()
              JMenuItem menuItem;
              //Create the popup menu.
              JPopupMenu popup = new JPopupMenu();
              menuItem = new JMenuItem("A popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              menuItem = new JMenuItem("Another popup menu item");
              //menuItem.addActionListener(this);
              popup.add(menuItem);
              //Add listener to the text area so the popup menu can come up.
              MouseListener popupListener = new PopupListener(popup);
              table.addMouseListener(popupListener);
         public static void main(String[] args)
              JFrame frame = new JFrame();
              TableBasic table = new TableBasic();
              table.createPopupMenu();
              frame.setContentPane(table);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         class PopupListener extends MouseAdapter
              JPopupMenu popup;
              PopupListener(JPopupMenu popupMenu)
                   popup = popupMenu;
              public void mousePressed(MouseEvent e)
                   maybeShowPopup(e);
              public void mouseReleased(MouseEvent e)
                   maybeShowPopup(e);
              private void maybeShowPopup(MouseEvent e)
                   if (e.isPopupTrigger())
                        popup.show(e.getComponent(), e.getX(), e.getY());
    ///when integrate the previous table into here, popup menu won't work
    import java.awt.*;
    import javax.swing.*;
    public class InternalFrameBasic
         extends JFrame
         //implements ActionListener
         private JDesktopPane desktop;
         private JInternalFrame menuWindow;
         public static final int desktopWidth = 800;
         public static final int desktopHeight = 700;
         public InternalFrameBasic(String title)
              super(title);
              //Set up the GUI.
              desktop = new JDesktopPane();
              desktop.putClientProperty("JDesktopPane.dragMode", "outline");
              //Because we use pack, it's not enough to call setSize.
              //We must set the desktop's preferred size.
              desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
              setContentPane(desktop);
              createMenuWindow();
              desktop.add(menuWindow); //DON'T FORGET THIS!!!
              Dimension displaySize = menuWindow.getSize();
              menuWindow.setSize(desktopWidth, displaySize.height);
         private void createMenuWindow()
              menuWindow =
                             new JInternalFrame("Event Watcher", true, //resizable
                                                                                                   true, //closable
                                                                                                   false, //not maximizable
                                                                                                   true); //iconifiable
              menuWindow.setContentPane(new TableBasic());
              menuWindow.pack();
              menuWindow.setVisible(true);
          * Create the GUI and show it.  For thread safety,
          * this method should be invoked from the
          * event-dispatching thread.
         private static void createAndShowGUI()
              //Make sure we have nice window decorations.
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //Create and set up the window.
              JFrame frame = new InternalFrameBasic("Example Internal Frame");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args)
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        createAndShowGUI();
    }

    table.createPopupMenu();The above line should not be in the main method. It should be in the constructor class of TableBasic.
    You never execute that method in your InternalFrameBasic class to the mouse listener never gets added to the table.

  • How to display non-URL-based thumbnail images in JTable

    I'm trying to display thumbnail images as a tooltip popup for certain cells in a JTable. The thumbnail images are java image objects that have been retrieved dynamically as the result of a separate process--there is no associated URL. For this reason, I can't use the setToolTipText() method of the JTable.
    My attempts to JTable's createToolTip() method also failed as it seems the ToolTipManager never calls this method for a JTable.
    As a workaround, I've added a MouseMotionListener to the JTable that detects when the mouse is over the desired table cells. However, I'm not sure how to display the popup over the JTable. The only component that I can get to display over the JTable is a JPopupMenu, but I don't want to display a menu--just the image. Can anyone suggest a way to display a small popup image over the table?
    Thanks.

    Thank You Rodney. This explains why my createToolTip() method wasn't being called, but unfortunately I'm no closer to my goal of displaying a true custom tooltip using a non-URL image rather than a text string. If I make a call to setToolTipText(), at any point, the text argument becomes the tooltip and everything I have tried in createToolTip() has no effect. However, as you pointed out, if I don't call setToolTipText(), the table is not registered with the tooltip manager and createToolTip() is never even called.
    To help clarify, I have attached an SSCCE below. Please note that I use a URL image only for testing. In my actual application, the images are available only as Java objects--there are no URLs.
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    public class Test {
        static Object[][] data = {
                {"Cell 0,0", "Cell 0,1"},
                {"Cell 1,0", "Cell 1,1"}};
        static String[] columnNames = {"Column 0", "Column 1"};
        static JFrame frame;
        static String testImageURLName = "http://l.yimg.com/k/omg/us/img/7c/0a/4009_4182164952.jpg";
        static JTable testTable = new JTable(data, columnNames) {
            public JToolTip createToolTip() {
                System.out.println("testTable.createToolTip() called");
                Image testImage = getTestImage();
                // this.setToolTipText("Table ToolTip Text");
                JLabel customTipLabel = new JLabel(new ImageIcon(testImage));
                customTipLabel.setToolTipText("Custom ToolTip Text");
                JToolTip parentTip = super.createToolTip();
                parentTip.setComponent(customTipLabel);
                return parentTip;
        // This image is loaded from a URL only for test purposes!!!
        // Ordinarily, the image object would come from the application
        // and no URL would be available.
        public static Image getTestImage() {
            try {
                URL iconURL = new URL(testImageURLName);
                ImageIcon icon = new ImageIcon(iconURL);
                return icon.getImage();
            catch (MalformedURLException ex) {
                JOptionPane.showMessageDialog(frame,
                        "Set variable \"testImageName\" to a valid file name");
                System.exit(1);
            return null;
        public static void main(String[] args) throws Exception {
            frame = new JFrame("Test Table");
            frame.setSize(300, 100);
            // Set tool tip text so that table is registered w/ tool tip manager
            testTable.setToolTipText("main tooltip");
            frame.getContentPane().add(testTable);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
    }

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

  • Manipulating tab focus in JTable ??

    Hi ,
    I am using a JTable with 3 columns out of which 3rd column is non-editable and gets populated based on the values of first 2 columns.
    Default tab behaviour traverses through all the columns including the non-editable column. I want to restrict the tabbing to non editable column and want to move tabbing across the editable columns only.
    Not able to figure out the exact API's. CAn anybody please help me out ??
    thanks in advance

    Code for the class which does that magic. It also works for LEFT, RIGHT, UP, and DOWN arrow keys.
    import java.awt.Component;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.Iterator;
    import javax.swing.AbstractButton;
    import javax.swing.JComboBox;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JTable;
    import javax.swing.KeyStroke;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.EventListenerList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.TableColumnModelEvent;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.text.JTextComponent;
    public class MyTable extends JTable{
    protected boolean processKeyBinding(KeyStroke stroke, KeyEvent evt,
                                         int condition,boolean pressed) {
            Component cellEditorComp = this.getEditorComponent();
            // If the editor is a combo box, and the key is down arrow, pass the event to Drop down
            if ((cellEditorComp != null) &&
                (cellEditorComp instanceof JComboBox) &&
                (evt.getKeyCode() == KeyEvent.VK_DOWN))
                    return super.processKeyBinding(stroke, evt, condition, pressed);
            // if the current cell is in edit mode, pass the event to editor component
            // for right and left arrow keys
            // For combo box do not pass the event, instead handle left and right arrow key press.
            if ((getCellEditor() != null) &&
            !(cellEditorComp instanceof JComboBox) &&
            ((evt.getKeyCode() == KeyEvent.VK_LEFT) ||
            (evt.getKeyCode() == KeyEvent.VK_RIGHT)))
                    return super.processKeyBinding(stroke, evt, condition, pressed);
            // To avoid handling of the keys more than once,
            // the following condition is checked.
            if (pressed)
                    return true;
            if ((evt.getKeyCode() == KeyEvent.VK_TAB) &&
               (!evt.isAltDown())) {
                    if (evt.isShiftDown())
                            processShiftTabKey();
                    else
                            processTabKey();
            else if (evt.getKeyCode() == KeyEvent.VK_LEFT){
                    processShiftTabKey();
            else if (evt.getKeyCode() == KeyEvent.VK_RIGHT){
                    processTabKey();
            else if (evt.getKeyCode() == KeyEvent.VK_UP){
                    processUpArrow();
            else if (evt.getKeyCode() == KeyEvent.VK_DOWN){
                    processDownArrow();
            else
                    return super.processKeyBinding(stroke, evt, condition, pressed);
            return true;
    * Method to select a table cell
    public void setSelectedCell(int pRow, int pCol) {
            try {
                    this.grabFocus(); 
                    this.addColumnSelectionInterval(pCol, pCol); 
                    this.addRowSelectionInterval(pRow,pRow);
                    this.editCellAt(pRow,pCol);
                    if (this.getEditorComponent() != null)
                            this.getEditorComponent().requestFocus();
                    // make the cell visible, it may not be visible sometimes.
                    scrollRectToVisible(getCellRect(pRow, pCol, true));
            } catch (Exception e) {
                    System.out.println("ERROR: attempting to select cell at row " + pRow + " & column " + pCol);
    * PROCESS SHIFT + TAB KEY
    public void processShiftTabKey(){
         int nRow = this.getEditingRow();
             int nCol = this.getEditingColumn();
             // if the cell is in edit mode, stop it.
             if (this.getCellEditor() != null)
                  this.getCellEditor().stopCellEditing();
              int newCol = findPreviousEditableColumn(nRow, nCol);
              while (nCol == newCol){
                   nRow--; // check the next row
                   nCol = this.getColumnCount(); // to start with last col
                   if (nRow < 0){
                        this.transferFocus();
                        return;
                   newCol = findPreviousEditableColumn(nRow, nCol);
             setSelectedCell(nRow, newCol);
    public int findPreviousEditableColumn(int nRow, int nCol){
            if ((nRow >= 0) &&
                 (nRow < this.getRowCount())&&
                 (nCol >= 0)){             
                  for(int i=nCol-1; i!=-1; i--){
                            if (this.isCellEditable(nRow, i)){
                        return i;
             return nCol;
    * PROCESS TAB KEY
    public void processTabKey(){
             int nRow = this.getEditingRow();
             if (nRow == -1)
                    return;
             int nCol = this.getEditingColumn();
             // if the cell is in edit mode, stop it.
             if (this.getCellEditor() != null)
                    this.getCellEditor().stopCellEditing();
                    int newCol = findNextEditableColumn(nRow, nCol);
                    while (nCol == newCol){
                            nRow++; // check the next row
                            nCol = -1; // to start with 1st col
                            if (nRow >= this.getRowCount()){
                                    this.transferFocus();
                                    return;
                            newCol = findNextEditableColumn(nRow, nCol);
            setSelectedCell(nRow, newCol);
    * PROCESS UP ARROW KEY
    public void processUpArrow(){
         int nRow = this.getEditingRow();
         if (nRow <= 0)
              return;
         int nCol = this.getEditingColumn();
         // if the cell is in edit mode, stop it.
         if (this.getCellEditor() != null)
                    this.getCellEditor().stopCellEditing();
         setSelectedCell(nRow-1, nCol);
    * PROCESS DOWN ARROW KEY
    public void processDownArrow(){
         int nRow = this.getEditingRow();
         if ((nRow == -1) ||
            ((nRow+1) == this.getRowCount()))
                 return;
         int nCol = this.getEditingColumn();
         // if the cell is in edit mode, stop it.
         if (this.getCellEditor() != null)
              this.getCellEditor().stopCellEditing();
         setSelectedCell(nRow+1, nCol);
    public int findNextEditableColumn(int nRow, int nCol){
             if ((nRow >= 0) &&
              (nRow < this.getRowCount())){             
                    for(int i=nCol+1; i<this.getColumnCount(); i++){
                      if (this.isCellEditable(nRow, i)){
                        return i;
             return nCol;
    }

  • Two different ways to show a JPopupMenu - the differene

    Hi!
    I am wondering what the difference between these lines are:
    myTable.setComponentPopupMenu(tablePopupMenu);and
    tablePopupMenu.show(myTable, evt.getX(), evt.getY());I have noticed that if I use setComponentPopupMenu(Component c) in a MouseListener for a JTable, I can just select a row once. I´m sure there are solutions for that, but stComponentPopupMenu must be harder to work with than a JPopupMenu.show() method. Am I right?

    Again, have you read the API. This method was added to make it easier. Well, the API says if you set a popup menu to a component, then it will pop up (depending on the bindings).
    If I use the JPopupMenu.show() method in a mouseListener, it will also pop up. I can not see the difference. It is still the same amount of code, just one row.
    I just discovered when I was trying with my NetBeans application (almost generated code) and my own written code, that in my own code I was using a mousePressed method and in the NetBeans application a mouseClicked. The functionality of both the codes are now the same after I have changed to mousePressed in my NetBeans application.

  • Memory Leak with JPopupMenu

    It seems there is a memory leak with JPopupMenu. The following program demonstrates this leak. If you run the program, click on show form, and then close the form, the used memory will be GCd appropriately. If you click on show form, then right click on the table to show the popup (even if you dont do anything else with the popup) then close the form, it never GCs the form. I've tried all kinds of crazy things, but I cant seem to find what is keeping the memory from being GCd.
    Peter
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeListener;
    import java.text.DecimalFormat;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    @SuppressWarnings("serial")
    public class TriState extends JPanel {
         private static final long               K               = 1024;
         private static final long               M               = K * K;
         private static final long               G               = M * K;
         private static final long               T               = G * K;
         protected static int ctr = 1;
         private JButton                              btnShow          = new JButton("Show Form");
         private JLabel                              lblMem          = new JLabel();
         private static final DecimalFormat     df               = new DecimalFormat("#,##0.#");
         protected Timer                              updateTimer     = new Timer();
         public TriState() {
              this.setLayout(new GridLayout());
              add(btnShow);
              add(lblMem);
              updateTimer.scheduleAtFixedRate(new UpdateTimerTask(), 1000, 1000);
              btnShow.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        FrmReferrals fr = new FrmReferrals();
                        fr.setVisible(true);
         class UpdateTimerTask extends TimerTask {
              public void run() {
                   SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                             dumpMemoryUsage();
         protected void dumpMemoryUsage() {
              System.gc();
              Long t = Runtime.getRuntime().totalMemory();
              long f = Runtime.getRuntime().freeMemory();
              String st = convertToStringRepresentation(t);
              String sf = convertToStringRepresentation(f);
              String su = convertToStringRepresentation(t - f);
              System.out.println("Total:" + st + "(" + t + ") Free:" + sf + "(" + f + ") Used:" + su + "(" + (t - f) + ")");
              lblMem.setText(su + "/" + st);
         public static String convertToStringRepresentation(final long value) {
              final long[] dividers = new long[]{T, G, M, K, 1};
              final String[] units = new String[]{"TB", "GB", "MB", "KB", "B"};
              if (value < 1)
                   throw new IllegalArgumentException("Invalid file size: " + value);
              String result = null;
              for (int i = 0; i < dividers.length; i++) {
                   final long divider = dividers;
                   if (value >= divider) {
                        final double dr = divider > 1 ? (double) value / (double) divider : (double) value;
                        result = df.format(dr) + units[i];
                        break;
              return result;
         private static void createAndShowGUI() {
              JFrame frame = new JFrame("SimpleTableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TriState newContentPane = new TriState();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         protected class PopupMenu extends JPopupMenu {
              public PopupMenu() {
                   JRadioButtonMenuItem item1 = new JRadioButtonMenuItem(new AbstractAction("Insert Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item1.setActionCommand("Insert");
                   add(item1);
                   JRadioButtonMenuItem item2 = new JRadioButtonMenuItem(new AbstractAction("Delete Item") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                             System.out.println(e.getActionCommand());
                   item2.setActionCommand("Delete");
                   add(item2);
         public class FrmReferrals extends JFrame {
              public FrmReferrals() {
                   super();
                   init();
              protected void init() {
                   jbInit();
              protected void closeIt() {
                   uninit();
              // variables here
              protected Dimension          dimPreferred     = new Dimension(1270, 995);
              protected JTabbedPane     tabbedPane          = new JTabbedPane();
              protected JTable          tblReferrals     = null;
              protected PopupMenu          popMenu           = new PopupMenu();
              protected void jbInit() {
                   setPreferredSize(dimPreferred);
                   setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   setTitle("Referrals");
                   JPanel pnl = new JPanel();
                   pnl.setOpaque(false);
                   pnl.setLayout(new BorderLayout());
                   pnl.add(tabbedPane, BorderLayout.CENTER);
                   // put it all in the frame
                   add(pnl);
                   pack();
                   setLocationRelativeTo(null);
                   // init the table and model
                   ReferralsTableModel ctm = new ReferralsTableModel(buildDummyVector());
                   tblReferrals = new JTable(ctm);
                   tblReferrals.setComponentPopupMenu(popMenu);
                   tblReferrals.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                   tabbedPane.add(new JScrollPane(tblReferrals, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
                   addWindowListener(new WindowListener() {
                        @Override
                        public void windowActivated(WindowEvent e) {}
                        @Override
                        public void windowClosed(WindowEvent e) {}
                        @Override
                        public void windowClosing(WindowEvent e) {
                             closeIt();
                        @Override
                        public void windowDeactivated(WindowEvent e) {}
                        @Override
                        public void windowDeiconified(WindowEvent e) {}
                        @Override
                        public void windowIconified(WindowEvent e) {}
                        @Override
                        public void windowOpened(WindowEvent e) {}
              protected Vector<DBO_Referrals> buildDummyVector() {
                   Vector<DBO_Referrals> vr = new Vector<DBO_Referrals>();
                   for (int x = 0; x < 5000; x++) {
                        DBO_Referrals r = new DBO_Referrals(x+(5000*ctr));
                        vr.add(r);
                   return vr;
              protected void uninit() {
                   tblReferrals.setComponentPopupMenu(null);
                   for (Component c : popMenu.getComponents()) {
                        PropertyChangeListener[] pl = c.getPropertyChangeListeners();
                        for (PropertyChangeListener l : pl)
                             c.removePropertyChangeListener(l);
                        if (c instanceof JMenuItem) {
                             ActionListener [] al = ((JMenuItem)c).getActionListeners();
                             for (ActionListener l : al) {
                                  ((JMenuItem)c).removeActionListener(l);
                   popMenu = null;
              protected class DBO_Referrals {
                   protected long          id;
                   protected String     Employee;
                   protected String     Rep;
                   protected String     Asst;
                   protected String     Client;
                   protected String     Dates;
                   protected String     Status;
                   protected String     Home;
                   public DBO_Referrals(long id) {
                        this.id = id;
                        Employee = "Employee" + id;
                        Rep = "Rep" + id;
                        Asst = "Asst" + id;
                        Client = "Client" + id;
                        Dates = "Dates" + id;
                        Status = "Status" + id;
                        Home = "Home" + id;
                   public long getId() {
                        return id;
                   public String getEmployee() {
                        return Employee;
                   public String getRep() {
                        return Rep;
                   public String getAsst() {
                        return Asst;
                   public String getClient() {
                        return Client;
                   public String getDates() {
                        return Dates;
                   public String getStatus() {
                        return Status;
                   public String getHome() {
                        return Home;
              public class ReferralsTableModel extends AbstractTableModel {
                   protected Vector<DBO_Referrals>          data          = new Vector<DBO_Referrals>();
                   protected String[]                         sColumns     = {"id", "Employee", "Rep", "Assistant", "Client", "Date", "Status", "Home", "R"};
                   public ReferralsTableModel() {
                        super();
                   public ReferralsTableModel(Vector<DBO_Referrals> data) {
                        this();
                        this.data = data;
                   @SuppressWarnings("unchecked")
                   @Override
                   public Class getColumnClass(int col) {
                        switch (col) {
                             case 0 :
                                  return Long.class;
                             default :
                                  return String.class;
                   @Override
                   public int getColumnCount() {
                        return sColumns.length;
                   @Override
                   public int getRowCount() {
                        return data.size();
                   @Override
                   public Object getValueAt(int row, int col) {
                        if (row > data.size())
                             return null;
                        DBO_Referrals a = data.get(row);
                        switch (col) {
                             case 0 :
                                  return a.getId();
                             case 1 :
                                  return a.getEmployee();
                             case 2 :
                                  return a.getRep();
                             case 3 :
                                  return a.getAsst();
                             case 4 :
                                  return a.getClient();
                             case 5 :
                                  return a.getDates();
                             case 6 :
                                  return a.getStatus();
                             case 7 :
                                  return a.getHome();
                             case 8 :
                                  return "+";
                             default :
                                  return null;

    BTW instead of continually printing out the memory use a profiler (jvisualvm in the jdk/bin directory -> heapdump -> search on your class -> view in instances -> find nearest GC root).
    Looks like BasicPopupMenuUI doesn't remove a reference to the JRootPane immediately. As far as I can see it will be removed when another menu shows.
    As a hackish workaround you can try this in you FrmReferrals#uninit():
                for(ChangeListener listener : MenuSelectionManager.defaultManager().getChangeListeners()) {
                    if (listener.getClass().getName().contains("MenuKeyboardHelper")) {
                        try {
                            Field field = listener.getClass().getDeclaredField("menuInputMap");
                            field.setAccessible(true);
                            field.set(listener, null);
                        } catch (Exception e) {
                            // ignored
                        break;
                }Funnily enough though it isn't there when I reduce your code to a SSCCE:
    import java.awt.*;
    import javax.swing.*;
    public class TestBasicPopupMenuUILeak extends JFrame {
        public TestBasicPopupMenuUILeak() {
            super("Not collected right away");
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.getContentPane().add(
                            new JButton(new AbstractAction("Show frame") {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    EventQueue.invokeLater(new Runnable() {
                                        public void run() {
                                            JLabel label = new JLabel(
    "Right click to show popup, then close this frame."
    + "The frame with not be GCed until another (popup) menu is shown.");
                                            JPopupMenu popup = new JPopupMenu(
                                                    "Popup");
                                            popup.add("Item");
                                            label.setComponentPopupMenu(popup);
                                            // named differently so you can find it
                                            // easily in your favorite profiler
                                            JFrame frame = new TestBasicPopupMenuUILeak();
                                            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                                            frame.getContentPane().add(label);
                                            frame.pack();
                                            frame.setLocationRelativeTo(null);
                                            frame.setVisible(true);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    }

  • JTable - row selection not working + change the text format

    Hi All,
    I have written a code to display Jtable with 2 columns, 1 column to display image+text and other is multiline.
    I have used 2 different cell renderer for achiveing the same.
    Please advice on the following:
    @ When I click on row, only one column gets selected. How to fix this?
    @ Data to be displayed in rows is fetched from database. And on some STATUS value row should be in bold text or plain text. I have achieved this but withou logic to iterate over it.
    @ When user right clicks on the row allow them to set text in the row as bold or plain.(Just like we do with mails in outlook box)
    Below is the code:
    Hi All,
    I have written a code to display Jtable with 2 columns, 1 column to display image+text and other is multiline.
    I have used 2 different cell renderer for achiveing the same.
    Please advice on the following:
    @ When I click on row, only one column gets selected. How to fix this?
    @ Data to be displayed in rows is fetched from database. And on some STATUS value row should be in bold text or plain text. I have achieved this but withou logic to iterate over it.
    @ When user right clicks on the row allow them to set text in the row as bold or plain.(Just like we do with mails in outlook box)
    Below is the code:package jtab;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import jtab.TestIcon.iconRenderer;
    public class SampleJtable {
         JFrame frame;
         JTable table;
         JScrollPane panel;
         JPopupMenu popupMenu ;
         public static void main(String[] args) {
              SampleJtable sample = new SampleJtable();
              sample.loadGUI();
         public void loadGUI(){
              frame = new JFrame("Sample Program for Font and ImageIcons");
              frame.setContentPane(panel);
              frame.setSize(550,250);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         public SampleJtable(){
              BufferedImage images[] = new BufferedImage[1];
              try{
                   images[0] = javax.imageio.ImageIO.read(new File("C:/go.gif"));
              }catch(Exception e){
                   e.printStackTrace();
              final Object data [][] = {{"Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe \n P",new ImageStore(images[0],"Bourquin Rene")},
                        {"Auftrag \n test \n \n 1957,Grenchen Kaufe \n N",new ImageStore(images[0],"Bourquin Rene")}};
              String colIds [] ={"Beschrebung","Von"};
              DefaultTableModel model = new DefaultTableModel(data, colIds) {  
    public Class getColumnClass(int column) {  
    return data[0][column].getClass();
              /*Vector<Object> rowData1 = new Vector(2);
              rowData1.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
              rowData1.add(new ImageStore(images[0],"Bourquin Rene"));
              Vector<Object> rowData2 = new Vector(2);
              rowData2.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
              rowData2.add(new ImageStore(images[0],"Bourquin Rene"));
              Vector<Vector> rowData = new Vector<Vector>();
         rowData.addElement(rowData1);
         rowData.addElement(rowData2);
              Vector<String> columnNames = new Vector<String>();
         columnNames.addElement("Beschrebung");
         columnNames.addElement("Von");     
              DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {  
              table = new JTable(model);
              table.setDefaultRenderer(ImageStore.class, new ImageRenderer());          
              table.getTableHeader().getColumnModel().getColumn(0).setCellRenderer(new LineCellRenderer());
              table.setRowHeight(84);
              panel = new JScrollPane(table);
              panel.setOpaque(true);
         class ImageRenderer extends DefaultTableCellRenderer {  
         public Component getTableCellRendererComponent(JTable table,
         Object value,
         boolean isSelected,
         boolean hasFocus,
         int row, int column) {  
         super.getTableCellRendererComponent(table, value, isSelected,
         hasFocus, row, column);
         ImageStore store = (ImageStore)value;
         setIcon(store.getIcon());
         setText(store.text);
         return this;
         class ImageStore {  
         ImageIcon icons;
         String text;
         int showingIndex;
         public ImageStore(BufferedImage image1,String s) {
         icons = new ImageIcon(image1);
         showingIndex = 0;
         text = s;
         public ImageIcon getIcon() {  
         return icons;
         public void toggleIndex() {  
         showingIndex = (showingIndex == 0) ? 1 : 0;
         class LineCellRenderer extends JEditorPane implements TableCellRenderer {
              public LineCellRenderer() {           
              setOpaque(true);
              setContentType("text/html");          
              public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
              //System.out.println("Whats in value = "+ value.toString());
              String [] strArray = value.toString().split("\n");
              String rtStr = null ;
              System.out.println("TYPE+ "+ strArray[strArray.length-1].toString());
              String val = strArray[strArray.length-1].toString().trim();
              if (val.equalsIgnoreCase("N")){
                   System.out.println("TYPE+ IS NEW");
                   rtStr = "<html><head></head><body><b><div style=\"color:#FF0000;font-weight:bold;\">" + strArray[0] + "</div>" +
                             " <div style=\"color:#0000FF;font-weight:bold;\">" + strArray[1] + "</div>" +
                             "<div style=\"color:#0000FF;font-weight:bold;\">" + strArray[2] + "</div>" +
                             "<div style=\"color:#0000FF;font-weight:bold;\">" + strArray[3] + "</div>" +
                             "</b></body></html>";
              else {
                   System.out.println("TYPE+ IS PENDING");
                   rtStr = "<html><head></head><body><div style=\"color:#FF0000;\">" + strArray[0] + "</div>" +
                   " <div style=\"color:#0000FF;\">" + strArray[1] + "</div>" +
                   "<div style=\"color:#0000FF;\">" + strArray[2] + "</div>" +
                   "<div style=\"color:#0000FF;\">" + strArray[3] + "</div>" +
                   "</body></html>";
              setText(rtStr);
              return this;

    Posting code again........
    package jtab;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.ImageIcon;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import jtab.TestIcon.iconRenderer;
    public class SampleJtable {
    JFrame frame;
    JTable table;
    JScrollPane panel;
    JPopupMenu popupMenu ;
    public static void main(String[] args) {
    SampleJtable sample = new SampleJtable();
    sample.loadGUI();
    public void loadGUI(){
    frame = new JFrame("Sample Program for Font and ImageIcons");
    frame.setContentPane(panel);
    frame.setSize(550,250);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public SampleJtable(){
    BufferedImage images[] = new BufferedImage[1];
    try{
    images[0] = javax.imageio.ImageIO.read(new File("C:/go.gif"));
    }catch(Exception e){
    e.printStackTrace();
    final Object data [][] = {{"Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe \n P",new ImageStore(images[0],"Bourquin Rene")},
    {"Auftrag \n test \n \n 1957,Grenchen Kaufe \n N",new ImageStore(images[0],"Bourquin Rene")}};
    String colIds [] ={"Beschrebung","Von"};
    DefaultTableModel model = new DefaultTableModel(data, colIds) {
    public Class getColumnClass(int column) {
    return data[0][column].getClass();
    /Vector<Object> rowData1 = new Vector(2);
    rowData1.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
    rowData1.add(new ImageStore(images[0],"Bourquin Rene"));
    Vector<Object> rowData2 = new Vector(2);
    rowData2.add("Auftrag \n test \n 777,Abdherhalden Josef, \n 1957,Grenchen Kaufe");
    rowData2.add(new ImageStore(images[0],"Bourquin Rene"));
    Vector<Vector> rowData = new Vector<Vector>();
    rowData.addElement(rowData1);
    rowData.addElement(rowData2);
    Vector<String> columnNames = new Vector<String>();
    columnNames.addElement("Beschrebung");
    columnNames.addElement("Von");
    DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
    table = new JTable(model);
    table.setDefaultRenderer(ImageStore.class, new ImageRenderer());
    table.getTableHeader().getColumnModel().getColumn(0).setCellRenderer(new LineCellRenderer());
    table.setRowHeight(84);
    panel = new JScrollPane(table);
    panel.setOpaque(true);
    class ImageRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
    ImageStore store = (ImageStore)value;
    setIcon(store.getIcon());
    setText(store.text);
    return this;
    class ImageStore {
    ImageIcon icons;
    String text;
    int showingIndex;
    public ImageStore(BufferedImage image1,String s) {
    icons = new ImageIcon(image1);
    showingIndex = 0;
    text = s;
    public ImageIcon getIcon() {
    return icons;
    public void toggleIndex() {
    showingIndex = (showingIndex == 0) ? 1 : 0;
    class LineCellRenderer extends JEditorPane implements TableCellRenderer {
    public LineCellRenderer() {
    setOpaque(true);
    setContentType("text/html");
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println("Whats in value = " value.toString());
    String [] strArray = value.toString().split("\n");
    String rtStr = null ;
    System.out.println("TYPE " strArray[strArray.length-1].toString());
    String val = strArray[strArray.length-1].toString().trim();
    if (val.equalsIgnoreCase("N")){
    System.out.println("TYPE IS NEW");
    rtStr = "<html><head></head><body><b><div style=\"color:#FF0000;font-weight:bold;\">" strArray[0] "</div>"
    " <div style=\"color:#0000FF;font-weight:bold;\">" strArray[1] "</div>"
    "<div style=\"color:#0000FF;font-weight:bold;\">" strArray[2] "</div>"
    "<div style=\"color:#0000FF;font-weight:bold;\">" strArray[3] "</div>"
    "</b></body></html>";
    else {
    System.out.println("TYPE+ IS PENDING");
    rtStr = "<html><head></head><body><div style=\"color:#FF0000;\">" strArray[0] "</div>"
    " <div style=\"color:#0000FF;\">" strArray[1] "</div>"
    "<div style=\"color:#0000FF;\">" strArray[2] "</div>"
    "<div style=\"color:#0000FF;\">" strArray[3] "</div>"
    "</body></html>";
    setText(rtStr);
    return this;
    }

  • DropDown List in a JTable

    Hi.
    I want to add a drop down list(similiar to combo box) in a JTable cell.
    but the difference is that multiple selection should be allowed(similar to JList, but it should be drop down)
    have anyone implemented this thing before,
    if so please help or give ideas
    thanks
    ranjith

    To make this more explicit, I've changed your code a bit. This will only compile if CustomTablePanel is derived from JTable:
                                                JPopupMenu popup;
                                                public boolean editCellAt(int row, int col, EventObject e) {
                                                        if(col == 1)
                                                        popup = new JPopupMenu();
                                                        Rectangle rect = getCellRect(row, col, true);
                                                        JList l = new JList(new Object[] { "one", "two", "three" });
                                                        JScrollPane pane = new JScrollPane(l);
                                                        popup.add(pane);
                                                        popup.setPreferredSize(new Dimension(rect.width, rect.height * 4));
                                                        popup.show(this, rect.x, rect.y);
                                                        return false;
                                                        } else {
                                                          return super.editCellAt(row, col, e);//<--- IMPORTANT!
                                                public void editingCanceled(ChangeEvent e) {
                                                        popup.setVisible(false);
                                            }

  • Remove the Enter key binding from a JPopupMenu

    Hi,
    Does anyone know how to remove the Enter key binding from a JPopupMenu?
    So when the popupmenu is showing and you type Enter, nothing should happen and the menu should stay where it is.
    I have tried:
    popup.getActionMap().put("enter", null);
    popup.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enter");but the popup always disappears.
    Any ideas?
    Cheers,
    patumaire

    First of all, that is not the proper way to "remove" a key binding. Read the Swing tutorial on [How to Use Key Bindings|http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html#howto] for more information.
    However, we still have a couple of problems:
    a) the input map is dynamically built as the popup menu is displayed
    b) the input map is built for the root pane, not the popup menu
    The following seems to work:
    popup.show(...);
    InputMap map = getRootPane().getInputMap(JTable.WHEN_IN_FOCUSED_WINDOW);
    map.put(KeyStroke.getKeyStroke("ENTER"), "none");
    KeyStroke[] keys = map.allKeys();
    for (int i = 0; i < keys.length; i++)
         KeyStroke key = keys;
         Object action = map.get( key );
         System.out.println(key + " : " + action);

Maybe you are looking for

  • Contacts no Longer work after iOS 5 update

    .. I can get to contacts but i no longer have a +  sign to add new contacts. sometimes it will flicker briefly and then disappear??? HELP?? i have done a restore and everything to no avail..

  • Unable to access queries in Universe created over infocubes

    Hello Gurus Im having a weird situation over here with my queries created over BI content info cubes.Ive gone through all the threads related to my issue and ive tried more or less all the solutions specified. I hope i would get a different solution

  • Cluster table defination not as per book give me own defination

    Hi gurus, Please give me the cluster table defination and how to create it step by step method. Dont give answer Tables assigned to a table cluster are referred to as cluster tables. I know that give explanation what is the need of this tables alread

  • Converting a JPG into a stationary

    Is it possible to take an EPS / JPG / PDF file and convert it into a stationary? I managed to do that, but without the ability to enter text in this mail. How can I create a kind of "text box" same as in the pre-installed stationaries?

  • HR TIME ATTENDANCE MANAGMENT SYSTEM (PA2011 - PA2002)

    HR TIME ATTENDANCE MANAGMENT SYSTEM ==================================== I am having card swipe time in PA2011. Now i hav to insert this data in PA2002(ATTENDANCE).But i dnt know tat which time is login & which is logout time.......how to identify th