Focus on JTextfield in JDialog box

A JDialog box is being opened from a menu.
There is only one JTextfield on the dialog box and 2 buttons.
The focus is not on any of the components in the dialog box and I want it on the textfield by default.
I have tried all the requestFocus(),requestDefaultFocus(),grabfocus() etc and none of them work.
There is an eventListener added to the JTextfield could this be the problem.

I am a little supprised that the focus is not given to the text field if that is the only thing on the dialog.
You could try detecting the display of the dialog and then giving the focus to the text field. Focus will not be given to a component if the component cant be displayed at that time. My guess is that the dialog is still hidden when you are trying to set the focus and that is what is causing the problem.

Similar Messages

  • Problem with JDialog box

    Hi Guys,
    I have a problem with the JDialog box. The close button (Cross mark of the box) is not displayed when I was trying to use my custom LookAndFeel and Custom theme. I am pasting the code sample here.
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.LookAndFeel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    import javax.swing.plaf.ColorUIResource;
    import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
    import com.jgoodies.looks.plastic.PlasticTheme;
    import com.medplexus.looks.plastic.theme.SkyGreen;
    public class TestTheDialog implements ActionListener {
    JFrame mainFrame = null;
    JButton myButton = null;
    public TestTheDialog() {
    mainFrame = new JFrame("TestTheDialog Tester");
    mainFrame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    try{
         MyLookAndFeel.setCurrentTheme(new CustomLaF());
         UIManager.setLookAndFeel(new MyLookAndFeel());
         SwingUtilities.updateComponentTreeUI(mainFrame);
         CustomDialog cd = new CustomDialog();
         cd.setDefaultLookAndFeelDecorated(true);
    catch(Exception e){
    myButton = new JButton("Test the dialog!");
    myButton.addActionListener(this);
    mainFrame.setLocationRelativeTo(null);
    mainFrame.getContentPane().add(myButton);
    mainFrame.setSize(200, 150);
    //mainFrame.pack();
    mainFrame.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    if(myButton == e.getSource()) {
    System.err.println("Opening dialog.");
    CustomDialog myDialog = new CustomDialog(mainFrame, true, "Do you like Java?");
    System.err.println("After opening dialog.");
    if(myDialog.getAnswer()) {
    System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
    else {
    System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
    static class CustomLaF extends PlasticTheme {
    protected ColorUIResource getPrimary1() {
    return new ColorUIResource(255,128,0);
    public ColorUIResource getPrimary2() {
              return (new ColorUIResource(Color.white));
         public ColorUIResource getPrimary3() {
              return (new ColorUIResource(255,128,0));
    public ColorUIResource getPrimaryControl() {
    return new ColorUIResource(Color.GREEN);
    protected ColorUIResource getSecondary1() {
    return new ColorUIResource(Color.CYAN);
    protected ColorUIResource getSecondary2() {
              return (new ColorUIResource(Color.gray));
         protected ColorUIResource getSecondary3() {
              return (new ColorUIResource(235,235,235));
         protected ColorUIResource getBlack() {
              return BLACK;
         protected ColorUIResource getWhite() {
              return WHITE;
         private Object getIconResource(String s) {
    return LookAndFeel.makeIcon(getClass(), s);
    private Icon getHastenedIcon(String s, UIDefaults uidefaults) {
    Object obj = getIconResource(s);
    return (Icon) ((javax.swing.UIDefaults.LazyValue) obj).createValue(uidefaults);
    static class MyLookAndFeel extends Plastic3DLookAndFeel {
              protected void initClassDefaults(UIDefaults table) {
                   super.initClassDefaults(table);
              protected void initComponentDefaults(UIDefaults table) {
                   super.initComponentDefaults(table);
                   Object[] defaults = {
                             "MenuItem.foreground",new ColorUIResource(Color.white),
                             "MenuItem.background",new ColorUIResource(Color.gray),
                             "MenuItem.selectionForeground",new ColorUIResource(Color.gray),
                             "MenuItem.selectionBackground",new ColorUIResource(Color.white),
                             "Menu.selectionForeground", new ColorUIResource(Color.white),
                             "Menu.selectionBackground", new ColorUIResource(Color.gray),
                             "MenuBar.background", new ColorUIResource(235,235,235),
                             "Menu.background", new ColorUIResource(235,235,235),
                             "Desktop.background",new ColorUIResource(235,235,235),
                             "Button.select",new ColorUIResource(255,128,0),
                             "Button.focus",new ColorUIResource(255,128,0),
                             "TableHeader.background", new ColorUIResource(255,128,0),
                             "TableHeader.foreground", new ColorUIResource(Color.white),
                             "ScrollBar.background", new ColorUIResource(235,235,235),
                             "OptionPane.questionDialog.border.background", new ColorUIResource(Color.gray),
                             "OptionPane.errorDialog.titlePane.foreground", new ColorUIResource(Color.white),
                             "OptionPane.questionDialog.titlePane.background", new ColorUIResource(255,128,0),
                             "InternalFrame.borderColor", new ColorUIResource(Color.gray),
                             "InternalFrame.activeTitleForeground", new ColorUIResource(Color.white),
                             "InternalFrame.activeTitleBackground", new ColorUIResource(Color.gray),
                             "InternalFrame.borderColor", new ColorUIResource(Color.white),
                             "Table.selectionBackground",new ColorUIResource(255,128,0)
                   table.putDefaults(defaults);
    public static void main(String argv[]) {
    TestTheDialog tester = new TestTheDialog();
    package CustomThemes;
    import javax.swing.JDialog;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    public class CustomDialog extends JDialog implements ActionListener {
    private JPanel myPanel = null;
    private JButton yesButton = null;
    private JButton noButton = null;
    private boolean answer = false;
    public boolean getAnswer() { return answer; }
    public CustomDialog(){
    public CustomDialog(JFrame frame, boolean modal, String myMessage) {
    super(frame, modal);
    setTitle("Guess?");
    myPanel = new JPanel();
    getContentPane().add(myPanel);
    myPanel.add(new JLabel(myMessage));
    yesButton = new JButton("Yes");
    yesButton.addActionListener(this);
    myPanel.add(yesButton);
    noButton = new JButton("No");
    noButton.addActionListener(this);
    myPanel.add(noButton);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    setLocationRelativeTo(frame);
    setVisible(true);
    public void actionPerformed(ActionEvent e) {
    if(yesButton == e.getSource()) {
    System.err.println("User chose yes.");
    answer = true;
    setVisible(false);
    else if(noButton == e.getSource()) {
    System.err.println("User chose no.");
    answer = false;
    setVisible(false);
    Thanks and Regards
    Kumar.

    Hi All,
    I am using the JGoodies Look and feel (looks2.0.1.jar). I wrote my own custom LookAndFeel and Theme , but the problem with this is the JDialog/JOptionPane dialog boxes are displayed with out the close button (cross button on the titlebar).
    I am pasting the code here.
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.Icon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.LookAndFeel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    import javax.swing.plaf.ColorUIResource;
    import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
    import com.jgoodies.looks.plastic.PlasticTheme;
    import com.medplexus.looks.plastic.theme.SkyGreen;
    public class TestTheDialog implements ActionListener {
        JFrame mainFrame = null;
        JButton myButton = null;
        public TestTheDialog() {
            mainFrame = new JFrame("TestTheDialog Tester");
            mainFrame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {System.exit(0);}
            try{
                 MyLookAndFeel.setCurrentTheme(new CustomLaF());
                 UIManager.setLookAndFeel(new MyLookAndFeel());
                 //Plastic3DLookAndFeel.setCurrentTheme(new SkyGreen());
                 //UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
                 SwingUtilities.updateComponentTreeUI(mainFrame);
                 CustomDialog cd = new CustomDialog();
                 cd.setDefaultLookAndFeelDecorated(true);
            catch(Exception e){
            myButton = new JButton("Test the dialog!");
            myButton.addActionListener(this);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.getContentPane().add(myButton);
            mainFrame.setSize(200, 150);
            //mainFrame.pack();
            mainFrame.setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(myButton == e.getSource()) {
                System.err.println("Opening dialog.");
                CustomDialog myDialog = new CustomDialog(mainFrame, true, "Do you like Java?");
                System.err.println("After opening dialog.");
                if(myDialog.getAnswer()) {
                    System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
                else {
                    System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
        static class CustomLaF extends PlasticTheme {
            protected ColorUIResource getPrimary1() {
              return new ColorUIResource(255,128,0);
            public ColorUIResource getPrimary2() {
                  return (new ColorUIResource(Color.white));
             public ColorUIResource getPrimary3() {
                  return (new ColorUIResource(255,128,0));
            public ColorUIResource getPrimaryControl() {
              return new ColorUIResource(Color.GREEN);
            protected ColorUIResource getSecondary1() {
              return new ColorUIResource(Color.CYAN);
            protected ColorUIResource getSecondary2() {
                  return (new ColorUIResource(Color.gray));
             protected ColorUIResource getSecondary3() {
                  return (new ColorUIResource(235,235,235));
             protected ColorUIResource getBlack() {
                  return BLACK;
             protected ColorUIResource getWhite() {
                  return WHITE;
             private Object getIconResource(String s) {
                return LookAndFeel.makeIcon(getClass(), s);
            private Icon getHastenedIcon(String s, UIDefaults uidefaults) {
                Object obj = getIconResource(s);
                return (Icon) ((javax.swing.UIDefaults.LazyValue) obj).createValue(uidefaults);
          static class MyLookAndFeel extends Plastic3DLookAndFeel {
                  protected void initClassDefaults(UIDefaults table) {
                       super.initClassDefaults(table);
                  protected void initComponentDefaults(UIDefaults table) {
                       super.initComponentDefaults(table);
                       Object[] defaults = {
                                 "MenuItem.foreground",new ColorUIResource(Color.white),
                                 "MenuItem.background",new ColorUIResource(Color.gray),
                                 "MenuItem.selectionForeground",new ColorUIResource(Color.gray),
                                 "MenuItem.selectionBackground",new ColorUIResource(Color.white),
                                 "Menu.selectionForeground", new ColorUIResource(Color.white),
                                 "Menu.selectionBackground", new ColorUIResource(Color.gray),
                                 "MenuBar.background", new ColorUIResource(235,235,235),
                                 "Menu.background", new ColorUIResource(235,235,235),
                                 "Desktop.background",new ColorUIResource(235,235,235),
                                 "Button.select",new ColorUIResource(255,128,0),
                                 "Button.focus",new ColorUIResource(255,128,0),
                                 "TableHeader.background", new ColorUIResource(255,128,0),
                                 "TableHeader.foreground", new ColorUIResource(Color.white),
                                 "ScrollBar.background",  new ColorUIResource(235,235,235),
                                 "OptionPane.questionDialog.border.background", new ColorUIResource(Color.gray),
                                 "OptionPane.errorDialog.titlePane.foreground", new ColorUIResource(Color.white),
                                 "OptionPane.questionDialog.titlePane.background", new ColorUIResource(255,128,0),
                                 "InternalFrame.borderColor", new ColorUIResource(Color.gray),
                                 "InternalFrame.activeTitleForeground", new ColorUIResource(Color.white),
                                 "InternalFrame.activeTitleBackground", new ColorUIResource(Color.gray),
                                 "InternalFrame.borderColor", new ColorUIResource(Color.white),
                                 "Table.selectionBackground",new ColorUIResource(255,128,0)
                       table.putDefaults(defaults);
        public static void main(String argv[]) {
            TestTheDialog tester = new TestTheDialog();
    import javax.swing.JDialog;
    import java.awt.event.ActionListener;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JButton;
    import java.awt.event.ActionEvent;
    public class CustomDialog extends JDialog implements ActionListener {
        private JPanel myPanel = null;
        private JButton yesButton = null;
        private JButton noButton = null;
        private boolean answer = false;
        public boolean getAnswer() { return answer; }
        public CustomDialog(){
        public CustomDialog(JFrame frame, boolean modal, String myMessage) {
            super(frame, modal);
            setTitle("Guess?");
            myPanel = new JPanel();
            getContentPane().add(myPanel);
            myPanel.add(new JLabel(myMessage));
            yesButton = new JButton("Yes");
            yesButton.addActionListener(this);
            myPanel.add(yesButton);       
            noButton = new JButton("No");
            noButton.addActionListener(this);
            myPanel.add(noButton);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setLocationRelativeTo(frame);
            setVisible(true);
        public void actionPerformed(ActionEvent e) {
            if(yesButton == e.getSource()) {
                System.err.println("User chose yes.");
                answer = true;
                setVisible(false);
            else if(noButton == e.getSource()) {
                System.err.println("User chose no.");
                answer = false;
                setVisible(false);
    }Thanks and Regards
    Kumar.

  • Help needed: Creating web link in JDialog Box

    I'm in need of this urgently, any help would be much appreciated. I'm currently display some information in a JDialog box when an item is clicked in a JApplet.
    I need to display a weblink within the dialog box.
    Thanks anyone

    I am using JDeveloper 10.1.3.3.0. Thanks Heaps

  • If I delete a message using delete key, AND the "Find in this message" box is open, should the focus switch to the search box, or remain in the message list?

    If the "Find in this message" search box has been left open, but I have selected a message in the message pane, if I use the delete key to delete the current message, the focus moves to the "Find" box. It took me a while to figure out why the focus did not remain in the message list so I could delete the next message. I can regain the desired behavior by closing the search box, but it would be nice to not need to. This is on a Windows 7 OS. I should check to see how it behaves on a Linux box.

    Hi,
    for the Points 
    Sometime I think I would like it if I could delete an iMessage completely.
    Other times when reading them on my iPhone I wish to leave them until I can answer them with something that is on my Mac.
    It seems that as a device or a Mac that is off line can "catch up" on iMessages sent within a few hours would suggest that the iMessages are held on the server for a period.
    It would be handy for different levels of "deletion".
    7:19 PM      Monday; February 11, 2013
    Please, if posting Logs, do not post any Log info after the line "Binary Images for iChat"
      iMac 2.5Ghz 5i 2011 (Mountain Lion 10.8.2)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
     Couple of iPhones and an iPad
    "Limit the Logs to the Bits above Binary Images."  No, Seriously

  • KeyEvent calling JDialog box flickers

    On a JFrame I have a button with an ActionPerformed() method. On pressing the button a dialog box pops up on the screen as it is meant to do. This functionality is also needed to be assigned to the 'F1' key as well. In the same class I have a keyReleased() method that listens when the F1 key is pressed. For the VK_F1 KeyEvent I have put the same lines of code that I put in the ActionPerformed() method of the button. When F1 is pressed, the JDialog appears but it flickers for the first few seconds which is annoying. Does any one know why the JDialog box flickers and how to solve this.

    has any one got any sugguestions how to solve a flickering JDialog box in general???

  • JDialog boxes

    Hi,
    Just a bit curious whats the best way to creat a JDialog box?
    I currently have have one main panel, with one button. When the user clicks this button, it brind up the dialog box. I dont think i have done this correctly, as when the dialog box populates, when I move it around on the screen, it erases the contents off the panel that called the dialog (erases the contents when i move the dialog accross the screen.
    Can any one help me set out the correct constructors for the DIalog and the panel calling it?
    thanks in advance
    public public class PanelA extends JPanel {
    public class Dialoig Box extends JDialog {
    public class GUI {
    public () {
    //code here to add a jbutton to panelA
    //code here to add PanelA to the frame
    //inner class here . Action listener for the button
    class CheckButtonActionListener
    implements ActionListener {
    public void actionPerformed(ActionEvent event) {
    //Main method here
    Main frame = new Main();

    import javax.swing.*;
    public class Main extends javax.swing.JFrame {
        public Main() {
            initComponents();
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Test Dialog Box");
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jPanel1.add(jButton1);
            getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-401)/2, (screenSize.height-411)/2, 401, 411);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            JDialog dialog = new DialogBox(this,true);
            dialog.setVisible(true);
        public static void main(String args[]) {
            new Main().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
        public class DialogBox extends javax.swing.JDialog {
            public DialogBox(java.awt.Frame parent, boolean modal) {
                super(parent, modal);
                initComponents();
            private void initComponents() {
                jPanel1 = new javax.swing.JPanel();
                jButton1 = new javax.swing.JButton();
                setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
                setTitle("Dialog Box");
                jButton1.setText("jButton1");
                jButton1.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        jButtonActionPerformed(evt);
                jPanel1.add(jButton1);
                getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
                java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
                setBounds((screenSize.width-237)/2, (screenSize.height-191)/2, 237, 191);
            private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
                setVisible(false);
                dispose();
            private javax.swing.JButton jButton1;
            private javax.swing.JPanel jPanel1;
    }

  • Script that will automaticly set the focus to the next text box after the previous one is completed

    Specificly, entering a SSN into a form with three text boxes. 1st box for first 3 digits, 2nd box for middle 2 digits, and 3rd box for last 4 digits. I would like the user to be able to enter the 1st three digits into the 1st box, and after the 3rd digit is entered, the focus jumps to the 2nd box, then once the middle two are entered, the focus jumps the the 3rd box without having to manually use the tab key to advance through the boxes. Thanks.

    See JavaScript - setFocus Method for tabbing to next form field for a sample form that uses a document level script and custom keystroke script. See Entering Document Scripts and Entering scripts for form fields by Thom Parker for detailed instructions on entering or viewing these type of scripts.

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

  • 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);}
    }

  • Auto-shift of focus between JTextFields

    Greetings.
    I have an array of 50 JTextFields which I restricted to a four-character entry limit. The limit works just fine, but I would like the focus to shift to the next JTextField when the limit is reached. Currently, I'm watching for the limit via an extended PlainDocument called CharLimitDocument. (*code included below) I know that Java offers the function FocusManager.focusNextComponent(Component aComp), but I'm not sure how to retrieve the current component. Can anyone help?
    Thanks in advance,
    Liz
    *CharLimitDocument Code
    import javax.swing.text.*;
    import java.awt.*;
    //This class overloads the Document so that a JTextField can be designed to accept only a specific number of characters.
    class CharLimitDocument extends PlainDocument
    private int limit;
    public CharLimitDocument(int limit)
    {  this.limit = limit;  }
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
    if((str.length() + getLength()) <= limit)
    {     super.insertString(offs, str, a);     }
    else
    {     Toolkit.getDefaultToolkit().beep();     }
    }//end class CharLimitDocument

    Maybe you were talking about this function in javax.swing.JComponent?
    hasFocus() (returns boolean)
    You could test each component to see if it hasFocus() and then you'd be able to retrieve the 'current' component (pseudo code below). Even though you have fifty fields, this still woudn't be memory/processor intensive.
    Hope that helps,
    H
    int compindex=0;
    while((compindex)<=(getComponentCount()))
         if(getComponent(compindex).hasFocus()==true)
         {this is the current component... do whatever;}
         else
         {compindex++;}
    }

  • How to set focus on JTextField

    hi everyone,
    i have a JTextFields on my form. i have a reset button. i want keh when i click it all the fields get default value(that i have done) and focus is set on any of the JTextFields. please tell me how to do that.
    thanks & regards

    i triend using requestFocus method but i coouldn't get
    please tell me the wayread the docs
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.htmlor, post a small demo program explaining:
    what it is you expect, and
    what it is you get

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

  • Can't get focused a JTextField within a JTable cell

    I have a table and I placed a cell editor with a JText field on it for all cell editing,
    I want to do things when the focus is lost or gained and my app works fine when a cell is double clicked or f2 is pressed, but when a cell is selected (without double clicking) and just begin typing it produces no focus gained event.
    I tried by calling grabFocus method of that jTextField within the overriden prepareEditor method of the JTable but it doesn't get focus (doesn't even gains and loses it :s )
    Does anyone have an idea of how to force this component to grab focus?
    Thanks

    Hai,
    dont add the FocusListener to the EditorComponent.
    Try to use the JTable Functions - like this:
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import javax.swing.*;
    public class Test extends JFrame
         JTable table;
         JTextArea text;
         JScrollPane scroll;
         JTextField cellTextField;
         Test()
              DefaultTableModel model = new DefaultTableModel();
              cellTextField = new JTextField();
              text = new JTextArea();
              text.setEditable(false);
              scroll = new JScrollPane();
              scroll.setViewportView(text);
              table = new JTable(model){
                   @Override
                   public Component prepareEditor(TableCellEditor editor, int row, int column) {
                        text.append("Better use this to Start Edit!\n");
                        return super.prepareEditor(editor, row, column);
                   @Override
                   public void editingStopped(ChangeEvent e) {
                        text.append("Better use this to Stop Edit!\n");
                        super.editingStopped(e);
              model.addColumn("Column 1");
              model.addColumn("Column 2");          
              model.addRow(new String [] {"Cell 1", "Cell 2"});
              table.setCellSelectionEnabled( true );
              table.getColumnModel().getColumn(0).setCellEditor( new DefaultCellEditor(cellTextField));
              table.getColumnModel().getColumn(1).setCellEditor( new DefaultCellEditor(cellTextField));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(table, BorderLayout.NORTH);
              getContentPane().add(scroll, BorderLayout.CENTER);
              setSize(300, 300);
              setVisible(true);
              setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         public static void main(String[] args)
              new Test();
    }

  • Getting focus on JTextField?

    I made a chat with a JApplet. In my chat i have a JTextField where users can write messages. I want to have focus on this JTextfield all the time, the user should not be allowed to get focus somewhere else. How can I do that? I tried requestFocus(); but its not making any differants. I use gridbaglayout and this is how I create my JTextfield:
    beskedFelt = new JTextField(10);
    c.insets = new Insets(10,0,0,0);
    c.gridx = 1;
    c.gridy = 2;
    gridbag.setConstraints(beskedFelt, c);
    contentPane.add(beskedFelt);
    beskedFelt.setEditable(true);
    beskedFelt.addActionListener(this);
    beskedFelt.requestFocus();
    thx for your time....

    yesss it worked:
    beskedFelt = new JTextField(10);
    EventQueue.invokeLater(new Runnable() {
    public void run() {
    beskedFelt.requestFocus();
    c.insets = new Insets(10,0,0,0);
    c.gridx = 1;
    c.gridy = 2;
    gridbag.setConstraints(beskedFelt, c);
    contentPane.add(beskedFelt);
    beskedFelt.setEditable(true);
    beskedFelt.addFocusListener(this);
    beskedFelt.addActionListener(this);
    public void focusGained(java.awt.event.FocusEvent fe)
    public void focusLost(java.awt.event.FocusEvent fe)
              Object source = fe.getSource();
              if ( source == beskedFelt)
    beskedFelt.requestFocus();
    thx a lot ppl....

  • Series of JDialog boxes

    Hi everyone,
    While installing any software we usually come across a series of dialog boxes with 'Back'
    and 'Next' buttons; I have to do something similar in our project. I am generating a series of dialog boxes without any problem using JDialog in Swing. But the problem is
    When the user enters some values in first dialog box and clicks 'Next' button and goes to the
    second dialog box and then comes back to the first dialog box using the 'Back' button in the second dialog box, I have to display the first dialog box with those values which the user entered previously so that he need not enter them again. How to do this?
    Thanks in advance. (I actually did it successfully by using event handling, but is there a better way of doing it like writing the values entered by the user into some text file and then retrieving them from the text file while displaying the dialog box?)

    Here's one way. Your dialog class should implement an interface such as
    public interface InputPage
    public void takeState (Hashtable ht);
    public void giveState (Hashtable ht);
    A "director" class maintains the sequence of InputPage implementations
    and listens for "next" and "back" events. When a page comes into view,
    that director invokes takeState(); and when a page goes out of view, the
    director invokes giveState(). In this way, the pages propogate the data
    back and forth.

Maybe you are looking for

  • No of day in a month

    I want to count the number of days for a month using sysdate and then multiply it with an amount. how do i do that . for eg if my sysdate is 27th june then june being a 30 days month i need to multiply 30 with the ammount. Ammount * 30. if my sysdate

  • Deployment issue with EPMA & Planning in 11.1.2

    Hi I installed the following applications of Hyperion suite: Essbase EPMA CalcManager Planning During configuring i configured each product separately since i wanted to configure separate DB for each of them. The configuration went with no issues. Bu

  • ERROR - no available datasource for source system exist

    I tried to load the master for 0Bill_Type 1) Install infoobject business content and Create infoobject 2) Activate datasource in R/3 3) Replicate datasource 4) Assign infosource ---> the error said no available datasource for source system exist When

  • FaceTime still not working after restore/hard reset

    Any ideas guys done apple support don't know that the issue is either.  I have five devices all same issue since upgrading iso7.

  • Role for just importing documents to workspace

    It seems we need to add users to content publisher role to import document to file system so they can attach them to a cell in planning. That role gives them data source management. Is there a better role for just importing documents?