Keeping focus in the viewable window of a scroll pane

I have many text fields and text areas inside a scroll pane. When I use tab to cycle through these boxes the focus goes out of the viewable window rather then the scroll pane moving to follow the focus. Is it possible for the scroll pane to follow the focus? I would think it is. But I haven't been able to figure out how. Any ideas?
Thanks,
Mark

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class test extends JFrame {
  FieldListener fieldListener = new FieldListener();
  final static int fieldNumber = 15;
  JPanel panel;
  public test() {
    super("Focused Scrolling");
    panel = new JPanel();
    panel.setLayout(new GridLayout(0,1));
    JTextField textField;
    for(int i = 0; i < fieldNumber; i++) {
      textField  = new JTextField("TextField # " + i);
      textField.addFocusListener(fieldListener);
      panel.add(textField);
    JScrollPane scrollPane = new JScrollPane(panel);
    getContentPane().add(scrollPane, "Center");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300,200);
    setLocation(350,200);
    setVisible(true);
  class FieldListener extends FocusAdapter {
    public void focusGained(FocusEvent e) {
      JComponent field = (JComponent)e.getSource();
      Rectangle r = field.getBounds();
      //System.out.println("r = " + r);
      // JComponent method sends message to component's
      // parent who implements scrollable interface
      panel.scrollRectToVisible(r);
  public static void main(String[] args) {
    new test();
}

Similar Messages

  • Keep focus in the same window after opening a new window per key-event

    I have an application in which user can press on a specific key, and that opens a new window in a JFrame. User might want open a few of such windows in a row by changing the cursor position and pressing the same letter key. But the problem is that with every new window Java VM transfers the focus to that new window. User is forced either to click to regain focus, or to move the mouse out-and-in the window, in which case the focus returns to it as well, assuming the X11 style of focus by cursor position of course.
    Is there any way to keep the focus with the window on which the cursor is placed?

    In your ActionListener your code should be something like:
    JFrame anotherOne = new JFrame();
    anotherOne.setVisible(true);
    originalFrame.requestFocusInWindow();If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://sscce.org], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Can anybody help? My Safari browser keeps crashing. The whole window just turns grey.

    Can anybody help? My Safari browser keeps crashing on iMac 10.7.5. The whole window just turns grey. It started happening around the time of the new bookmarks menu upgrade recently which changed the bookmarks to be only on the side and makes it so you can see all your bookmarks while browsing.  I know I have a lot of bookmarks, so I tried hiding them, but it still happens. I ALREADY TRIED CLEARING MY HISTORY, AND THAT DID NOT HELP, AND I HAVE NO EXTENSIONS FOR THIS BROWSER.
    Does the fact that I am in Brasil have anything to do with it?
    Thank you to anyone who can help. In case no one can come up with an answer, is there an easy way to transfer my bookmarks from safari to either firefox or chrome?
    Much appreciated.

    1. This is a comment on what you should and should not do to protect yourself from malicious software ("malware") that circulates on the Internet. It does not apply to software, such as keystroke loggers, that may be installed deliberately by an intruder who has hands-on access to the victim's computer. That threat is in a different category, and there's no easy way to defend against it. If you have reason to suspect that you're the target of such an attack, you need expert help.
    If you find this comment too long or too technical, read only sections 5, 6, and 10.
    OS X now implements three layers of built-in protection specifically against malware, not counting runtime protections such as execute disable, sandboxing, system library randomization, and address space layout randomization that may also guard against other kinds of exploits.
    2. All versions of OS X since 10.6.7 have been able to detect known Mac malware in downloaded files, and to block insecure web plugins. This feature is transparent to the user, but internally Apple calls it "XProtect." The malware recognition database is automatically checked for updates once a day; however, you shouldn't rely on it, because the attackers are always at least a day ahead of the defenders.
    The following caveats apply to XProtect:
    It can be bypassed by some third-party networking software, such as BitTorrent clients and Java applets.
    It only applies to software downloaded from the network. Software installed from a CD or other media is not checked.
    As new versions of OS X are released, it's not clear whether Apple will indefinitely continue to maintain the XProtect database of older versions such as 10.6. The security of obsolete system versions may eventually be degraded. Security updates to the code of obsolete systems will stop being released at some point, and that may leave them open to other kinds of attack besides malware.
       3. Starting with OS X 10.7.5, there has been a second layer of built-in malware protection, designated "Gatekeeper" by Apple. By default, applications and Installer packages downloaded from the network will only run if they're digitally signed by a developer with a certificate issued by Apple. Software certified in this way hasn't necessarily been tested by Apple, but you can be reasonably sure that it hasn't been modified by anyone other than the developer. His identity is known to Apple, so he could be held legally responsible if he distributed malware. That may not mean much if the developer lives in a country with a weak legal system (see below.)
    Gatekeeper doesn't depend on a database of known malware. It has, however, the same limitations as XProtect, and in addition the following:
    It can easily be disabled or overridden by the user.
    A malware attacker could get control of a code-signing certificate under false pretenses, or could simply ignore the consequences of distributing codesigned malware.
    An App Store developer could find a way to bypass Apple's oversight, or the oversight could fail due to human error.
    For the reasons given above, App Store products, and other applications recognized by Gatekeeper as signed, are safer than others, but they can't be considered absolutely safe. "Sandboxed" applications may prompt for access to private data, such as your contacts, or for access to the network. Think before granting that access. OS X security is based on user input. Never click through any request for authorization without thinking.
    4. Starting with OS X 10.8.3, a third layer of protection has been added: a "Malware Removal Tool" (MRT). MRT runs automatically in the background when you update the OS. It checks for, and removes, malware that may have evaded the other protections via a Java exploit (see below.) MRT also runs when you install or update the Apple-supplied Java runtime (but not the Oracle runtime.) Like XProtect, MRT is effective against known threats, but not against unknown ones. It notifies you if it finds malware, but otherwise there's no user interface to MRT.
    5. The built-in security features of OS X reduce the risk of malware attack, but they're not absolute protection. The first and best line of defense is always going to be your own intelligence. With the possible exception of Java exploits, all known malware circulating on the Internet that affects a fully-updated installation of OS X 10.6 or later takes the form of so-called "Trojan horses," which can only have an effect if the victim is duped into running them. The threat therefore amounts to a battle of wits between you and the malware attacker. If you're smarter than he thinks you are, you'll win.
    That means, in practice, that you always stay within a safe harbor of computing practices. How do you know what is safe?
    Any website that prompts you to install a “codec,” “plug-in,” "player," "extractor," or “certificate” that comes from that same site, or an unknown one, is unsafe.
    A web operator who tells you that you have a “virus,” or that anything else is wrong with your computer, or that you have won a prize in a contest you never entered, is trying to commit a crime with you as the victim. (Some reputable websites did legitimately warn visitors who were infected with the "DNSChanger" malware. That exception to this rule no longer applies.)
    Pirated copies or "cracks" of commercial software, no matter where they come from, are unsafe.
    Software of any kind downloaded from a BitTorrent or from a Usenet binary newsgroup is unsafe.
    Software that purports to help you do something that's illegal or that infringes copyright, such as saving streamed audio or video for reuse without permission, is unsafe. All YouTube "downloaders" are outside the safe harbor, though not all are necessarily harmful.
    Software with a corporate brand, such as Adobe Flash Player, must be downloaded directly from the developer’s website. If it comes from any other source, it's unsafe. For instance, if a web page warns you that Flash is out of date, do not follow an offered link to an update. Go to the Adobe website to download it, if you need it at all.
    Even signed applications, no matter what the source, should not be trusted if they do something unexpected, such as asking for permission to access your contacts, your location, or the Internet for no obvious reason.
    "FREE WI-FI !!!" networks in public places are unsafe unless you can verify that the network is not a trap (which you probably can't.) Even then, do not download any software or transmit any private information while connected to such a network, regardless of where it seems to come from or go to.
    6. Java on the Web (not to be confused with JavaScript, to which it's not related, despite the similarity of the names) is a weak point in the security of any system. Java is, among other things, a platform for running complex applications in a web page, on the client. That was always a bad idea, and Java's developers have proven themselves incapable of implementing it without also creating a portal for malware to enter. Past Java exploits are the closest thing there has ever been to a Windows-style virus affecting OS X. Merely loading a page with malicious Java content could be harmful.
    Fortunately, client-side Java on the Web is obsolete and mostly extinct. Only a few outmoded sites still use it. Try to hasten the process of extinction by avoiding those sites, if you have a choice. Forget about playing games or other non-essential uses of Java.
    Java is not included in OS X 10.7 and later. Discrete Java installers are distributed by Apple and by Oracle (the developer of Java.) Don't use either one unless you need it. Most people don't. If Java is installed, disable it — not JavaScript — in your browsers.
    Regardless of version, experience has shown that Java on the Web can't be trusted. If you must use a Java applet for a task on a specific site, enable Java only for that site in Safari. Never enable Java for a public website that carries third-party advertising. Use it only on well-known, login-protected, secure websites without ads. In Safari 6 or later, you'll see a lock icon in the address bar with the abbreviation "https" when visiting a secure site.
    Follow the above guidelines, and you’ll be as safe from malware as you can practically be. The rest of this comment concerns what you should not do to protect yourself from malware.
    7. Never install any commercial "anti-virus" or "Internet security" products for the Mac, as they all do more harm than good, if they do any good at all. Any database of known threats is always going to be out of date. Most of the danger is from unknown threats. If you need to be able to detect Windows malware in your files, use one of the free anti-virus products in the Mac App Store — nothing else.
    Why shouldn't you use commercial "anti-virus" products?
    Their design is predicated on the nonexistent threat that malware may be injected at any time, anywhere in the file system. Malware is downloaded from the network; it doesn't materialize from nowhere.
    In order to meet that nonexistent threat, the software modifies or duplicates low-level functions of the operating system, which is a waste of resources and a common cause of instability, bugs, and poor performance.
    To recognize malware, the software depends on a database of known threats, which is always at least a day out of date. Most of the real-world danger of malware attack comes from highly targeted "zero-day" exploits that are not yet recognized.
    By modifying the operating system, the software itself may create weaknesses that could be exploited by malware attackers.
    8. An anti-malware product from the App Store, such as "ClamXav," doesn't have these drawbacks. That doesn't mean it's entirely safe. It may report email messages that have "phishing" links in the body, or Windows malware in attachments, as infected files, and offer to delete or move them. Doing so will corrupt the Mail database. The messages should be deleted from within the Mail application.
    An anti-virus app is not needed, and should not be relied upon, for protection against OS X malware. It's useful only for detecting Windows malware. Windows malware can't harm you directly (unless, of course, you use Windows.) Just don't pass it on to anyone else.
    A Windows malware attachment in email is usually easy to recognize. The file name will often be targeted at people who aren't very bright; for example:
    ♥♥♥♥♥♥♥♥♥♥♥♥♥♥!!!!!!!H0TBABEZ4U!!!!!!!.AVI♥♥♥♥♥♥♥♥♥♥♥♥♥♥.exe
    Anti-virus software may be able to tell you which particular virus or trojan it is, but do you care? In practice, there's seldom a reason to use the software unless a network administrator requires you to do it.
    The ClamXav developer won't try to "upsell" you to a paid version of the product. Other developers may do that. Don't be upsold. For one thing, you should not pay to protect Windows users from the consequences of their choice of computing platform. For another, a paid upgrade from a free app will probably have the disadvantages mentioned in section 7.
    9. It seems to be a common belief that the built-in Application Firewall acts as a barrier to infection, or prevents malware from functioning. It does neither. It blocks inbound connections to certain network services you're running, such as file sharing. It's disabled by default and you should leave it that way if you're behind a router on a private home or office network. Activate it only when you're on an untrusted network, for instance a public Wi-Fi hotspot, where you don't want to provide services. Disable any services you don't use in the Sharing preference pane. All are disabled by default.
    10. As a Mac user you don't have to live in fear that your computer is going to be infected every time you install an application, read email, or visit a web page. But neither should you have the false idea that you will always be safe, no matter what you do. The greatest harm done by security software is precisely its selling point: it makes people feel safe. They may then feel safe enough to take risks from which the software doesn't protect them. Nothing can lessen the need for safe computing practices.

  • How to set focus in the parent window after a JOptionPane pop up ?

    I am not able to set the focus back to a JTextField in the parent window after poping up a JOptionpane.showMessageDialog(). I tried requestfocus(),requestFocusInWindow etc......but not working. The code is given below.
    if ((encryptor.encrypt(password)).equals(configuredPasswd)) {
                        validPassword = true;
                   } else {
                        JOptionPane.showMessageDialog(saveUI,"The password entered is not correct.");
                        saveUI.getPasswdField().setText("");
    saveUI.getPasswdField().requestFocus();
    Sometimes the focus is coming to the JTextField.Sometimes it appears for a moment and then dissappears.Please give a solution

    see if this makes a difference
    if((encryptor.encrypt(password)).equals(configuredPasswd))
      validPassword = true;
    else
      JOptionPane.showMessageDialog(saveUI,"The password entered is not correct.");
      ActionListener al = new ActionListener(){
        public void actionPerformed(ActionEvent ae){
          saveUI.getPasswdField().setText("");
          saveUI.getPasswdField().requestFocusInWindow();}};
      javax.swing.Timer timer = new javax.swing.Timer(100,al);
      timer.setRepeats(false);
      timer.start();
    }

  • Keeping things inside the browser window

    I do not want any browser scrollbars unless the browser is resized below minsize, the problem is when I set body,html in the CSS to have a height of 100% it does not seem to keep anything restricted to the browser window viewport.
    This is probably more of a CSS problem, but was hoping someone here might have a template where all regions are constrained to the size of the browser window?
    Thanks,
    Dan

    It isn't working with mpg files. I reclaimed all WMV, and unchecked "Always show movie controller" and unchecked "Launch QT player"
    It is working in FFox but not in Safari 3.x
    http://www.familybowlaway.com/parties.asp

  • Since upgrading to Mavericks from time to time the focus for the cursor is misplaced when scrolling

    Since upgrading to Mavericks, from time to time the focus for scrolling is misplaced. If I click into the list of emails, the mail message in preview scrolls. If I click into the mailboxes column, the list of emails in my inbox scrolls. Have anyone else seen this issue?

    Since upgrading to Mavericks, from time to time the focus for scrolling is misplaced. If I click into the list of emails, the mail message in preview scrolls. If I click into the mailboxes column, the list of emails in my inbox scrolls. Have anyone else seen this issue?

  • Arrow keys don't change the focus in the delete window

    When I delete an image a window open the three option; delete, reject and cancel; with reject being the focus.  In oder to select another option I have to reach for the mouse; because the arrow keys do nothing, and there is no D, R or C shortcut.  Is there something wrong with my setup; like an option I've failed to set. Hard to believe the user must always reach for the mouse when deleting images.

    I'm not sure why they don't work on mine.  There is an program on my machine who's shortcuts have to be disabled before I use CS5, but I don't know any others that remap my arrow keys.  Of course it's entirely possible that there is one, but I have no idea how I'd ID it; if it exists.
    I dl'd my copy of CS5 from Adobe then bought a student copy at the bookstore, then used the key from that to activate the dl'd copy.  I can't think of any reason that should create problems.  I suppose I could re-install it from the disk; but I'd rather not

  • In Word and others, when I tip, regularly the focus quits the present window and i can't no more tip verry perturgbating

    In Word and other programs -  even in Safari - when I tip, the focus is suddently somewhere else and I tip nothing more.
    Extremely annoying: I have to tip twice the same things!
    the pointer of the mouse is also erratic

    Sorry, i wanted to write ' type ': when i type In word suddenly the pointer is somewhere else and i have to click in the windows to get the focus. Very annoying and Time consuming. I become crazy with this.
    best regards

  • When i get a pop up to another link it opens a new window. Can i just keep it in the new window just in another tab?

    Need Tabs all on one page. How do I prevent new windows from popping up when I open a new link? Can I have them automatically load to another tab?

    This issue can be caused by an extension that isn't working properly.
    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do not click the Reset button on the Safe mode start window or otherwise make changes.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes

  • My screen shakes and my browser keeps going to the maximum window size. Screen shaking up and down

    My screen shakes up and down when I am typing or when I click on a new page. If I hold the control button, then the screen doesn't shake. The screen keeps going to maximum size automatically also and the toolbar goes away.

    Hello there Saber7,
    If I understand correctly, the phone seems to think the phones volume up is constantly being pressedbut the button still clicks when you press it. This should be easy to isolate to hardware or software, so I would start by quitting all the apps that are running on the phone:
    iOS: Force an app to close
    Double-click the Home button.
    Swipe left or right until you have located the app you wish to close.
    Swipe the app up to close it.
    When you have done that reset the device and test the issue again:
    iOS: Turning off and on (restarting) and resetting

  • How to bring the new window in front of old window

    Hi everyone,
    Here is what I have:
    there is a hyperlink on Page1.jsp, which opens another page Page2.jsp through onclick=
    window.open('./faces/Page2.jsp','mywindow','width=500','height=600');
    However, after Page2.jsp is opened in a new window, it is always behind the old window with Page1.jsp. That is, Page1.jsp always gets the focus. I have to click Page2.jsp at windows' bottom bar in order to bring it up.
    How to set Page2.jsp window in front of Page1.jsp window as default?
    Thanks in advance,

    it should have the focus
    jsut tried your code and my browser keeps focused on the other window
    i would be looking elsewhere for your problem
    maybe in your browsers setup?

  • How to solve RDP lost focus issue when RDP window minimized

    Hello,
    I have an application running on Windows 2012 server where users connect to the server via RDP client. Users run on Windows 7/XP.  The application is a screen recording software which records all the activity.
    Users connect to Windows Server 2012 by giving the IP Address in RDP. The user opens the applications & starts his work and recording is also started.
    At an instant, the user minimized the RDP window on his Laptop/Desktop, now the screen-recording stops. As soon as the RDP window is maximized, the recording starts again.
    I learned from Technet that there is a workaround by tweaking the registry on user laptop/desktop. However the problem here is that I have no control on user laptops/desktops as the users are spread in the whole world & does not belong only to my organization.
    Hence is there any other way by which I can solve the issue without any registry tweak. Is there a way by which I can enforce users to use the RDP client of the Windows 2012 Server on which I have control and I can change the settings on the same.
    Will Windows 2012 Server RDS services resolve the issue without any change at the user end.
    This is a P1 issue for me. Hence expecting support from the community
    Regards

    Hi,
    Thank you for posting in Windows Server Forum.
    Initially suggest you to upgrade the RDP client version to RDP 8.1 for better performance.
    From the description it seems you are using RDP to connect to the server. Can you please clarify again, if it’s RemoteApp application or connecting the application after RDPing to the server?
    If it’s RemoteApp application and facing problem then there is one Hotfix available to try:
    A RemoteApp application main window takes the focus after the applications windows are maximized in Windows
    http://support.microsoft.com/kb/2862019
    For RDP, you can try the following option to configure. You can configure “Keep-alive connection interval” under group policy and check.
    Computer Configuration\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Services Session Host\Connections\
    Configure Keep-alive connection interval:  Enable and specify value 
    In addition to this also verify the registry setting must be set as per following 
    HKEY_Local_Machine \ SOFTWARE \ Policies \ Microsoft \ Windows NT \ Terminal Services
    KeepAliveEnable REG_DWORD
    0x00000001 (1)
    KeepAliveInterval REG_DWORD
    0x00000001 (1)
    Hope it helps!
    Thanks.
    Dharmesh Solanki
    TechNet Community Support

  • Cannot move inside the Fonts window using arrow keys?

    I'm pretty sure there was a way to move around in the Fonts menu using the arrow keys.  The selected Collection, Family or Typeface would turn from grey (not able to navigate) to the blue (able to navigate). 
    Does this ring a bell to anyone else?

    So I did search before posting this question but couldn't find anything.  Of course right after I post I found the answer.
    But this doesn't always work in all programs.
    You have to shift the focus to the font window by clicking on it, not just by clicking on a Collection, Family or Typeface line item.  Then the selected column will be highlighted blue, the Maximize, Minimize and Close buttons will be in color and the selected item will also be highlighted in blue.
    But this doesn't always work in all programs.
    Any ideas?

  • All I'm getting is the IMovie window and a continuously spinning wheel...what can I do to fix it?

    Even before my update to iOS 5.1 it was doing that, not a very long time ago. My mac is starting to get really slow, and is stopping sometimes and keeps spinning the wheel for a very long time. I updated my mac today, but still in IMovie all I keep getting is the open window and the continuously spinning wheel, how can i fix it? Can you help me please?

    Try:
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try on another computer
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar       

  • Site automatically scale to fit the browser window

    hello all!
    i'm working on a site that i'd like to automatically scale to fit the browser window, without any scrolling and while preserving its aspect ratio.
    my client is very particular about the design & does not want the width & height of the images & text to change like they do in a responsive site- he just wants the site to scale to fit in a browser window. Yikes!!!
    could anyone give me a hand with this please?
    thanks so very much!
    -sharon

    Hi Andreas
    I'm really looking forward to hearing about your tests tonight. As I said to Elaine (above) I will be delighted if someone proves me wrong. I'm just looking for a solution.
    I've just had another quick go on Edge Animate to try out your suggestions:
    My findings are that it doesn't matter whether a graphic is wrapped in a div or not. If the graphic has L, T , W & H pixel values and the surrounding div group is set to L, T , W & H % values, the L & T will scale down but the W & H will not - the graphic will just stay the same size when the browser is shrunk. The only way to get the graphic to scale down is to change its L, T , W & H to % - but, as I've said it won't retain its aspect ratio.
    As soon as images are imported, the situation changes. The layout preset offers 4 more options including 'Scale background image'. And Background image settings now appear offering W 100%, H Auto by default. These both seem essential to achieving scale-to-fit. I've tried images with and without being wrapped in a div. Just as with graphics, I find that if I add the % to the div then the image doesn't scale. But if I add the % to the image it scales perfectly.
    As far as I can see the problem is that, with graphics, the link width and height feature doesn't seem to work properly. I would expect that if I create a graphic 100px square then change W & H to %, then both W & H would be the same %. But I get all sorts of results. It doesn't seem to make a difference if I fix the percentages so W & H are both 100%. Changing from Global to Applied doesn't seem to affect anything either. Surely if W & H are set to 100% (and linked) then a graphic should remain square regardless of browser size? I can't find any combination that will allow this. Is it just me? Am I doing something stupid?
    Good luck tonight.
    Cheers

Maybe you are looking for