Editor-in-Chief of cell customized JTable loss of focus

It is a follow-up of Re: tutorial on the AWT/Swing control flow in which I ask for pointers to help me understand the source of behavior lost focus in the custom my JTable cell editor.

I've done some research more and it turns out that loss of focus is a more general problem with the custom cell editors who call other windows. Even the demo of the pipette in the JTable tutorial at http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableDialogEditDemo has this problem, IF you add a text field or both to the setting in FRONT of the table. Only in the demo table loses focus when the color picker appears, it is because the table is the only thing in the window!

Here's the code for demo, increased with two text fields, which are certainly bad here, but which serve the desired purpose:
/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TableDialogEditDemo extends JPanel {
    public class ColorEditor extends AbstractCellEditor
            implements TableCellEditor,
            ActionListener {
        Color currentColor;
        JButton button;
        JColorChooser colorChooser;
        JDialog dialog;
        protected static final String EDIT = "edit";

        public ColorEditor() {
            //Set up the editor (from the table's point of view), which is a button.
            //This button brings up the color chooser dialog, which is the editor from the user's point of view.
            button = new JButton();
            button.setActionCommand(EDIT);
            button.addActionListener(this);
            button.setBorderPainted(false);

            //Set up the dialog that the button brings up.
            colorChooser = new JColorChooser();
            dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                    colorChooser, this,  //OK button handler
                    null); //no CANCEL button handler
        }

        /**
         * Handles events from the editor button and from the dialog's OK button.
         */
        public void actionPerformed(ActionEvent e) {
            if (EDIT.equals(e.getActionCommand())) {
                //The user has clicked the cell, so bring up the dialog.
                button.setBackground(currentColor);
                colorChooser.setColor(currentColor);
                dialog.setVisible(true);

                //Make the renderer reappear.
                fireEditingStopped();

            } else { //User pressed dialog's "OK" button
                currentColor = colorChooser.getColor();
            }
        }

        public Object getCellEditorValue() {
            return currentColor;
        }

        public Component getTableCellEditorComponent(JTable table,
                                                     Object value,
                                                     boolean isSelected,
                                                     int row,
                                                     int column) {
            currentColor = (Color) value;
            return button;
        }
    }

    public class ColorRenderer extends JLabel
            implements TableCellRenderer {
        Border unselectedBorder = null;
        Border selectedBorder = null;
        boolean isBordered = true;

        public ColorRenderer(boolean isBordered) {
            this.isBordered = isBordered;
            setOpaque(true);
        }

        public Component getTableCellRendererComponent(
                JTable table, Object color,
                boolean isSelected, boolean hasFocus,
                int row, int column) {
            Color newColor = (Color) color;
            setBackground(newColor);
            if (isBordered) {
                if (isSelected) {
                    if (selectedBorder == null) {
                        selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                table.getSelectionBackground());
                    }
                    setBorder(selectedBorder);
                } else {
                    if (unselectedBorder == null) {
                        unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                table.getBackground());
                    }
                    setBorder(unselectedBorder);
                }
            }
            return this;
        }
    }

    public TableDialogEditDemo() {
        super(new GridLayout());

        JTextField tf1 = new JTextField("tf1");
        add(tf1);
        JTextField tf2 = new JTextField("tf2");
        add(tf2);

        JTable table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        JScrollPane scrollPane = new JScrollPane(table);

        table.setDefaultRenderer(Color.class,
                new ColorRenderer(true));
        table.setDefaultEditor(Color.class,
                new ColorEditor());

        add(scrollPane);
    }

    class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"First Name",
                "Favorite Color",
                "Sport",
                "# of Years",
                "Vegetarian"};
        private Object[][] data = {
                {"Mary", new Color(153, 0, 153),
                        "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", new Color(51, 51, 153),
                        "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", new Color(51, 102, 51),
                        "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", Color.red,
                        "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", Color.pink,
                        "Pool", new Integer(10), new Boolean(false)}
        };

        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 void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("TableDialogEditDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent newContentPane = new TableDialogEditDemo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
When you come back to choose a color, tf1 is given to the development, instead of the table. This is because bringing the color selector window to front raises an event lost the focus to the cell editor component; It's temporary, as it should, then, why the hell is the system to lose track of who has the focus in the window?

I see the following in #getMostRecentFocusOwner () Window:
  public Component getMostRecentFocusOwner()
  {
    if (isFocused())
    {
      return getFocusOwner();
    }
    else
    {
      Component mostRecent =
        KeyboardFocusManager.getMostRecentFocusOwner(this);
      if (mostRecent != null)
      {
        return mostRecent;
      }
      else
      {
        return (isFocusableWindow())
               ? getFocusTraversalPolicy().getInitialComponent(this)
               : null;
      }
    }
  }
My app has a custom course development policy, so I am able to see who is called, and indeed, getInitialComponent() is called. Clearly, the KeyboardFocusManager is in fact to lose track of the fact that the table was concentrated to the point where the control was transferred to the color picker! I think that is quite unreasonable, especially since, as mentioned, it is a temporary , not a permanent LostFocus event.

I would be grateful for any wisdom to solve this, since a behavior similar to this little demo - without loss of focus, of course - is an essential part of my application.

Hello
Or simpler, setFocusable (false)

 public ColorEditor() {
   button = new JButton();
   button.setActionCommand(EDIT);
   button.addActionListener(this);
   button.setBorderPainted(false);
   button.setFocusable(false); //<---- add
 

Tags: Java

Similar Questions

  • Bug: New editor-in-Chief "Insert link...". "does not link text?

    We were unable to upgrade many of our clients for the new editor because they have grown dependent on feature "Custom links" former editor that added the link by using the name of the module as the link for the link text. For example, in the former editor, if you have added a link to a piece of media download it would look like this:

    Revised April 2011

    It made him very simple and intuitive for end-users to add basic links to items in the module. They their selected in the list and a 'ready to go' link was inserted for them.

    However, the system now offers the following when you click on this same point with "insert links...". "in the new editor:

    LiteratureRetrieve.aspx? ID = 12345

    Some would say "Just select and edit text." (.. .assuming you know / remember the name that you have given this particular element)

    HHowever, If do you this with the new editor, it attaches automatically link to just the first letter you type, having for result something like this:

    Nname of ew

    This, of course, can now only be corrected using the HTML mode, which, ironically, is what the editor is supposed to be helping users to avoid!

    Also, this seems to be the case for all links created with the new editor (, new pages, FAQ, etc), so I'm really confused as to how there is no mention of this problem anywhere, by anyone.

    IMHO, this (oversight?) must be addressed as a priority, because it clearly undermines the essential purpose of having a WYSIWYG editor there in the first place!

    Or maybe I should just now seeking customers with ability of HTML coding?

    If I'm missing something, please let me know, but for now, the new editor in Chief is a "no-go" for most customers because this 'link to fundamentals creating' ability was rendered useless to them.

    -Bruce

    From version R207, R207 - update of the system: the link selector inserts the name of the element instead of the URL of the link.

    Dan Popa

  • My co-editor in Chief is the CC 2015 but computer science from the University, I am using is stuck with CC 2014. Help!

    Hey Adobe Community People.

    My co-editor is CC 2015 (working in another State), but the University computer I use is stuck with CC 2014. I checked with our IT Department and they say that the school license is not set to renew until August, so we're stuck with this version until then. Am I supposed to twiddle my thumbs for the next two months? My editor and I share projects every day so this is a huge setback.

    Is there is workaround for this backward incompatibility dilemma? I don't know about XML, but that it only works with sequences, or can it many projects? Must reinstall everything 2014 and just redo the whole of his work?

    I buy my own darn computer and pay for 2015 for CC?

    These ^ ^ ^ are all the solutions... but I wonder if there is a simpler, which don't make me to re-do work or pay for the Crack of Adobe (I mean cloud creative).

    Also, Adobe, you are makes it very difficult for me to contact support by phone. I am disappointed in your absence on the customer service... it is also just a rant on my frustration with the incompatibility of these annual updates of the CC.

    Help!

    Sincerely,

    Frustrated. (My real name is Brian... and I'm not usually this unpleasant)

    This isn't his right - the whole concept of the subscription model is up-to-date new revisions are released.  You should talk to Adobe - I've provided contact information in my answer.

  • I've recently upgraded to El Capitan of Lion.  My iPhoto library is also transformed into Photos.  In iPhoto, I used Photoshop as my editor in Chief of "standard / default.  I can't do that to work with Photos, all I can't get is the photo editor.

    I've recently updated to Lion at El Capitan and my library of more than 40 000 iPhoto was also improved (?) photo.  He ran all night.  I used Photoshop as my editor of "standard/default" in iPhoto, but now I can't seem to appear in the photo is the photo editor, which is not enough for my purposes.  I have found a workaround that requires images to export], edited and then re-imported to the Photos, but I lose all the original images.  Can I have Photoshop become my default editor for Photos, as if it was in iPhoto?

    3rd party editing application must be updated to work with the new structure of the El Capitan and Photos before they will be able to work seamlessly with Photos.

    In the meantime we must export the original file in the office using the menu option file ➙ export Original unmodified for 1 Photo and edit the file there.

  • Update of Stimulus Legacy profiles to new editor-in-Chief

    Hello world

    I am currently working on the update of a testbed of Veristand 2011 to 2015 SP1. On the bench that we have a lot of Stimulus profile files that were created with the profile of Stimulus editor inherited.

    Is it possible to update the profile of current stimulus editor files and keep their use?

    By looking at the files, I know they are XML, but for some reason, they are completely different formats. It should be possible, however, the translation from one format to the other quite easily. I'm not saying that's what I'll do, just that it is possible.

    See you soon,.

    Pete

    There is not a conversion utility. Here are a few points to note:

    1. the stimulus inherited profile editor is always delivered with 2015 SP1. You can continue to run the same tests in the new version without converting them. New projects by default will not have this tool in the Workspace menu, but you can add it.

    2. If one of your tests is to read CSV files, the same format works in the new Stimulus profile editor.

    Please let us know if there is a particular reason that you want to convert the files to the new format if the notes above don't help you. Who could help us understand a good path for you!

  • Photoshop Elements 14, RAW-editor-in-Chief, Synchronisieren von Bildeinstellungen

    Wie kann ich im RAW-editor gewahlte Bildeinstellungen auf eine andere RAW-Datei have?

    It is not possible to save the settings as a preset in the elements. You would need something like Lightroom.

  • Developer SQL 4.1.0.17 - editor-in-Chief

    I use SQL Developer 4.1.0.17

    Build handmade 17.29

    I wanted to replace apostrophe markts.

    Steps to follow:

    1. click on edit and replace

    "2 text to search for.

    3. replace by (hidden by NAME)

    4. selected text

    5 Cloicked OK

    Found no «»

    Repeated steps above, citations, replaced by the NAME even though replacement string was EMPTY!

    Had to copy and paste to Open Office and do replace it in there.

    Everyone knows who? What is an ide without basic capabailities edition.

    MOD. action: Please refrain from using that word in the title of the thread, which will not help to understand what you want, more breaking the rules to keep the professional language, it has been amended accordingly.

    Post edited by: Nicolas.Gasparotto

    I do not fear the harsh words, but you could use securities descriptions topic/thread?

    Here's how it works in my current dev build. We are always to finish the job of the UI in the spreadsheet, but here's what it looks like right now in pl/sql editors.

    You can see the occurrences found the chain of research immediately, and then they are replaced as expected when I hit the button "replace all." Note the first time that I ran through it, so I started with the text selection and pressing Ctrl + R, he noticed this and started with the highlight mode switched on.

    We hope to have an ai2 out soon in order to test this for yourself. Or feel free to give me another test scenario to go up there.

  • Editor in Chief

    Hello
    Free editor supports Unicode, which can be used in both Windows and Linux?
    Kind regards

    Hello

    Vim/gvim supports unicode (see Help for: encoding =,: set fileencoding = orders) and is one of the two most popular/well-known text editors. Others (Emacs) should also take support unicode. Both vim and Emacs are available under Linux and Windows, vi (the predecessor of vim) is the default editor in almost any Unix system. IMO must be considered (even if at first it may seem very difficult to use).

  • Error message when you use Photoshop Elments as editor-in-Chief

    Hello

    I use PSE 10 (and 9) and Lightroom 4 has added a new program.

    I've linked PES 10 as external editor as shown in Ernen-editor-in-Lightroom-nutzen-/ http://TV.adobe.com/de/Watch/von-Photoshop-Elements-zu-Lightroom-wechseln/Elements-als-ext (German).

    Error message:

    Unexpected error executing the command:

    #1 bad argument to 'reduce' (string expected, got the draw)

    error_message_lgtroom2PSE.JPG

    So, what's the problem?

    Greetings,

    Oliver Rindelaub

    This is a known bug in LR4. Try reinstalling PSE10.

    Beat

  • Loss of Focus in a custom component ItemRendered

    I have a custom component which is composed of multiple TextAreas and displayed on the screen with other identical components via itemRenderer where = 'true' useVirtualLayout.

    After I clicked on an text box to give it focus, I want to be able to tab to the next TextArea. But instead of emphasis here, the emphasis is the parent of the itemRenderer, forces me to click in the text box in my component to give it focus.

    I tried to use focusManager.setFocus (parm) - corresponding parm to the id text box , I want to take focus, but if I did that with focusManager.getFocus (), I find that the parent currently has the focus.

    I tried also provide each TextArea with a tabIndex (instead of using focusManager.setFocus). But it seems to be ignored.

    Any ideas?

    You need to maybe get the keyFocusChange event and cancel it.

  • Resize, crop and rule Dimensions puzzle, editor-in-Chief

    I resized an image by changing the resolution from 72 to 300 inorder to get my image down to a realistic 5 x 7, I opened the sovereign in the editor and then the value my standard harvest size 5 x 7, but I see that they do not match. Is this normal and what I need to adjust physically harvest every time for each photo?

    And my point is that you are cheating yourself if you change the resolution of your image. It's an extra step that has zero advantage and can be harmful.

    If 'Resample' is not checked, you must pixels of same accurate than you had before. Your picture has not changed.

    If 'Resample' is checked, then you're throwing pixels.

    You can 'include everyone in the shot of the group' regardless of the resolution of the image.

    So I come back in my opinion earlier... the value of the crop tool to have proportions of 5 x 7, empty the field of the resolution, and that's all you need.

  • Photoshop Elements ver7. Editor in Chief

    So I bought a new laptop and with it I orderded adobe photoshop elements version 7.  Once I finished installing everything that I went to try to open the editor of photoshop. He talks about the first screen with the blue box, where it shows all its loading, and when he came to the part where it says 'building the TWAIN menu items' a new window opens and says "a problem caused blocking the program works correctly. Windows will close the program and notify you if a solution is available.

    then I hit close program and everything closes. no solution.

    I tried to call support adobe technique, but they were of no use. They said that the support is a paid service.

    Ive tried uninstalling the software and put it back via the cd that came with eveyting but the program does not always load.

    the organzier photoshop elements part works, but the editor is not. I tried to open the editor of the Organizer, but the same problem has resulted.

    my laptop runs on the windows vista operating system.

    If anyone can please offer suggestions/solutions that would be so useful. I like editing photos and Miss to do that due to a technical problem.

    Thanks in advance.

    Adobe is not updated of his technical notes.  But the technical note applies to the PSE 7.  However, a look at my machine, I see PSE 7 folder is located here:

    Adobe Photoshop C:\Program 7.0\Locales\en_US\Plug-Ins\Import-Export elements

    If you are in another country, you will need to choose the appropriate locale subfolder.  If you can't find it, use Windows Explorer to find C:\Program Adobe Photoshop Elements 7.0 Twain_32.8BA.

  • Can't connect to Editor-in-Chief of the PSE6

    I receive the following message if poster, although I'm registered.

    We were unable to connect to adobe to register your product

    Thank you

    I have corrected the problem.

    I have re-installed and blocked the Java plugin

  • Loss of focus intermittently

    Sometimes I have to resize a batch of images by hand - with smaller batches, sometimes it's just faster than creating a macro. Yesterday was such a day.

    Ps CS5 64-bit W7 and several photos using open, I start with Ctrl-Alt-I and tap on the selected size, finishing with the Enter key. The next thing that I could do is run an action to sharpen for screen, except that I found that when I did it, sometimes the computer would make a 'mistake' sound. If I then clicked on the tab of the image and tried again, it works fine.

    Of course, when you're done that maybe 20 times, taking the hand of the keyboard, sliding a mouse and clicking a tab becomes a bit annoying, especially when there is no reason for the image of your work to lose focus. BTW, no other images to obtain focus, none seem to have.

    I have a lot of plug-ins including Nik, fractals and Topaz - nothing too exotic - and the extension of Dr. Brown. Can any kind soul point me in the right direction before the hood and get dirty?

    He there had a number of discussions on how the ALT immediately activates the menus in Photoshop CS5, which is actually the standard Windows behavior, but represents a slight departure from earlier versions of Photoshop.  The departure of light, is that activation of the menu seems to take the path with the help of other keyboard shortcuts, instead you net a his 'mistake' of windows.

    I'm wondering, since the Alt key is one of those that you use, if this problem happens to you.

    See this thread:

    http://forums.Adobe.com/thread/670988

    -Christmas

  • Loss of focus

    I inherited an HtmlHelp application built in RoboHelp. I got call from my (VB6) application or double-click on it in a directory in Windows Explorer, it does not return attention to the calling application.

    It is apparently unique to RoboHelp, than others. I have CHM files make the focus called my app VB6 or Windows Explorer.

    I found a curiosity in my research (see link below), but his solution makes no difference for me, and I see no evidence of my application help uses DHTML in any case.

    Any help that can be provided would be greatly appreciated!

    http://forums.madcapsoftware.com/viewtopic.php?f=8 & t = 5239

    PS Edited to add: I use RoboHelp HTML X5.0.1

    Here is the solution to my problem as suggested by Pete lees in another thread about the same problem:
    ===============
    Pete Lees:
    There seems to be something slightly wrong with the ehlpdhtm.js file that is compiled into some (maybe all?) Generated by RoboHelp .chm files. As far as I can see, the JavaScript functions that are responsible for the problem are the bounded by the following two comments in the ehlpdhtm.js file:

    Start supporting the previous call of HHActiveX
    ...
    End to support the previous call of HHActiveX

    These JavaScript functions seem to be responsible for the activation of the HHActiveX DLL, which I believe implements additional RoboHelp features as browse sequences and glossary tab in a .chm file. In any event, if I comment these functions, a .chm file that previously failed to make the focus on the desktop Windows is now. Obviously, however, by disabling these functions I lose the extra features which provides the DLL.

    Pete
    =================
    I put my CHM in comment section Pete mentioned, rebuilt, and now it works fine. I had previously tried idea of Pete to remove the whole construction js file, I am not done correctly but it had no effect.

    Thank you, Pete!

Maybe you are looking for

  • Is it possible to directly connect dish Qosmio G20?

    HY everybody, I have a Qosmio G20-PQG21. The receiver is 60 metres from the position of the laptop. In this case, the channel is not editable. The problem that this person wants to change channels. The problem is quite simple... can I connect the coa

  • LABVIEW FOR LEGO MINDSTORMS

    Hello, I need help. Pls help me with motors to control Robots NXT with NXT buttons. I need change the power of the engines with NXT buttons. How do I achieve this function? Thank you very much for your answer! -In the attachment is the same program b

  • I need to use Word on my laptop when there is no internet connection - is it possible?

    I work in one apartment for disabled elderly and many of them do not have internet, let alone know how to use a computer. I need to put my laptop with a questionnaire that I created in Word and fill it in some of their apartments. How I can do this o

  • Method to get the accuracy of the GPS in meters

    Hi experts, What is a good want to can provide the code to get the accuracy of the current GPS of the device, in meters. Help, please. Best regards, Year s

  • Why SAF queue contains all messages?

    Hi allI have a test business service that publishes to a JMS queue. The queue is in the armed forces of Sudan imported Destinations. I've suspended this queue for transfer, but when I use the SB console to test the service of the company, the message