Focus in Swing

I have 4 textfields TF1, TF2, TF3, TF4 added to a panel.
TF2 has the next focus component as TF4. I set it using setNextFocusableComponent.
So the focus order is TF1, TF2, TF4.
If TF2 is disabled, then the Focus order becomes TF1, TF4.
This is the expected behaviour and works this way in JDK 1.3
But in JDK 1.4, I see that if TF2 is disabled. The focus order is TF1, TF3, TF4.
Is there any way to correct this.
Thanks
Ravi

One of the factors, the order of focus in java depends upon is the order in which u add ur components. By default 'this' is the tab focus order. But you can also set the nextFocusableComponent() to alter this. Sometimes even tius does'nt work, then one has to write his/her own FocusTraversalPolicy, overriding the default policy.
first try the first two .....

Similar Messages

  • Order of focus for swing components

    Hi All,
    I am in search of the way to definine the order of focus for swing components.
    I have a JPanel to which I can add multiple JButtons and JLabels. My problem is that when ever JButton comes, it should get the focus even though JLabel exists.
    If I drag the JButton on to JLabel then also it should be placed on top of the JLabel.
    Can any body help me to solve this problem.
    Thanks in advance,
    Regards,
    Roja.

    Hi,
    I am giving my sample code here.
              if (textButton != null) {
                   setUserTextPresentFlag(true);
                   textButton.setFocusPainted(false);
                   textButton.setContentAreaFilled(false);
                   textButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
                   textButton.setBounds(
                        editPosX,
                        editPosX,
                        textButton.getWidth(),
                        textButton.getHeight());
                        textButton.setRequestFocusEnabled(true);
    //                    textButton.grabFocus();
                        textButton.requestFocus();
    System.out.println("requestFocus isDisplayable::"+userTextImageButton.isDisplayable()+" isEnabled "+userTextImageButton.isEnabled()+" isFocusPainted "+userTextImageButton.isFocusPainted()+" isVisible "+userTextImageButton.isVisible()+" userTextImageButton.hasFocus() "+userTextImageButton.hasFocus());
    I am getting the following values for the system.out.println values.
    isDisplayable::false isEnabled true isFocusPainted false isVisible true userTextImageButton.hasFocus() false
    I didn't find a method to set displayable to true.
    could u find where the problem is?
    Thanks in advance,
    roja.

  • Swing event queue, modal dialogs, event threads, etc...

    Hey all,
    So I am playing around with the focus manager, swing event thread and event queue, etc. Learned quite a bit. I am also playing around with test automation of our UI, using jfcUnit. I have written a few simple apps to play aorund with record/playback, coding tests, etc. What this thread is about though, is figuring out how modal and non-modal dialogs "take over" the event thread/queue? The reason I ask is, if I put a simple test harness like tool embeded in my app as a separate pop-up modal dialog, and from within it there is a GUI that I can use to select a "Test" to run. Now, when I run this test, jfcUnit needs to run on the main window, not within my non-modal dialog. What I am not sure of, however, is that if by using a non-modal dialog all events will go to the main event thread? I mean, I know if I mouse over my second non-modal frame (spawned from the application frame), that events will trigger for that dialog. I remember reading somewhere that modal dialogs "block" the main event queue, all left over events are given to the newly added event queue (presumably by the modal dialog) and existing left-over events get moved to the event queue. If that is the case, I am curious why events for the "old" queue are moved to the new queue if they were orginally intended for the old queue? I would think a "flush" before adding a new queue would be more appropriate so that the old queue can process all of its intended events.
    Now, I am just about to try this, but I am hoping a non-modal pop-up will not interfere with the jfcUnit running the UI of the main window. I am guessing, however, that it might. How are non-modal dialogs handled in terms of events and the event queue? Is it the same as modal dialogs? Or is there no blockage of the mainwindow event queue? If there is no blockage, than any sort of automation based on relative positions to a window may occur on the non-modal dialog, in which case it's best to hide the non-modal dialog during running of these tests.
    What are your thoughts, or better yet, knowledge of this topic? A decent explanation from a developer standpoint and not from the API's which dont give some of the more detailed info I am seeking is what I am hoping to get out of this.
    Thanks.

    Check this out. First, AWTListener has a LOT of
    different types you can register it for. I ORd all
    them together and when I ran my app, it took almost 30
    minutes for it to show up because of the huge stream
    of events being spit out via System.out. ...Yes, that doesn't surprise me in the least. There's hundreds of events that are fired around, usually unbeknownst to the user for every little thing. Lots of component and container events, in particular.
    Just make sure you OR ( using | not || ) ALL the
    "mask" values you want to watch for. That may be why
    you aren't seeing anything. When I did all that, and
    opened a menu, a ton of events came out.Maybe, I'll try that again, but I did specifically add an ActionEvent mask to get action events, and that should be all I need to get action events on buttons or menu items, and it wasn't getting them for either. It was only getting events on buttons when I used SwingEventMonitor, but not menu items.
    So I don't quite understand enough of the underlying event handling. Although, I suspect it could have something to do with the fact that these are Swing components, not AWT components (which their native peers) and it's pretty clear from AbstractButton (or was it DefaultButtonModel) how ActionEvents are fired, and they don't seem to have any connection to the code that deals with AWTListeners.
    My problem is that I kinda need a way to catch events without having a listener attached directly. Normally, I would have a listener, but there's this situation whereby an action may be triggered before I can get hold of the component to attach my listener to it. Perhaps I can get mouse press/release and just deal with it that way.
    Let me know if you did that and still didn't see what
    you were looking for. After playing with this, I am
    guessing the main reason for AWTListener is to
    register a listener for a specific type of event,
    instead of listening to them all, hence avoiding lots
    of extra overhead. Then again, the main event
    dispatcher must do a decent amount of work to fire off
    events to listeners of specific awt event types.Yes, it's definitely that. There's no point in sending events if no one is listening for it, so it does save some time.
    You are right, popup menus I think are dialogs, I
    don't know for sure, but you can access them via the
    JMenu.getPopupMenu() and JMenu.isPopupShowin().
    However, I am still not getting my test stuff working
    quite right.
    Yes, for menu popups. For a JPopupMenu on a right-click on any component (tree or whatever), I had a need to know about that from any arbitrary application (it's this GU testing app I'm working on), and since the popup menu doesn't belong to any component before it's shown, I couldn't necessarily know about it til it was displayed. I managed to use a combination of HierarchyEvents (using an AWTEventListener) and "component added" ContainerEvents. Not a simple matter, but it seems to work well.

  • Weird focus problems (& 1 workaround)

    I am building a wizard with an extension of JDialog. Based on earlier input, I create the JDialog with a bunch of JPanels each with a combobox and a textfield. I have a next, cancel, and back button at the bottom on its own panel. I also have a "Finish" button when I reach the last panel. So I have to change the buttonPanel by putting the finish button on at the end and I put the next button back on when coming back from the last panel.
    The problems I have been running into involve getting focus to one of the JTextfields mentioned above. I had a problem when I built my JDialog after clicking the next button. I removed everything from my ContentPane (cp) using cp.removeAll(). After building my JDialog, my code trys to give focus to the first text field. It wouldn't. I tested the text field and it is indeed focusable, visible, and displayable.
    The fix was removing each individual component from the content pane instead of doing the removeAll(). Then, after adding everything to the content pane, my textfield could grab the focus.
    The only problem that remains is with the back button. When I move back from the final panel the following code is executed:
    buttonPanel.removeAll();
    //buttonPanel.remove(backButton);
    //buttonPanel.remove(finalButton);
    //buttonPanel.remove(cancelButton);
    buttonPanel.add(backButton);
    buttonPanel.add(nextButton);
    buttonPanel.add(cancelButton);
    Then, as in other cases, the buttonPanel object is added to the content pane. This causes the textfield to be unable to grab focus. I commented out the code and the focus worked fine (but of course my buttonPanel was not correct).
    This is happening with 1.4.1 on windows 2000. I don't have another computer to test this one.
    Am I doing something inherently wrong or is this a bug?
    I've looked around and there are a lot of problems reported with focus and swing, but I wasn't sure if this was a symptom of those problems or if this is something different.
    I appreciate any help you can give.
    thanks,
    Geoff

    I won't throw everything at you but this should be plenty. If anyone needs any explanations I am not going anywhere. I'm trying to figure out if the problem is a bug or not.
    The workaround is mentioned in a comment for the action listener of nextButton. The problem piece of code that is mentioned at the top of this thread is also commented and it is part of the action listener for backButton.
    There are some declarations I have left out and I've left out some helper functions and some private classes, but I looked at it closely. There shouldn't be anything that is a mystery here. But, again, if anything is unclear just give a shout.
    thanks in advance,
    Geoff
    public InfoDialog(JFrame owner, int[] results)
         super(owner, "Wizard", true);
         cp = getContentPane();
         this.owner = owner;
         answers = results;
         lastPanel = answers.length-1;
         //figure out number of panels and last one greater than 0
         for(int i =0; i<answers.length; i++)
              numPanels++;
              if(answers>0)
                   lastPanel = i;
         if(numPanels==0)
              return;
         nameVectors = new Vector[answers.length];
         typeVectors = new Vector[answers.length];
         while(answers[currentPanel]<=0 && currentPanel<answers.length)
              currentPanel++;
         firstPanel = currentPanel;
         inputLabel = new JLabel();
         inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
         inputLabel.setText(getInputLabelText(currentPanel));
         panelArray = new JPanel[answers[currentPanel]];
         nameVectors[currentPanel] = new Vector();
         typeVectors[currentPanel] = new Vector();
         comboArray = new ClassComboBox[answers[currentPanel]];
         textArray = new StringTextField[answers[currentPanel]];
         for(int i=0; i<panelArray.length; i++)
              panelArray[i] = new JPanel();
              panelArray[i].setLayout(new BoxLayout(panelArray[i], BoxLayout.X_AXIS));
              comboArray[i] = new ClassComboBox();
              panelArray[i].add(comboArray[i]);
              textArray[i] = new StringTextField(new String(""));
              panelArray[i].add(textArray[i]);
         cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS));
         //cp.add(infoPanel);
         cp.add(inputLabel);
         for(int i=0; i<panelArray.length; i++)
              cp.add(panelArray[i]);
         //infoPanel = new JPanel();
         //infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.X_AXIS));
         //infoPanel.add(new ClassComboBox());
         //infoPanel.add(new StringTextField(new String("")));
         //cp.add(infoPanel);
         backButton = new JButton("Back");
         backButton.setEnabled(false);
         backButton.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent ae){
                   //save values of previous panel into vector
                   typeVectors[currentPanel] = null;
                   nameVectors[currentPanel] = null;
                   typeVectors[currentPanel] = new Vector();
                   nameVectors[currentPanel] = new Vector();
                   for(int i=0; i<panelArray.length; i++)
                        typeVectors[currentPanel].add((String)comboArray[i].getSelectedItem());
                        nameVectors[currentPanel].add(textArray[i].getText());
                   //remove everything from JDialog
                   //cp.removeAll();
                   cp.remove(inputLabel);
                   for(int i=0; i<panelArray.length; i++)
                        cp.remove(panelArray[i]);
                   cp.remove(buttonPanel);
                   //store last panel, figure out what the new currentPanel val is
                   int previousPanel = currentPanel;
                   currentPanel--;
                   while(answers[currentPanel]<=0 && currentPanel >= firstPanel)
                        currentPanel--;
                   //go through panelArray getting rid of its subcomponents
                   for(int i=0; i<panelArray.length; i++)
                        panelArray[i].removeAll();
                   panelArray = null;
                   comboArray = null;
                   textArray = null;
                   //arrays will be initialized to the appropriate length for the currentPanel
                   panelArray = new JPanel[answers[currentPanel]];                    
                   comboArray = new ClassComboBox[answers[currentPanel]];
                   textArray = new StringTextField[answers[currentPanel]];
                   //inputLabel.setText(pinTypes[currentPanel]);
                   inputLabel.setText(getInputLabelText(currentPanel));
                   cp.add(inputLabel);
                   for(int i=0; i<panelArray.length; i++)
                        panelArray[i] = new JPanel();
                        panelArray[i].setLayout(new BoxLayout(panelArray[i], BoxLayout.X_AXIS));
                        comboArray[i] = new ClassComboBox();
                        comboArray[i].setSelectedItem(typeVectors[currentPanel].get(i));
                        panelArray[i].add(comboArray[i]);
                        //textArray[i] = new StringTextField(new String(""));
                        textArray[i] = new StringTextField((String)nameVectors[currentPanel].get(i));
                        panelArray[i].add(textArray[i]);
                        cp.add(panelArray[i]);
                   //focus problem is caused by this block of code
                   //moving back from last panel
                   if((currentPanel == lastPanel-1) && previousPanel==lastPanel)
                        buttonPanel.removeAll();
                        //the following code did not fix the problem
                        //buttonPanel.remove(backButton);
                        //buttonPanel.remove(finalButton);
                        //buttonPanel.remove(cancelButton);
                        buttonPanel.add(backButton);
                        buttonPanel.add(nextButton);
                        buttonPanel.add(cancelButton);
                   if(currentPanel==firstPanel)
                        backButton.setEnabled(false);
                   cp.add(buttonPanel);
                   //System.out.println();
                   //System.out.println("textArray[0].isVisibile: " + textArray[0].isVisible());
                   //System.out.println("textArray[0].isDisplayable: " + textArray[0].isDisplayable());
                   //System.out.println("textArray[0].isFocusable: " + textArray[0].isFocusable());
                   //textArray[0].grabFocus();
                   pack();
                   //repaint();
                   System.out.println();
                   System.out.println("textArray[0].isVisibile: " + textArray[0].isVisible());
                   System.out.println("textArray[0].isDisplayable: " + textArray[0].isDisplayable());
                   System.out.println("textArray[0].isFocusable: " + textArray[0].isFocusable());
                   textArray[0].grabFocus();
         nextButton = new JButton("Next");
         nextButton.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent ae){
                   //logic to grab information from JComboBox and JTextField
                   typeVectors[currentPanel] = null;
                   nameVectors[currentPanel] = null;
                   typeVectors[currentPanel] = new Vector();
                   nameVectors[currentPanel] = new Vector();
                   for(int i=0; i<panelArray.length; i++)
                        typeVectors[currentPanel].add((String)comboArray[i].getSelectedItem());
                        nameVectors[currentPanel].add(textArray[i].getText());
                   //here is the code that didn't work and the subsequent code
                   //that fixed the problem
                   //cp.removeAll();
                   cp.remove(inputLabel);
                   for(int i=0; i<panelArray.length; i++)
                        cp.remove(panelArray[i]);
                   cp.remove(buttonPanel);
                   currentPanel++;
                   //System.out.println("currentPanel prior to processing: " + currentPanel);
                   if(currentPanel<(answers.length-1))
                        while(answers[currentPanel]<=0 && currentPanel<lastPanel)
                             currentPanel++;
                   for(int i=0; i<panelArray.length; i++)
                        panelArray[i].removeAll();
                        //comboArray[i].removeAll();
                        //textArray[i].removeAll();
                   panelArray = null;
                   comboArray = null;
                   textArray = null;
                   panelArray = new JPanel[answers[currentPanel]];
                   inputLabel.setText(getInputLabelText(currentPanel));
                   cp.add(inputLabel);
                   //test to see if this is the first time reaching this point
                   //if you haven't reached this point before, vector will be null
                   boolean firstTime = false;
                   if(nameVectors[currentPanel]==null)
                        firstTime = true;
                   if(firstTime)
                        nameVectors[currentPanel] = new Vector();
                        typeVectors[currentPanel] = new Vector();
                   comboArray = new ClassComboBox[answers[currentPanel]];
                   textArray = new StringTextField[answers[currentPanel]];
                   //establish the proper # of combo boxes & text fields
                   int len = panelArray.length;
                   for(int i=0; i<len; i++)
                        panelArray[i] = new JPanel();
                        panelArray[i].setLayout(new BoxLayout(panelArray[i], BoxLayout.X_AXIS));
                        comboArray[i] = new ClassComboBox();
                        if(!firstTime)
                             comboArray[i].setSelectedItem(typeVectors[currentPanel].get(i));
                        panelArray[i].add(comboArray[i]);
                        textArray[i] = new StringTextField();
                        if(!firstTime)
                             textArray[i].setText((String)nameVectors[currentPanel].get(i));
                        panelArray[i].add(textArray[i]);
                        cp.add(panelArray[i]);
                   if(currentPanel==lastPanel)
                        buttonPanel.removeAll();
                        buttonPanel.add(backButton);
                        buttonPanel.add(finalButton);
                        buttonPanel.add(cancelButton);
                   backButton.setEnabled(true);
                   cp.add(buttonPanel);
                   //textArray[0].requestFocus();
                   //System.out.println();
                   //System.out.println("textArray[0].isVisibile: " + textArray[0].isVisible());
                   //System.out.println("textArray[0].isDisplayable: " + textArray[0].isDisplayable());
                   //System.out.println("textArray[0].isFocusable: " + textArray[0].isFocusable());
                   //textArray[0].grabFocus();
                   pack();
                   //System.out.println();
                   //System.out.println("textArray[0].isVisibile: " + textArray[0].isVisible());
                   //System.out.println("textArray[0].isDisplayable: " + textArray[0].isDisplayable());
                   //System.out.println("textArray[0].isFocusable: " + textArray[0].isFocusable());
                   textArray[0].grabFocus();
         setLocationRelativeTo(owner);
         setVisible(true);          

  • Book on Swing

    I am looking to buy a good book focusing on Swing. Any suggestions? One that I am looking at is "Swing, Second Edition" by Matthew Robinson, Pavel Vorobiev. Is this one any good or are there better ones?

    I've been using the Robinson book and I find it to be excellent. The O'Reilly book is also good, though I'm not as familiar with it as I am with the Robinson book.
    The O'Reilly book does have a section on the UIManager keys, which I haven't seen elsewhere.
    The Robinson book has the best coverage on printing that I've seen.

  • Jupanelbinding bug?

    hello.
    the jupanelbinding doesn´t get the focus if fex. the column of a table is not editable.
    (focusgained-method of jupanelbinding).
    following example:
    we have a combobox and a table (master detail). the table has only not editable columns. so if the combobox has the focus and we click on the table, the focus of the panelbinding doesn´t change. if we make the columns editable, it works fine.
    is there a workaround or something else?
    thx in advance

    In your example the last bound control in focus was combobox. Since the table cells are not enabled, no bound control is in focus. If you want your focused control to be part of the panelBinding status, you may call the panelBinding.displayStatus() apis. If you want to get the current control with focus, using Swing apis to get that info as focus is primarily a View responsibility and Swing panel maintains the current control.

  • MouseListener not responding.

    I'm working on a school project to make a video player/image gallery/Paint rip-off. I'm having a problem with a MouseListener that's not responding and I don't know how to get around it.
    (Note: I know that combining Swing and JavaFX is error-prone and not ideal, however this class focuses on Swing and so we must use it)
    public class DisplayWindow implements MouseListener {
         JFrame frame;
         private MouseListener[] listeners;
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             DisplayWindow window = new DisplayWindow();
                             window.frame.setVisible(true);
                        } catch (Exception e) {
                             e.printStackTrace();
         public DisplayWindow() {
              initialize();
         private void initialize() {
              frame = new Welcome(this);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         @Override
         public void mouseClicked(MouseEvent e) {
              JPanel p = (JPanel) e.getSource();
              switch (p.getName()) {
              case "videoPanel" :
                   System.out.println("run videobrowser");
                   break;
    public class Welcome extends JFrame {
         public JPanel imagePanel;
         public JPanel videoPanel;
         public JPanel doodlePanel;
         DisplayWindow listener;
         public Welcome(DisplayWindow listener) {
              this.listener = listener;
              getContentPane().setBackground(Color.DARK_GRAY);
              setBounds(100, 100, 800, 600);
              videoPanel = new JPanel();
              videoPanel.setName("videoPanel");
              videoPanel.addMouseListener(listener);
              FlowLayout videoLayout = (FlowLayout) videoPanel.getLayout();
              videoLayout.setAlignment(FlowLayout.LEFT);
              videoLayout.setHgap(-5);
              videoLayout.setVgap(-5);
              Dimension d = new Dimension(243, 163);
              File videoFile = new File("footballfail.mp4");
              try {
                   imagePanel.add(new WelcomeImageLoader(imageFile, d));
                   doodlePanel.add(new WelcomeImageLoader(doodleFile, d));
                   videoPanel.add(new WelcomeVideoLoader(videoFile, d));
              } catch (IOException e) {
                   e.printStackTrace();
              getContentPane().setLayout(groupLayout);
    public class WelcomeVideoLoader extends JPanel {
         public WelcomeVideoLoader(File videoFile, final Dimension d) {
              Media media = new Media(videoFile.toURI().toString());
              final JFXPanel jfxPanel = new JFXPanel();
              //final Dimension dim = d;
              final Group root = new Group();
              MediaPlayer player = new MediaPlayer(media);
              player.play();
              player.setCycleCount(MediaPlayer.INDEFINITE);
              player.setMute(true);
              MediaView view = new MediaView(player);
              DoubleProperty width = view.fitWidthProperty();
              DoubleProperty height = view.fitHeightProperty();
              width.bind(Bindings.selectDouble(view.sceneProperty(), "width"));
              height.bind(Bindings.selectDouble(view.sceneProperty(), "height"));
              view.setTranslateX(13);
              view.setPreserveRatio(true);
              root.getChildren().add(view);
              Platform.runLater(
                        new Runnable() {
                             @Override
                             public void run() {
                                  Scene scene = new Scene(root, d.getWidth(), d.getHeight(), Color.valueOf("#404040"));
                                  jfxPanel.setScene(scene);
              super.add(jfxPanel);
    }The video is looping fine in videoPanel but as I said before, MouseListener is no longer responding. I have more JPanels (images, not videos, so I don't have a problem with threads interfering) in class Welcome but I didn't include them to keep the code short. Their MouseListeners are responding though.
    Does anyone know why the MouseListener on videoPanel is not responding and what I can do to fix this? I'm still new to programming, so if you know the answer, please explain it like you're explaining it to a chimp.

    I mocked up something similar to try to see what is going on. It appears that adding a mouse listener directly to a JFXPanel will work, but the mouse event will not get propagated to a JPanel that contains the JFXPanel. In your case, your JFXPanel is contained in a JPanel (the WelcomeVideoLoader), which is contained in the videoPanel, to which the mouse listener is attached. I think you somehow need to arrange for a mouse listener to be registered with the JFXPanel.

  • JMenu, Hotkeys & Action Listener

    If I set a JMenu Hotkey, it will activate whenever I press it (not just when the menu is open). I don't want the hotkey to activate when I'm typing elsewhere outside the menu (ex: JTextField). I don't want to have to use CTL+hotkey for everything on my menu.
    Any Suggestions?
    Here's example code of what I am currently doing
        fileMenu = new JMenu("File");
        fileMenuItem1 = new JMenuItem("Open", KeyEvent.VK_O);
        fileMenuItem2 = new JMenuItem("Save", KeyEvent.VK_S);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        fileMenu.setFont( menuFont );
        fileMenuItem1.setFont( menuFont );
        fileMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));# Don't want to do this for each item
        fileMenuItem1.addActionListener(this);
        fileMenu.add(fileMenuItem1);
        fileMenuItem2.setFont( menuFont );
        fileMenuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
        fileMenuItem2.addActionListener(this);   
        fileMenu.add(fileMenuItem2);
    etc...
      public void actionPerformed(ActionEvent e)
        String arg = e.getActionCommand();     
        System.out.println("KEY PRESSED: "+arg );# Should only print when 'File' Menu is open...not all the time
        etc..
      }

    If I set a JMenu Hotkey, it will activate whenever I
    press it (not just when the menu is open). I don't
    want the hotkey to activate when I'm typing elsewhere
    outside the menu (ex: JTextField). I don't want to
    have to use CTL+hotkey for everything on my menu.
    If you want the Ctrl+hotKey swallowed then your component must be the one that grabs it. So your JTextField would need to understand what Ctrl+O means. I assume you want to use Ctrl+hotKey inside the JTextField or some other text component for something other than what the menu does. That means you need to manipulate the InputMap(s) and ActionMap of the component in order to reroute that ctrl+hotKey to some other action.
    If you don't handle the key in the component that has keyboard focus, then Swing passes that event up the containment hierarchy which allows containers of that component to process the key event. So what's happenning is when you push Ctrl+hotkey in a JTextField, since he doesn't understand what Ctrl+hotkey is, Swing walks the up to the parent of that component and allows it to try to process the event. Eventually it gets to the JMenuBar which has a hotkey set, so that action is fired. (JMenuBars have InputMaps and ActionMaps too).
    Here is some example code to futher illustrate. Grab this and throw it in a public static void main(), Try typing Ctrl+O and Ctrl+P in the JTextField. See how the KeyEvents are handled?
            JTextField field = new JTextField( 20 );
            field.getInputMap( JComponent.WHEN_FOCUSED ).put( KeyStroke.getKeyStroke( KeyEvent.VK_O, KeyEvent.CTRL_MASK ), "doSomething" );
            field.getActionMap().put( "doSomething", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("I did something.");
            JPanel panel = new JPanel( new FlowLayout( FlowLayout.LEFT ) );
            panel.getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ).put( KeyStroke.getKeyStroke( KeyEvent.VK_P, KeyEvent.CTRL_MASK ), "doSomething2" );
            panel.getActionMap().put( "doSomething2", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println( "The Panel is doing something!" );
            panel.add( new JLabel( "Enter something: ") );
            panel.add( field );
            JFrame frame = new JFrame();
            frame.setContentPane( panel );
            frame.pack();
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setVisible( true );Read more about Key Handling in post 1.3 java here:
    http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

  • My Comparison of some IDEs in UI Design.

    Hello, all. Right now I am trying to develop some complex UI for an application, and I tried several IDE to do that.
    Eclipse - Visual Editor is shit, it does not support XY Layout, which is very convienent and important for UI designers.
    JBuilder - for some point JBuilder is best - it supports XY Layout, and what's more? You can use XY Layout first, and later on, switch back GridBagLayout! JBuilder tries to do data transfer for you - the components on the frame is almost the same as it is placed with XY Layout! In this way, you are not restricted by some uncommon packages; for other points JBuilder is not best - It is not very steady, if the source code of Java files becomes larger, when I click design button, and tried to see my result, it crashes!
    IntelliJ IDEA - I don't know how to describe my fealing. It introduces some new ideas by using XML as well as Horizental Spacer and Vertical Spacer. But when I look at the code, there is nothing about component properties.
    NetBeans - Well, It supports several good Layouts - Free Layout and Null Layout etc. But if you use these layout, you are bound to some paticular packages, although NetBeans does provide some automatically insertions into jar files.
    Sun One Studio - I am going to try that........................
    Well, above is only some grouse of a novice UI programmer, sorry to waste your time if you don't like it. Anyway, I tried to find and download and install and run some programs and compare resulsts on three IDEs today, and going to try another one. BTW, I use Eclipse for common coding.

    I am looking forward to hearing about your experience with Sun One Studio. I have primarily been using eclipse for coding but recently started a project where the team had been using JBuilder for coding. I got acquainted with JBuilder and began to develop a front end with it. I have gotten some functioning SWING mockups up rather quickly. However, all of my hopes came tumbling down when trying to use the IDE to work with JTabbedPanes. Eclipse's Visual Editor seems to have good support for JTabbedPain, however, like you indicated, I saw no support for the XYLayout manager which I used in JBuilder.
    Boy, I come from VB, VC++ and .Net world and UI development with these technologies is much, much easier. Looking forward to your experience on Sun One, which by the way, I have also tried, but, at the time, not focused on SWING development.

  • EXPERTS: Prevent 'LostFocus' Advanced

    hi,
    i need expert help by the following question:
    how to prevent a 'lost-focus' AND get a pressed control (ex. buttons)
    correctly repainted/initialized.
    sample situation:
    you have a text-control and a button. the text-control has the focus. whenever you press the button the text-control should not lost his focus and the button should fall back to a normal optic.
    my solution (not complete)
    private void myText_LostFocus(){
       //*** prevent a lost-focus ***
       javax.swing.SwingUtilities.invokeLater(new Runnable(){
          public void run(){
             myTxt.setRequestFocusEnabled(true);
             myTxt.requestFocus();
    }my solution prevent a lost-focus but the button stay with a PRESSED OPTIC. Every try to repaint/initialize the button doesn't work!
    thx for any idea
    oliver scorp

    hi again,
    i found the mistake!
    it was not a question of the lost-focus-solution. the problem was created by opening a modal dialog from the button who normally get the focus.
    the solution is to create an asyncron dialog (in his own thread) in 'action_performed' by the button.
    cu
    oliver scorp

  • SWT Table + CCombo

    Hi,
    I've added a CCombo to my SWT table using TableEditor. However, the background is different from the TableItem. Especially when I do a mouse over and the TableItem changes colour while the CCombo background remains white. Any idea on how to fix?
    Thanks.

    You're better off finding a SWT forum and asking there. These GUI related forums on this site are focused on Swing ( with some awt) and there just aren't a lot of regular contributors here that I am aware of that use SWT.

  • Ceranith, your pretty good at answering my questions...heres a quick one...

    Okay, I set a background for the main part of my frame(I have a small little black backgrounded panel at the bottom), and that works fine, but when I go to add all of my paintComponent stuff...it just erases the background in a way, and puts its old dull gray thing back. I have to go to bed real soon, but is there a quick fix for this? Like should I do another set background or something, or should I just make a big rectangle to fill the screen(I was thinking about this, but I REALLY rather do it a 'better' way...)
    Thanks

    Well I'm kinda learning basic graphic concepts while also trying to make a game...doesn't seem that hard the way I'm going, but I could be wrong.
    I figure I should try to focus on swing rather than AWT since Sun will be working on making Swing really good...
    Oh, for the super.paintComponent(g) where do I put that in here? :
    public class GUI extends JComponent{
         Image image;
         Graphics2D g2d;
         public void paintComponent(Graphics g){
              if(image == null){
                   image = createImage(getSize().width , getSize().height);
                   g2d = (Graphics2D)image.getGraphics();
                   g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
              g.drawImage(image , 0 , 0 , null);
    }In the if statement that gets called once, or out of it that gets called a lot?
    Thanks

  • Ground Zero

    Hello,
    I'm sure this has been asked before. I am new to programming and I'm starting with Java. Other than the tutorials on Sun's site does anyone have a suggestion for a book. Most of the books I find are more for learning Java rather than learning to program from nothing, using Java. Once I learn the basics I would like to focus on swing applications/GUI and software integration. Any input would be great.
    Thanks,
    77

    Try "Professional Java User Interfaces" by Marinilli. It goes about explaining the design patterns and practices used to design and implement Java user interfaces.
    First you'll need to learn the language itself otherwise most books on building software with Java assume that you're already familiar with it. They like to keep language practicality and software development materials like design patterns separate.

  • Problem About Focus transfer in swing JTable Cell

    I open a JDialog in KeyPressed Event of Cell of the JTable,when the JDialog closed, I cannot set the Focus to next Cell in my code. the focus was set on the ToolBar(I don't write it in my code).
    key pressed
    void this_keyPressed(KeyEvent e) {
    String text = this.getText().trim();
    if(e.getKeyCode()==10 && text.trim().length()>0)
    wzdlg = new JDialog();
    Dimension dlgSize = wzdlg.getPreferredSize();
    wzdlg.setLocation(0,0);
    wzdlg.setModal(true);
    wzdlg.pack();
    wzdlg.show();
    //When JDialog Closed,Focus move to next cell
                   //table.editAt(0,1); //cannot getFocus
                   //following cannot get focus too
         Component comp = ((DefaultCellEditor)table.getCellEditor(0,1)).getComponent();
         if (comp instanceof javax.swing.JTextField) comp.requestFocus();               
    Why? How Can I do?

    Try calling prepareEditor after your editCellAt method. It would be like
    JTable.editCellAt(row, col);
    JTable.prepareEditor(theTextFieldComponent, row, col);
    Here, the text field component would be from the component editor. I would recommend you holding a reference than doing a getComponent. But, both may work.

  • Swing Applet - Internet Explorer - Focus issue - tool tips

    Hi ,
    We are using Swing applet in IE Browser , except this swing component rest of the components in the browser are HTML/DHTML components.
    and we are having issue focus issue with this swing components ,
    once immediately after launching the swing applet , the UI components are having some focus issue , if I bring the mouse on top of the swing UI components , we couldn't able to see the tooltips(flyover text) of those Swing UI components.
    However if we click some where on the Swing applet frame , we are able to see these tooltips(flyover text) .
    It looks like a kind of compatibility issue between swing and IE browser .
    I am trying to find a solution for this issue , so that once after launching the applet , tooltips will work without need to click on the applet bar.
    Can somebody share some thoughts on this issue??
    Thanks,
    Bonthu.

    As a wild guess you are mixing Swing and awt components which is a big no-no and among other things can cause repainting, refreshing issues.
    If you want more help then that you need to post some code that shows us what you are doing.

Maybe you are looking for

  • Text in outgoing emails

    I have been using my MacBook Pro for several months now and have had the same account linked to the mail icon as my yahoo account. Over the last few months I have been experiencing trouble with my yahoo account only when sending outgoing emails using

  • Best Practice for where to apply ACL's on a router

    I have a 1760 router with a 4 port ethernet card. It has the Vlan1 int on it for f0/0 in the IOS. I need to apply an ACL to that interface/subnet with the phyical cable in f0/0 and ip range of vlan1. When appling the ACL should I apply it to the phys

  • Strage shortcut win+space , cs6 and cc

    hi i found a strange shortcut i load a 5d mark 2 image , and i zoom in 100% after i selected the hand tool i kept the windows key down+left mouse click it's weird , it display a rectangle and zoom in different place of the image might you please chec

  • How to convert text to outline in photoshop elements 11

    I need to give my business card file to my printer to print, and for some reason I cannot find the convert text to shape option (it is not visible under layer-type as all my googling suggests). I basically need to do this as the printer doesnt have m

  • Problems with adobe flash addon

    I have updated Firefox and also installed the latest updates for Flash and Shockwave from Adobe. However, when I go to Tools, Add-ons, and select "find updates" it keeps showing that my Shockwave Flash plugin is not up to date, and sends me to an Ado