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.

Similar Messages

  • Problem with requesting focus for a list

    Hi there !
    What would be the right way to request focus for a list component ?
    I can use select() method to select some item from a list, but the list itself still hasn't got a focus until I click it.
    What I'd like to do is to be able to highlight some item from the list by using up and down arrow keys only, without clicking the list first =)

    The list is visible, but still this doesn't work.
    I think that the reason for this may be that I'm running this app on Nokia 9210 Communicator emulator. The emulator itself has had some not-so-minor problems...

  • Request focus for message area

    Dear All,
    As my screen is long hence if an error comes we will require to scroll down so I have added a message area UI element and in do modify method of the view i have request focus to my message area but it is not working.  Below is the code which I have written:
    try{
              IWDMessageArea msgarea=(MessageArea)view.getElement("MessageArea");
            msgarea.requestFocus();
            catch(Exception e)
    Is there any other property or changes need to be made.
    Thankyou.
    Regards,
    Santosh

    Hi,
    In would say, create an input field at the top left corner of the screen. Set its width to zero and bind it to a context attribute say Va_ShowMesg of type string. Now insert a MessageArea UI element just below the inputfield to display all the erro message at the top left.
    Now if you request focus for the input field using the following code, the focus will automatically come to the Message Area as well.
    wdThis.wdGetAPI().requestFocus(wdContext.currentContextElement(),wdContext.getNodeInfo().getAttribute(
              wdContext.currentContextElement().VA__SHOW_MESG));
    You can call this code whenever you need to display message to user in the message area and shift focus of the screen to the message displayed.
    Regards,
    Tushar Sinha

  • Problem with gaining focus for JTextField in JTabPane

    I have 2 tabs. The first one has a "save to file" puush button, the seccond has two textfields. When I push the save button I get a warning that not all fields in the seccond tab are filled. If I choose the first button it shows me the seccond tab and searches for the first empty field. Then it should set the focus to that field but it doesn't. Here's the code:
    void goToEmptyField() {
            tabs.setSelectedIndex(1);
            JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
            field.requestFocusInWindow();
        }The code for determining the first empty field works fine. I'm not sure if the seccond tab gets focus or just shows up. It doesn't have the light rectangle at the tab's description. Could anybody help me please?

    seems to work OK in this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      JTabbedPane tabs;
      JTextField nameField = new JTextField(20);
      JTextField actionField = new JTextField(20);
      public Testing()
        setLocation(400,300);
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel jp1 = new JPanel();
        JButton saveBtn = new JButton("Save");
        saveBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            if(checkFields()) saveData();}});
        jp1.add(saveBtn);
        JPanel jp2 = new JPanel();
        jp2.add(new JLabel("Name: "));
        jp2.add(nameField);
        jp2.add(new JLabel("Action: "));
        jp2.add(actionField);
        tabs = new JTabbedPane();
        tabs.addTab("Tab 1",jp1);
        tabs.addTab("Tab 2",jp2);
        getContentPane().add(tabs);
      public boolean checkFields()
        if(nameField.getText().equals("") || actionField.getText().equals(""))
          JOptionPane.showMessageDialog(this,"field/s empty");
          goToEmptyField();
          return false;
        return true;
      public void goToEmptyField()
        tabs.setSelectedIndex(1);
        JTextField field =  (nameField.getText().length() == 0) ? nameField : actionField;
        field.requestFocusInWindow();
      public void saveData()
        JOptionPane.showMessageDialog(this,"Saving data...");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • How to request focus for Panel hiding behind another panel?

    Hi guys,
    I have two panels(of different sizes) within a JFrame, i have one button (in smaller panel)that does some query in the back end & populates the results in another panel (bigger panel), now assuming that i am in smaller panel, how is that i can bring up the bigger panel that is hiding behind this smaller panel.
    I tried using requestFocus method but its not working.
    Can anyone help me in this regard?
    Thanks & Regards,
    Vishal

    Thanks for your feedback, but i am not using card layout instead i am using a Grid bag layout, i dont see any method like next() or show() for a instance of GridbagLayout.
    Any other alternative?
    Thanks & Regards,
    Vishal

  • I hired a commercial artist to create a color image for the cover of a self published book. I want a black and white image for the inside. The commercial artist has not responded to this request. How do I determine the format of the color image, I'm guess

    I hired a commercial artist to create a color image for the cover of a self published book. I want a black and white image for the inside. The commercial artist has not responded to this request. How do I determine the format of the color image, I'm guessing it's Illustrator's formatting but I don't know. How can I find out if Illustrator will open the file and allow alterations? The image opens only in Apple's Pages software?

    rons,
    It seems that all you have is a raster image, presumable PNG24 or JPEG, in RGB.
    It may have been created as raster artwork in Photoshop, or it may have been created as vector artwork with the help of Illy, or as a mixture of vector and raster artwork in either application, or both combined.
    If you just need to have a raster representation in black and white based on the current colour image, you may try this, in a new RGB document (View>Smart Guides are your friends):
    1) File>Place the image (you may tick Link or untick and have it embedded);
    2) Create a rectangle with black fill (R = G = B = 0), at least as large as the image, and place it behind the image (you may ClickDrag with the Rectangle Tool between opposite corners, then Ctrl/Cmd+X+B);
    3) Select all and in the Transparnecy palette flyout click Make Opacity Mask with both Clip and Invert Mask ticked.

  • Can a ReadOnly-JTextField get the Focus for a Copy action?

    Until JDK 1.3 a JTextField can be focusable and selectable, also the JTextField
    is not editable. So the user can Copy (with Ctrl-C) the displayed text to an other application.
    With JDK 1.4 the user cannot select the JTextField, if the Field is not editable.
    How I can the JTextField set to selectable (or focusable) in not editable state?
    thanks for suggestions
    Roland

    I suppose a workaround would be to make the JTextField editable, and to assign a DocumentListener that throws away all attempted updates to the content. Look in the API documentation for JTextField for an example of a DocumentListener that controls the content (you would just override insertString and deleteString (?) to do nothing).

  • How to disable the tab focusing for a JTextField object because those ...

    Hi All,
    Here I need some help. I want to disable the tab focusing( tab index) for a JTextField objects because those objects are set as setEditable(false). Also can u tell me about how to change the tab index orders for JTextFields.
    Many thanks,
    Vijaycanaan.

    I want to disable the tab focusing( tab index) for a JTextField objectsLook through the API and find methods with the word "focus" in the method name.
    Also can u tell me about how to change the tab index orders for JTextFields."How to Use the Focus Sub System":
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

  • Setting Focus of JTextField

    Hello,
    I have created a JDialog subclass that has several JTextFields in it.
    When the dialog is shown, I want the first (the top-most) textfield to have the focus.
    I have tried topTextField.requestFocus() but the focus remains on anotherTextField. isRequestFocusEnabled() == true for the topTextField, and I have not called any method to request the focus for anotherTextField.
    Is there any thing trickey about this getting focus business?

    Ok,
    I just noticed that the anotherTextField that has the focus is the first component that is added to a JPanel inbedded into my JDialog, and that when I add a different textField first, it has the focus. Is this a "feature" of Swing?
    In any case, I should still be able to change the focus to anyother component.
    Any ideas would be very helpful.

  • Button focus for mnemonic control

    Does anybody know how to set the focus on a JButton, in order for the mnemonic key to work? I have a Frame with textarea and a button, and the button ("Close") is set with a mnemonic key (`C`). I just don't know how to set the focus on the button so that when I hit Alt + C, the window will be close. Here is my code sample:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class BorderExample {
         private Frame f;
    private JButton close;
    private Panel p;
    private TextArea ta;
    public BorderExample() {
    f = new Frame("Border Layout");
    close = new JButton("Close");
    close.setMnemonic('C');
    close.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.exit(0);
    ta = new TextArea();
    ta.append("Hello World");
    ta.setEditable(false);
    public void launchFrame() {
    f.add(ta, BorderLayout.CENTER);
    p = new Panel();
    p.add(close);
    f.add(p, BorderLayout.SOUTH);
    f.pack();
    f.setSize(200, 200);
    f.setVisible(true);
    public static void main(String[] args) {
    BorderExample ex = new BorderExample();
    ex.launchFrame();
    Any suggestion is greatly appreciated.

    hi,
    this time i got ur exact problem. actually mnemonic control workes fine if all the components are in the same container. in ur example, they r in different panels. so, we need to make following changes :
    1) create a reusable action listener object, not the anonymous.
    2) call one method on the button panel : (methos in JComponent class, bur depricated since JDK1.3.)
    p.registerKeyboardAction(<action listener object>, <String action command>, KeyStroke.getKeyStroke(<key char value for mnemonic control>),JPanel.WHEN_IN_FOCUSED_WINDOW);
    this will fire the desirable event, even if u press alt-c while typing in text area.
    and regarding the grey color of text area, i am sorry about my previous reply. in disabled mode, background color doesn't change. just the text color changes and u can set that text color by calling this method of JTextComponent
    jtextcomp.setDisabledTextColor(Color c) ;
    hope this helps!!
    anshu

  • Set specific size for JTextfield/Jbutton in BorderLayout?

    can some one tell me how to set a specific size for JTextfield/JButton in Border/BoxLayout please?
    I stried setSize, setPrefersize, setMAxsize, setMinsize, setBounds... but it won't work?
    For example. If I add a jbutton to a jpanel, which has borderlayout, it will take up ALL the space in that jpanel.
    Thanks

    Typically you use a BorderLayout for the high level layout and then add panels using other layouts to the BorderLayout. So for example on a simple dialog that is using a form that asks your for your first name and last name you would build a panel with those fields and add that panel to the center of the BorderLayout. Then you would create another panel for the "Ok" and "Cancel" buttons which would typically use a FlowLayout. Then you add that panel to the South of the BorderLayout.
    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use LayoutManagers has all the information you need to know on using layout managers.

  • Need Help for -  JTextField outputs

    Hello everyone im back =P
    Just finished a code...and now i'd like to print the output using the JTextField , but it seems im having some problems :) ....don't know how to print the String.
    for JOptionPane its easy , we use JOptionPane.showMessag....etc
    we have also System.out...but i want to print this string with the JTextField, does anyone can help with that? thnks
                double m = complexo.module(r,i);
                double a = complexo.angle(r,i);
         String text = "Module: "+ Double.toString(m) + "\nAngle: " + Double.toString(a); 
    // I want to print  that String -> text
         JTextField  output = new JTextField(100);
         JPanel p = new JPanel();
         p.add(output);
         output.setText(text);
         output.setEditable(false);
    /** Is that ok ? do i have to use the JPanel or the JFrame ?  , well i just 
    *   want to print  that string  (text)  using the JTextField */ thnks

    In the future, Swing related questions should be posted in the Swing forum.
    and now i'd like to print the output using the JTextFieldLets get some terminoligy correct first. "Print" means you want to send the text to a printer so it can be printed on paper. I don't think thats what you want to do.
    You want to display the text on your monitor using a GUI. In that case you need to create a GUI container that contains a JTextField that will display the text.
    Start by read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html]How to Use Top Level Containers. The tutorial also has a section on using text components which shows you how to use a text field.

  • Key and action binding for JTextField

    when JtextField is focused I need to bind a combined key command to execute a function. For example when user presses ctrl+n and action will be executed. How can I do this for JTextField?

    Use following method:
    public void addKeyBoardAction(JComponent comp, String name, KeyStroke keyStroke,
                                      Action action) {
            comp.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, name);
            comp.getActionMap().put(name, action);
        }Call the method as:
    JTextField text=new JTextField();
    addKeyBoardAction(text, "MyTask", KeyStroke.getKeyStroke(
         KeyEvent.VK_SPACE,
         KeyEvent.CTRL_MASK), new MyAction());Thanks,
    Mrityunjoy
    Edited by: mrityunjoy on 17 Mar, 2009 6:40 PM

  • 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.

  • Focus On JTextField

    How can I put the Focus to JTextFiled when The JFrame is Displayed.

    Have you read the API for JTextField? There's a method there that will
    help. Try opening it up and searching for "focus".

Maybe you are looking for

  • ORA-17085 bug jdbc update on where statement

    hi, i'm going crazy. i have this bug since 2009 and i don't know how to do. i'm sure it's a bug from jdbc oracle (because it's working with mysql) i guess it's not possible to do update on a row where this row is in the where query. 1) Resultset with

  • Mission Photo Order

    OK, here's my mission: I've got photo's from the last ten years and they need some order. The photo's are stored on disks, on four different computers, in iPhoto, Aperture, in loose folders and any other form, place you and medium you can imagine, ev

  • Disk space for Grid Control

    Just getting started with the Grid Control. Anyone know roughly how much disk space is required for a basic installation?

  • Who i can install HPdesingjet5000 ps uv on window 7

    Hi  i have a hpdesingjet500 ps uv  the problem is  me computer not recognized the printer  i also tried to  install in windos  xp  but is the same  not recognize de printer , any can helme , wit thise issue

  • Looking for HD scrubber

    I'm selling my MBP (April '10) and have erased all the files before reinstalling Lion.  That's done and the computer seems clean.  However, I would like write over the former files for security purposes.  Is there a free program that would do this WI