Giving focus to a JPanel

I need to give the keyboard focus to an object, myJPanel, that extends JPanel. Calling myJPanel.isFocusable returns true, but when I try to give that object the focus with myJPanel.requestFocusInWindow, that method returns false and focus isn't transferred. Anybody have some ideas on what I'm doing wrong?
Thanks in advance.
--Jay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Thanks for the help, both of you. What's driving me nuts is that the JPanel already is focusable, at least according to the isFocusable method. Code like this:
System.err.println(this.isFocusable());
this.setFocusable(true);
System.err.println(this.isFocusable());
System.err.println(this.requestFocusInWindow());
prints out "true true false false." Apparently it is possible to give my JFrame the focus, but I'm just not doing it correctly. Also, I did call addKeyListener, but this is my first time using KeyListeners and it's totally possible I screwed that up too. Regardless, if the JFrame that's supposed to be listening for KeyEvents doesn't have the focus, then it won't pick up those KeyEvents whether the listener is set correctly or not. (At least, that's my reading of the Java documentation.)
Anyway, thanks for your advice, and any more ideas would be totally appreciated.
--Jay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Giving focus to a component

    Hi all,
    How does one give focus back or just plain giving focus to a JComponent
    e.g. JTextField, JButton, etc.
    This puzzles, me please help?

    That method was introduced in 1.4, but the API recommends you use requestFocusInWindow()

  • Giving focus to the program

    I need to make a Java program give focus to itself.
    I'm thinking of a thread that would give focus to the program every second.
    But I dont know how to make it "give focus to this program on the computer". With my searches, I can only find about giving focus to a component of the program, not the program in the computer/os
    The program will run in Windows, so something platform specific would be ok.
    Or any other way to make this Java program regain focus automatically about every second.

    In brief, I need to do it for a barcode system. It's somewhat complicated, the commerce system uses php and is online. In this system, I added an applet which recieves events from a local program (the one I want to auto-focus).
    This local program recieves events from the barcode scanner. But a barcode scanner is stupid, and considered like a keyboard for the computer, so a program must be in focus to recieve the events. The best solution I could think of is to make this local program always takes the focus. The interface of this program would be small (or no interface at al).
    All of this system is done and works correctly. The only piece of this puzzle that is missing is having the local program always recieve events from the scanner.
    The computer that will run it is the "cash regitster" computer for the store, so having this local program always gaining focus is correct. And if needed, this "auto-focus" could be deactivated while the computer is needed for other things.
    So the real point is maning sure the local program gains focus about every second so it recieves the events of the scanner, since the scanner is considered like a keyboard.

  • How to have focus in 2 JPanels on 1 JFrame?

    Hey all..
    Like i wrote in the subject, how can i do that?
    I have 2 JPanels in 1 JFrame. 1 top JPanel and 1 buttom JPanel. I've a keylistener in top JPanel and a buttonslistener in buttom JPanel. When i press on the button on the buttom JPanel, then my keylistener wont trigger in the top JPanel.
    Plz help.
    Thx.

    The whole point to window focus is to avoid this! There is at most one focused component per window.
    As a rule of thumb, when someone uses a KeyListener, they're mistaken. You should be using key binding. This can make your focus problems go away, since you can choose to associate the keyStoke with the whole window, not just the focused component.
    [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]

  • Detect Focus transfer between JPanels

    I have an app that has a scrollpane containing a JPanel (A), that contains a bunch of JPanels (B) - each of which contains multiple controls, panels, etc....
    I want to make sure that whichever JPanel (B) has the focus in it, and use the viewPort.scrollToVisible() to make sure that panel is fully displayed.
    So far, the only way I've seen to do that is to add a FocusListener to each and every control and check to see which panel it's in.
    BLECH!
    Is there an easier way?
    I'd really like some kind of listener that is just notified whenever focus transfers between the upper level Panels.

    Thanks to all. Re-read those sections, and came up with this little utility class to do what I needed.
    It listens for focus changes between panels, and notifies a listener of these changes.
    import java.awt.Component;
    import java.awt.KeyboardFocusManager;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    * Tracks the focus for Panels.  If the focus enters or leaves the panel (i.e. focus goes
    * to/from any component in the panel, and from/to anything outside the panel)
    * It notifies any listeners of the event.
    * @author jlussmyer
    public class PanelFocusTracker {
        /** Array of panels we are tracking focus changes for. */
        private JPanel[] panels = new JPanel[0];
        /** Which of our tracked panels currently has the focus */
        private JPanel curFocus = null;
         * Constructor.  Ties into focus handling system.
        public PanelFocusTracker() {
            KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            focusManager.addPropertyChangeListener(
                    new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent e) {
                            String prop = e.getPropertyName();
                            if (("focusOwner".equals(prop)) && ((e.getNewValue()) instanceof Component)) {
                                Component comp = (Component) e.getNewValue();
                                checkForPanelChange(comp);
            return;
         * Check to see if focus going to his component changes which containing
         * panel has the focus.
         * @param comp Component that is gaining focus.
        private void checkForPanelChange(Component comp) {
            JPanel gainPanel = getPanelForComponent(comp);
            if (gainPanel == curFocus) {
                return; // no change, nothing to do.
            if (curFocus != null) {
                notifyListeners(curFocus, false); // This panel lost focus
            if (gainPanel != null) {
                notifyListeners(gainPanel, true); // This panel gained focus
            curFocus = gainPanel;
            return;
         * Finds which of the panels we are tracking contains the given component.
         * @param comp Component to find containing panel for
         * @return Containing Panel, null if it isn't in one of the panels being tracked.
        private JPanel getPanelForComponent(Component comp) {
            JPanel result = null;
            while ((comp != null) && (result == null)) {
                if (isBeingTracked(comp)) {
                    result = (JPanel) comp;
                } else {
                    comp = comp.getParent();
            return result;
         * Checks to see if this is one of the JPanels we are tracking.
         * @param comp Component to check
         * @return true if it's a JPanel that we are tracking.
        private boolean isBeingTracked(Component comp) {
            boolean result = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (comp == panels[idx]) {
                    result = true;
                    break;
            return result;
         * Add a panel to the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to track focus for.
        public void addPanel(JPanel panel) {
            // Don't allow the same panel to be added multiple times.
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    panel = null;
                    break;
            if (panel != null) {
                JPanel[] temp = new JPanel[panels.length + 1];
                System.arraycopy(panels, 0, temp, 0, panels.length);
                temp[panels.length] = panel;
                panels = temp;
            return;
         * Remove a panel from the list of panels being tracked for Panel Focus
         * changes.
         * @param panel Panel to stop tracking focus for.
         * @return true if panel was being tracked, false otherwise.
        public boolean removePanel(JPanel panel) {
            boolean found = false;
            for (int idx = 0; (idx < panels.length); idx++) {
                if (panel == panels[idx]) {
                    found = true;
                    JPanel[] temp = new JPanel[panels.length - 1];
                    if (idx == 0) { // removing first entry
                        if (temp.length > 0) {
                            System.arraycopy(panels, 1, temp, 0, temp.length);
                    } else if (idx == (panels.length - 1)) { // remove last entry
                        System.arraycopy(panels, 0, temp, 0, temp.length);
                    } else { // Remove something in the middle
                        System.arraycopy(panels, 0, temp, 0, idx);
                        System.arraycopy(panels, idx + 1, temp, idx + 1, temp.length - idx);
                    break;
            return found;
         * Remove all JPanels from focus tracking.
        public void removeAllPanels() {
            panels = new JPanel[0];
            curFocus = null;
            return;
         * Interface for listeners to be notified of focus being gained/lost by
         * any of the panels being tracked.
        public interface Listener {
            /** Focus Lost by given panel */
            void panelFocusLost(JPanel panel);
            /** Focus gained by given panel */
            void panelFocusGained(JPanel panel);
        /** Listeners to be notified of Panel Focus changes */
        private ArrayList<Listener> focusListeners = new ArrayList<Listener>();
         * Add a listener to be notified of changes to the Focus for any Panel
         * being tracked.
         * @param listener Listener to be notified for Panel Focus changes.
        public void addListener(Listener listener) {
            focusListeners.add(listener);
            return;
         * Remove a Panel Focus listener.
         * @param listener listener to no longer be notified of Focus changes.
         * @return true if listener found, false otherwise.
        public boolean removeListener(Listener listener) {
            return focusListeners.remove(listener);
         * Notify all registered listeners of a Panel Focus change.
         * @param panel panel that gained/lost focus.
         * @param gained true if focus gained, false if focus lost.
        private void notifyListeners(JPanel panel, boolean gained) {
            Listener[] list = focusListeners.toArray(new Listener[focusListeners.size()]);
            for (int idx = 0; (idx < list.length); idx++) {
                if (gained) {
                    list[idx].panelFocusGained(panel);
                } else {
                    list[idx].panelFocusLost(panel);
            return;
    }

  • Giving "focus" to a folder in Mail: only with the keyboard?

    Hello everybody,
    I've found that in Mail, you can choose a folder with the mouse, but that you cannot activate it, you cannot give it the focus.
    When you click on a folder, it becomes pale blue and the arrow keys do not allow to go from one folder to the other. The focus is in the mails pane.
    The only way to give the focus to a folder is through the keyboard, using Shift-Tab (or Tab several times): the folder then becomes dark blue, it "has the focus", and the arrow keys allow to go from one folder to the other, or to open and close folders.
    This is an interface issue, and is highly unusual. Am I the only one to observe this?
    If I am the only one, then I have a bug somewhere. If not, Mail has an interface problem that I will report to Apple, hoping for the best.
    Thanks for your input, and Cheers!
    Roger the Photographer
    G5 1.8Dual, 2GB RAM   Mac OS X (10.4.8)   20" App Dsplay, ext. Lacie, iPod, Bach on Al-Lansing, Canon 5D, Canon L glass

    Hello Roger.
    What you’ve described is exactly how it works.
    Although I agree that this is non-standard behavior,
    I have the feeling that it’s intentional, not a bug.
    There are other situations in Mail where the view
    that handles the keystrokes is what the user is most
    likely to want rather than what has focus.
    If you have the preview pane visible, for example,
    and the view that has focus is the message list, the
    arrow keys let you select another message, but the
    Page Up/Down keys are handled by the preview instead,
    regardless of whether it has focus or not. Only if
    the preview pane is hidden does the message list
    respond to Page Up/Down keystrokes.
    Hi David,
    I've just discussed the thing rather extensively with an ex-senior scientist at Apple. I think that he is right - as you are -, this is intended behaviour.
    Whether it is a good idea or not is a different matter however. Apple's keyboard commands have never been as complete, or precise, as Microsoft's. Remark that this is not a compliment to Microsoft whose interface is at times simply terrible! But here, it's not the keyboard command policy that is not systematic, it's the response of the mouse. And this I find very surprising. I have 51 mailboxes in Mail and the more control I have, the happier I am, that's for sure!
    On the other hand, what surprised me is the fact that the mouse does not respond in the same way in, say, Mail and iTunes. In iTunes, if you click on a "folder" (they call them playlists, which is fine, but this is about the same as a folder is it not?), not only you select it, but you activate it: you give it the focus plain and simple.
    Look at Font Book: here also, you have what a power user is waiting for: clicking on a "folder", or a list or group, you give it the focus plain and simple. Idem in Address Book. iPhoto also, but then it's the tab key behaviour that's strange.
    I can see from here programming teams clashing over points like this one. I would greatly prefer that Apple's applications adopt a predictable behaviour from one app to the other.
    "Behaviour by design", all right. I will nonetheless send to Apple what we could call an "enhancement request".
    Cheers!
    Roger the Photographer
    G5 1.8Dual, 2GB RAM   Mac OS X (10.4.8)   20" App Dsplay, ext. Lacie, iPod, Bach on Al-Lansing, Canon 5D, Canon L glass

  • Giving Focus To Process

    I am creating a program that reads commands from a txt file and uses them to run processes (other .exe's).
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.*;
    import cs1.*;
    import javax.swing.*;
    public class Test
    public static void main(String[] args)
    Runtime rt = Runtime.getRuntime();
    Process child = rt.exec(callAndArgs);
    PROBLEM: I am going to be using the robot class to manipulate the process. But sometimes the process (say notepad.exe) does not come up with focus...the console window stays on top. Robot's activities are therefore misdirected. How can I set focus to the process? I have tried running without the console at all...no good.
    thanks!
    D Rice

    I have used this and it leaves it with focus, modify the YourApp for the executable, I put it there so you would know where.....
    StartCommand = "cmd.exe /c start" + " " + YourApp;
    Runtime rt = Runtime.getRuntime();
         try
         child = rt.exec(strFullCommand);
         catch(IOException e)
         System.err.println( "IOException starting process!");
         }

  • Giving Focus to Window/Frame

    Hi
    I am unable to give focus to newly opened window/frame
    How can I do it? A quick reply would be appreciated as I need it urgently
    Thanx in advance
    jods

    When you initialize the Window/Frame set it to focusable with setFocusable(true) and then simply call requestFocus()

  • Giving focus with mutpile JTextFields

    Hey,
    if i have two JTextFields, is it possible for me to give focus to a different one than the one at the top? I.e, i have three text fields, however i dont want to focus to go to the top one (which it does by default), i would like to give the second one focus, is this possible at all? Thank you!

    so, would it look like
    oldField.requestFocus;[ ? (oldField being the textfield)
    or is there more to it? (thanks for the reply btw ^^)

  • Giving focus to JTextfield or JTextArea

    Hello,
    I want to know how to give the focus to a JTextField.To be more precise,
    I would like the cursor to be placed in the JTextField or JtextArea so the user does not have to click on the field and then enter a text.I must specify there a lot of components in my panel(JComboBox,JLabel,JList,JTextField).
    I tried jText.setFocus(),jText.setFocusable(true), and all the other focus' methods but it doesn't work.I also tried the caret method.
    Thanks in advance.

    This thread may explain your problem:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=290339

  • Removing and restoring Focus to a JPanel

    Hi,
    I am working on a Tetris game in Java and I want to have a button that can pause the game and restore it. Everything works fine so far, I can get the blocks to stop and resume moving downward. However while the game is paused the player can still move the blocks left and right. I know this is happening because I called setFocusable(true) in my init() method of my JApplet and setFocusable(false) on the JButton, so the focus is always set to manipulate the blocks, but I am unsure how to get it to work so that calling a method will remove and restore Focus on the game.

    Add code to the ActionListener:
    If (notPaused)
       moveBlocks();

  • Requesting focus for JTextField inside JPanel

    I have an application with following containment hierarchy.
    JFrame --> JSplitPane --> JPanel.
    JPanel is itself a seperate class in a seperate file. I want to give focus to one of the JTextfields in JPanel, when the JPanel is intially loaded in the JFrame. I believe that I cannot request focus until the JPanel is constructed. I can set the focus from JFrame (which loads JPanel) but I want to do this from JPanel. Is there any technique to request focus from the JPanel itself (preferably during JPanel construction).
    regards,
    Nirvan.

    I believe that I cannot request focus until the JPanel is constructedYou can't request focus until the frame containing the panel is visible. You can use a WindowListener and handle the windowOpened event.

  • [Flex 4.5.1] Focus on TextInput hides windows 7 language bar when in Chrome, Firefox works fine

    Focus on TextInput hides windows 7 language bar when in Chrome (latest version by the time of the writting) - very odd behavior, if the user clicks away from the flex app then the language bar reappears but even if you change the language if you focus back on the application the language is back to what it was the last time the application was focused, though you can't actually see this since the language bar is gone.
    This is kind of a serious bug since an avarage user probably would't be able to change the language with key combinations...
    Does someone know anything about this issue ?

    Actually giving focus on the entire flex application results in hiding the windows 7 language bar in chrome. I just reported this. Here is the link for the bug + an extra issue:
    http://bugs.adobe.com/jira/browse/SDK-32039

  • Robot not working after another app gains focus

    I'm trying to automate some clicking for a program using Robot. The problem is, once I give focus to the target program, Robot stops working (so basically, the initial click into the program works, but it's useless if I can't release the mouse). Intuitively, it seems like the target program has somehow gained a higher priviledge to control the mouse or something if it has focus. Programmatically giving focus back to the java program after every event won't work. Is there a way to fix this, or should I try something more native to Windows like C#?
    This target program has a 3D interface and it uses DirectX and stuff, which might be why it (can) eats up control of the mouse. However I just think it's badly programmed, I tried doing some Robot stuff on a game and it seems to work.

    billyboy:
    How are you checking to see if it works? If you have an application that is processing the click events, and another application covers it, then it will no longer see the click events.
    This code:
    import java.awt.AWTException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.awt.Point;
    import java.awt.Robot;
    import javax.swing.Timer;
    public class JRobot implements ActionListener{
      Robot r;
      Timer t = new Timer(200, this);
      Point p = new Point(512, 512);
      boolean bTime = false;
      int iCount = 0;
      public JRobot(){
        try{
          r = new Robot();
          t.start();
        }catch(AWTException e){
          System.out.println(e.toString());
      public static void main(String[] args) {
        new JRobot();
      public void actionPerformed(ActionEvent e){
        if(bTime){
          p.x = 256;
          p.y = 256;
        }else{
          p.x = 512;
          p.y = 512;
        int iState = iCount%6;
        switch(iState){
          case 1: r.mouseMove(p.x, p.y);
                  break;
          case 2: r.mousePress(InputEvent.BUTTON1_MASK);
                  break;
          case 4: r.mouseRelease(InputEvent.BUTTON1_MASK);
                  break;
          case 5: bTime = !bTime;
          default:
        if(iCount>=100) System.exit(0);
        iCount++;
        System.out.println(iState+" x " + p.x + " y "+ p.y);
    }Does keep running and does click and release. I suspect your's is also. If you put one object at (256, 256) and another at (512, 512) you will soon see that they are alternatly chosen and gain and release focus appropriatly, but if one object is on top of the other, then the top object will recieve the click events.

  • HOW TO: SDI + Default Focus + CardLayout + jdk1.4

    Hi,
    I need some help to solve some focus issues.
    I use jdk 1.4.1_01 and Win2000
    I have a SDI application composed with:
    < = include
    JFrame < JScrollPane < JPanel (CardLayout) < JPanel 1 < JTextField11 *
    | | < JTextField12
    | | < JTextField13
    | < JPanel 2 < JTextField21 *
    | | < JTextField22
    | | < JTextField23
    | | < JTextField24
    | < JPanel 3 < JTextField31 *
    | < JTextField32
    | < JTextField33
    | < JTextField34
    | < JTextField35
    < JToolBar < JButton 1
    < JButton 2
    < JButton 3
    When you push :
    JButton 1 -> JPanel 1 is displayed
    JButton 2 -> JPanel 2 is displayed
    JButton 3 -> JPanel 3 is displayed
    I need to set the focus like this:
    So when you push :
    JButton 1 -> JPanel 1 is displayed AND JTextField11 get the focus
    JButton 2 -> JPanel 2 is displayed AND JTextField21 get the focus
    JButton 3 -> JPanel 3 is displayed AND JTextField31 get the focus
    How can i do that??? I tried several solution find here in the forum but no way... :((
    I need some help.
    JMi

    ok, done with requestFocus()

Maybe you are looking for

  • Broadband drops 'out' more than 'in' - OpenReach a...

    First, forgive me if a similar problem has been posted; I've had to resort to a 2G O2 dongle & speeds are so bad that I can't search the forum.  For weeks (months?) now I've had terrible broadband connectivity - sometimes going for days without a con

  • Just want to copy, not move

    I need to locate different groups of photos by various criteria, then simply copy these images to various folders on an external hard drive. Originals stay where they are and the copies in the new directories are not to be included in the current lib

  • QuickTime Pro: Audio Settings disabled

    I'm trying to add background music to a video in QT, and need to lower the volume so it doesn't drown out the narration. Went into Properties, clicked on "Audio Settings" & none of the options will do anything. Everything's either grayed out or unres

  • Eprint Enteprise Setup

    Hello! We are currently doing a POC with Eprint Enterprise 2.1 for our business.  We are using this to control printing to iOS devices (iPads, iPhones). I have installed Eprint Enterprise 64 bit 2.1 version on a Windows Server 2008 R2 installation. A

  • Does Media Encoder come with Premiere CC standalone?

    Anything else bundled? Thanks