Always show beginning of JTextField, while it stays selected

Hello,
I have an editable JComboBox, and when I select items from it, I highlight the selected item. If the item's length is longer than the textField's width, I have the cursor pointing to the end of the text by default. I was wondering if there's a way to always show the beginning of the text, regardless of the text length, while it stays selected. I have tried setCaretPosition(0) which works, but then unhighlights the text.
Your help will be very much appreciated.
Here's my SSCCE:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyTextFieldTest {
     JComboBox myComboBox = new JComboBox();
     public MyTextFieldTest()
          JFrame frame = new JFrame("MyTextFieldTest");
          JPanel panel = new JPanel();
          myComboBox = getMyComboBox();
          panel.add(myComboBox);
          frame.getContentPane().add(panel);
          frame.setSize(new Dimension(200,100));
          frame.setVisible(true);
     public JComboBox getMyComboBox()
          myComboBox = new JComboBox();
          myComboBox.setEditable(true);
          myComboBox.setPreferredSize(new Dimension(100,20));
          myComboBox.setSelectedItem("Items...");
          for(int i=0;i<10;i++)
               myComboBox.addItem("Item "+i);
          myComboBox.addItem("My very long Item");
          final JTextField editor = (JTextField)myComboBox.getEditor().getEditorComponent();
          myComboBox.addActionListener(new ActionListener()
               public void actionPerformed(ActionEvent e)
                    editor.setSelectedTextColor(Color.white);
                    editor.setSelectionColor(Color.blue);
                    editor.selectAll();
          return myComboBox;
     public static void main(String[] args)
          MyTextFieldTest test = new MyTextFieldTest();
}Edited by: programmer_girl on Sep 18, 2007 5:38 PM

      public void actionPerformed(ActionEvent e)
        editor.setSelectedTextColor(Color.white);
        editor.setSelectionColor(Color.blue);
        //editor.selectAll();
        editor.setCaretPosition(editor.getDocument().getLength());
        editor.moveCaretPosition(0);
      }

Similar Messages

  • JTextField - Show date format mask while inputing

    I have searched through the forums and I have not found an instance of someone try to show the format mask while a user inputs chars:
    ex: **/**/**** <-- Initialized
    1*/**/**** <-- After first integer
    10/3*/**** <-- After third integer
    I would also like the keep the caret position at the last integer and not always at the end of the input.
    Also if a user enters a "t"||"T" that it will automatically enter today's date.
    Is there a quick way? I have tried to use a DefaultStyledDocument but have not had success.
    Thanks

    here's a starter
    (needs to handle backspace, delete and probably a few other keys)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    class Testing extends JFrame
      JTextField tf = new JTextField(new MyDoc(),"**/**/**",10);
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel jp = new JPanel();
        jp.add(tf);
        getContentPane().add(jp);
        pack();
      class MyDoc extends PlainDocument
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
          if(str.equals("**/**/**") == false && (offs == 2 || offs == 5 ||
             str.length() > 1 || offs > 7 || "0123456789".indexOf(str) < 0))
            java.awt.Toolkit.getDefaultToolkit().beep();
            return;
          StringBuffer newText = new StringBuffer(getText(0,getLength()));
          if(newText.length() > 0)
            newText.setCharAt(offs,str.toCharArray()[0]);
            remove(0,getLength());
            super.insertString(0,newText.toString(),a);
            if(offs == 1 || offs == 4) tf.setCaretPosition(offs+2);
            else tf.setCaretPosition(offs+1);
          else super.insertString(offs,str,a);
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • My time machine always stops at some point... It always shows this message: "Time Machine Error. Unable to complete backup. An error occurred while copying files to the backup volume.

    My time machine always stops at some point... It always shows this message: "Time Machine Error. Unable to complete backup. An error occurred while copying files to the backup volume. I have tried everything and even did time machine in safe boot as told by an apple suppoprt advisor. still the same error after 16gb

    If you have more than one user account, these instructions must be carried out as an administrator.
    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
    Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left. If you don't see that menu, select
    View ▹ Show Log List
    from the menu bar.
    Enter the word "Starting" (without the quotes) in the String Matching text field. You should now see log messages with the words "Starting * backup," where * represents any of the words "automatic," "manual," or "standard." Note the timestamp of the last such message that corresponds to a failed backup. Now
    CLEAR THE WORD "Starting" FROM THE TEXT FIELD
    so that all messages are showning, and scroll back in the log to the time you noted. Select the messages timestamped from then until the end of the backup, or the end of the log if that's not clear. Copy them (command-C) to the Clipboard. Paste (command-V) into a reply to this message.
    If all you see are messages that contain the word "Starting," you didn't clear the text field.
    If there are runs of repeated messages, post only one example of each. Don't post many repetitions of the same message.
    When posting a log extract, be selective. Don't post more than is requested.
    Please do not indiscriminately dump thousands of lines from the log into this discussion.
    Some personal information, such as the names of your files, may be included — anonymize before posting.

  • Why is it that when I set the preference to always show the tab bar, it refuses to stay checked after I quit Firefox and restart it?

    Using Mac OSX10.6.7 and FF 4.0.1, I'm having a problem with the preference to always show the tab bar. I want it to always show. I check this in the Preferences under the "tab" window, and everything is fine until I quit FF and when I restart FF the tab bar is gone again. I go into preferences, and that option is now unchecked. How can I fix this so that my preference is saved?

    That hasn't helped the last ten times I tried. I posted before. I deleted the preferences file, I tried changing the preferences file, I went into about:config and changed the autoHide preference there. No dice. Firefox is not saving my preference for that one thing.

  • Apple TV after IO6 upgrade always shows What's new screen

    After upgrade my apple tv Generation always show what's new secreen and cannot bypassing.

    It happend to me also. The solution is just let it stay there for 10 to 15 minutes (do not unplug otherwise it will start all over again), the "What's New" screen will go away by itself and you are back to Apple TV's normal home screen again. This scenario happens usually when you hadn't plugged AppleTV to electrical outlet for a long while.
    This is obviously a bug because it seems "Continue" button is not responding. But actually it did respond but the screen freezes at "What's New". After 10 to 15 minutes the video card finally catches up to your last action.

  • Is there a way to default the monthly calendar display so that the current day always shows on top?

    Is there a way to default the monthly calendar display
    so that the current day always shows on top? ie, I want to always be able to see what's in the future 3-4 weeks, not what's in the past 3-4 weeks. The default monthly display is archaic--only allows you to see through the last day of the month. Suddenly today
    is Oct. 30th, and I have a ton of projects lined up in November, but because I haven't been scrolling down every day, I haven't been aware of them every day. I realize there are other tools in Microsoft to help me stay on task, such as reminders and such,
    but it would be helpful if I could always have the current day display on top of the monthly view so I can quickly scan what's coming up in the next few weeks. 

    Thank you!
    Right, I already have it in Month view. My question is a little more specific--I'd like for the current day to always display at the top. For example, today is Oct. 31st, so the current day is at the bottom of the calendar since it is the last day of the month.
    I can view everything in October that I've already completed. What I can't see are the future weeks because we haven't hit November yet. I'd like for the current day to always display at the top of my calendar so I can always see what's coming in the following
    three - four weeks (whether they're a part of that month or not). I've been to other forums trying to find the answer, and have come across the same exact question from frustrated users--but there seemed to be no solution. So I'm posing the question myself
    in this forum. Do you know if this is possible? What I found from other forums is that Outlook defaults to a physical 'desk' type calendar format--so just as I'd use a paper calendar at my desk, I wouldn't be able to see the following weeks unless I either
    flip the page to that month or I come to the first day of the next month, thereby tearing the the old month off and now only able to see the current month. That format is just so...paper...and archaic! Essentially I want the calendars to loop so it doesn't
    even really matter what month it is--I just always want to see what lies ahead without having to scroll down. With our being in the Technology Age, I'd assume this is a logical expectation, but we may be stuck with the replica version of the paper-desk-calendar
    format until Outlook programmers add this Technology Age feature in newer versions.  
    See, this month kind of messed me up because I have so many projects for November that start tomorrow and next week, but I haven't seen them until this week. I would have been better quipped--at least expecting them--had I been able to see all of those projects
    since last week or the week prior.  
    If there is no solution to this answer, would you know how I can contact Outlook to provide feedback? I'm guessing a newer version is on its way...
    Thanks again in advance!

  • In Dual Monitor setup, with Thunderbird not in main monitor, the some dialogs always shows in other monitor

    I have a three monitor set up. I have Thunderbird running in the right monitor. My main monitor is the middle one. Dialogs, such as Spell check, Activity Monitor always show up in the main window (not the one with Thunderbird) in the upper left hand corner.
    It happens on Windows Vista and Windows 7 Professional.
    I have Thunderbird version 24.3.0

    Some dialogs when moved, stay moved. Others do not. The ones that frustrate me are those that are Centered and therefore show up split across my two monitors.

  • In CLIENT_RESULT_CACHE_STATS$  "Find count always shows 0"

    In CLIENT_RESULT_CACHE_STATS$ "Find count always shows 0" even client cache is enabled.
    I am not able to enable client side result cache . I use ODAC which uses ODP.net driver internaly i have attached code file.
    I have done following settings in database
    client_result_cache_size 1048576 FALSE
    client_result_cache_lag 3000 TRUE
    result_cache_mode MANUAL
    result_cache_max_size 5373952
    result_cache_max_result 5
    result_cache_remote_expiration 0
    client_result_cache_size 1048576
    client_result_cache_lag 3000
    Database version is Enterprise Edition Release 11.2.0.1.0
    Only select * from V$RESULT_CACHE_STATISTICS where find count increases always but " Find count" in CLIENT_RESULT_CACHE_STATS$ is always 0.
    If the client side result cache enabled means it find count in CLIENT_RESULT_CACHE_STATS$ should increase rite???
    Please help me to solve this issue
    sharath

    Oops, not query the sys views.
    Thanks Chris, just read your message while post above.
    Yeah, should not use dba_objects.
    Message was edited by:
    user498460
    Message was edited by:
    user498460

  • Camera connection kit always shows no photos to import?

    No matter what use wether its from a camera via usb or the sd card slot it always shows no pictures to import.
    I havent used it in a while and just updated to 4.3.2 i believe it is, is there some compatablity issue with the latest update?
    I dont use it alot but always worked before.

    im no idevice expert but im not an idiot either
    i tried using ifile and transferred the pics, renamed them so they followed squence with the rest of the pics in the standard folder, and even deleted and existing pic to test it and NOTHING
    transferred pics are there in ifile and deleted pics are gone after restart but when i open "photos"  the transferred ones still arent there and the deleted still are.
    am i seriously missing something?

  • Help-UNICPOUTU always shows calendar server is not running

    Hi All,
    I am trying to export data from OCS 10g Calendar server and while using UNICPOUTU utility on default node (1), it always shows error message "Calendar Server is not running".
    I have stopped and than started server many time using unistop/unistart and opmnctl with stopall/start all. I can work without any problem with OCS portal and Windows calendar client.
    Can any body help me to find the cause and resolve it.
    Thanks in advance for your help and time.

    I was aware the format originated with CS&T (later Steltor) Corporate Time, and that the NetScape Calendar was of the same provenance. I didn't know SGI also had an offspring
    of Corporate Time.
    Sorry for not being more precise in my earlier post. I guess I should have said that the format used by unicpoutu/unicpoutr is specific to Oracle Calendar and other products derived from the earlier Unison/Corporate Time product.
    Either way, though, iCal is format that more programs understand. uniical is also the program that Oracle support recommended I use, instead of unicpoutu, when I ran into bugs with unicpoutu in the past.
    Tim

  • IPhone always shows 3G when waking from sleep

    Lately it seems that whenever I wake the phone from sleep, the screen shows 3G at the top, then switches to the wifi symbol after a couple of seconds. My phone is always on wifi at home, at my parents', and at my in-laws, so why does it always show the 3G symbol and then switch over when I hit the Home or Wake button? Seems like it should stay on wifi if it's connected to the wifi network.

    When the iPhone goes into sleep mode it loses the WiFi connection. It takes a brief time for it to reconnect when you wake it.

  • Iphone 5 cant be restored, it shows unknown error -1 while trying to restore and it only display connect to Itune

    Iphone 5 cant be restored, it shows unknown error -1 while trying to restore and it only display connect to Itune

    Greetings ayokunlefromlos angeles,
    Welcome to the Apple Support Communities!
    I understand that when attempting to restore your iPhone you receive an error and your iPhone shows the Connect to iTunes screen. To begin troubleshooting, I would suggest manually placing your iPhone in recovery mode and attempting the restore. Please follow the instructions located in the attached article to complete this process. 
    If you can't update or restore your iPhone, iPad, or iPod touch - Apple Support
    Cheers,
    Joe

  • Don't disconnect always showing

    My new I-pod always shows the Do not Disconnect symbol no matter what I do. I eject it from I-tunes manually and it still says that and even when I close out of I-tunes completely the sign stays.
    Can someone help understand as to why this little screen refuses to leave my I-pod even after everything it could be updating from is closed down.
    It's also stopped showing the charging sign. It just stays on Do not disconnect

    Welcome to the discussions.
    Have you seen this?
    Disconnecting the iPod from the Computer
    JC

  • I can't upgrade my iphone4 from iOS5.01 to iOS5.1, tried many times, always showed "unknown error 1602", what should I do?

    I can't upgrade my iphone4 from iOS5.01 to iOS5.1, tried many times, always showed "unknown error 1602", what should I do?

    Error 1600, 1601, 1602: Try the following steps to resolve this error: 
    Ensure proper USB isolation troubleshooting has been performed, and test with a known-good cable.
    Follow the steps listed for Error 1604.
    This error may be resolved by disabling, deactivating, or uninstalling third-party security, antivirus, and firewall software. See steps in this article for details on troubleshooting security software.
    Error 1604: This error is often related to USB timing. Try changing USB ports, uninstalling and reinstalling USB ports, and other available USB troubleshooting steps (troubleshooting USB connections, device not recognized properly, computer won't recognize a FireWire or USB device). If you are using a dock, bypass it and connect directly to the white Apple USB dock connector cable. If the issue persists on a known-good computer, the device may need service. 
    If the issue is not resolved by USB isolation troubleshooting, and another computer is not available, try these steps to resolve the issue:
    Connect the device to iTunes, confirm that the device is in Recovery Mode. If it's not in Recovery Mode, put it into Recovery Mode.
    Restore and wait for error 1604.
    When prompted, click OK.
    Close and reopen iTunes while iPhone remains connected.
    iPhone should now be recognized in Recovery Mode again.
    Try to restore again.
    If the steps above do not resolve the issue, try restoring using a known-good USB cable, computer, and network connection.

  • My iPhone 3G always shows an Unknown number calling when I've got that person's contacts, What should I do?

    When someone calls me, my iPhone 3G keeps on showing that it's an unknown number calling when I've got that person in my contacts.
    What can I do to solve this? Thanks.

    Simmilar issue here!
    Summary: Incoming calls show up only as phone numbers, not with the caller's name.
    Steps to Reproduce:
    1) On your iPhone, save a person's phone number in Contacts with the country's dialing code in front (+ZZZ-XX-YYYYYYY, where +ZZZ is the country code, XX is the carrier, YYYYYYY is the person's phone number);
    2) Make a call from that person's device/number to your iPhone;
    3) On your iPhone, while ringing, shows the above number without +ZZZ and without the person's name.
    Expected Results: No matter how the number is saved (as +ZZZ-XX-YYYYYYY or simply as XX-YYYYYYY) the caller ID should always show up, as in previous iOS editions.
    Actual Results: Caller ID does not work as expected and as in previous iOS versions.
    Notes: When I receive voice calls, the number comes in without the country dialing code in front, simply appears as XX-YYYYYYY (where the XX is the carrier code and YY is the number) and the caller's name does not appear. In my address book ALL my contact's telephone numbers are preceded with the corresponding country dialing code, because i travel a lot. If I delete the country code from a contact's phone number, and that number calls me, then the person's name appears. I'm am in Angola (country code +244) using iPhone 4, iOS 5, carrier: UNITEL (92)
    On the other hand, SMS's are OK, i.e. the Caller ID is linked to the phone number and shows up (because SMS's are receiver with the country dialing code in front of the phone number, p.ex. +244-XX-YYYYYYY).
    It has something to do with the Carrier Settings Update as in iTunes i get the error message 1630 which states that: "iTunes could not check for un update to the carrier for your iPhone. An unknown error occured (1630)."
    Thanks

Maybe you are looking for