Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / July 2006

Tip: Looking for answers? Try searching our database.

How to switch focus from a component to another

Thread view: 
Max010 - 26 Jul 2006 21:30 GMT
Hi there,

I was wondering if anyone can help me.  I have two JTextField and I
want to switch focus between one and the other so I can write different

words inside.

for instance here I wrote code for a button that when pressed writes
zero inside a JTextField:

void zeroButton_mouseClicked(MouseEvent e) {
 boolean b,c = false;
    if(tableNoTextField.hasFocus())
     {
     b = true;
     System.out.println(b);
      inputTableNo = inputTableNo + "0";
      System.out.println(inputTableNo);
      tableNoTextField.setText(inputTableNo);
     }
   if(noOfGuestField.hasFocus())
     {
     c = true;
     System.out.println(c);
      guestNumber = guestNumber + "0";
      System.out.println(guestNumber);
      noOfGuestField.setText(guestNumber);
      }

}

Here I tried to switch the focus between one JTextField to another but
without success:

boolean x = false;
boolean y = false;
 void tableNoTextField_mouseClicked(MouseEvent e) {

     if(tableNoTextField.hasFocus())
     {
      x = true;
     System.out.println(x);

     tableNoTextField.requestFocus();
     System.out.println("tableNoTextField has focus");
     System.out.println(y);
     }
 }

 void noOfGuestField_mouseClicked(MouseEvent e) {

     if(noOfGuestField.hasFocus())
     {
      y = true;
     System.out.println(y);

     noOfGuestField.requestFocus();
     System.out.println("noOfGuestField has focus");
     System.out.println(x);
     }
 }

Can anyone tell me how to switch the focus from one component to
another please?
Guido Zijlstra - 27 Jul 2006 08:32 GMT
I may very well be missing something here, but noOfGuestField already has
the focus (otherwise it wouldn't receive the mouseclick and your if
statement would not be true) so why would you wan't to switch the focus to
noOfGuestField? It already has it, so nothing happens.

Tnx,
Guido

>   void noOfGuestField_mouseClicked(MouseEvent e) {
>
[quoted text clipped - 11 lines]
> Can anyone tell me how to switch the focus from one component to
> another please?
Max010 - 27 Jul 2006 09:38 GMT
Thanks for your reply,

This is what I am trying to do.  I have a GUI with two jTextField and
12 buttons like a calculator with number from 0 to 9 and an ENTER
button.

When I click on the 0 button I would like the 0 to appear inside the
tableNoTextField.  Then I want to click on the noOfGuestField and click
on the 0 button and the 0 appears inside it.

However I can see that every time I click on the 0 button the
tableNoTextField and noOfGuestField lose their focus that is why
nothing happens.
I cant use the isVisible method for the if clause since both of them
are visible at the same time.

So how do I write a number inside a JTextField and write a number
inside another JTextField with the same set of buttons 0 to 9?

Thanks

> I may very well be missing something here, but noOfGuestField already has
> the focus (otherwise it wouldn't receive the mouseclick and your if
[quoted text clipped - 19 lines]
> > Can anyone tell me how to switch the focus from one component to
> > another please?
Andrew Thompson - 27 Jul 2006 10:34 GMT
Please refrain from top-posting.

> This is what I am trying to do.  I have a GUI with two jTextField and
> 12 buttons like a calculator with number from 0 to 9 and an ENTER
> button.
..
> So how do I write a number inside a JTextField and write a number
> inside another JTextField with the same set of buttons 0 to 9?

Your description and code fragments (snipped) are not
clear to me.

I suggest you post a short example of compilable code so
that people can better understand what you are attempting.
Note that an example only requires two text fields and one
button, so it should be under 20(?) lines of code.

Andrew T.
Guido Zijlstra - 27 Jul 2006 11:53 GMT
What you could do is have a variable, currentField for example,  that holds
the 'active' JTextField object. (Remember to init it to the first
JTextField)

You create methodes for either the focusGained or mouseClicked event (or
both) for the two JTextFields in which you set the currentField to the
JTextField that just got clicked.

Then in your button events you use currentField.setText to update the
selected JTextField. This should make sure that the JTextField you clicked
last (or selected via Tabbing to it) will get all the numbers you press
until you select to other textfield.

Have Fun,
Guido

> Thanks for your reply,
>
[quoted text clipped - 5 lines]
> tableNoTextField.  Then I want to click on the noOfGuestField and click
> on the 0 button and the 0 appears inside it.
Max010 - 27 Jul 2006 12:46 GMT
This is what I ve done and it seem to work altough there may be more
efficient and elegant solutions:

JTextField tableNoTextField = new JTextField();
JTextField noOfGuestField = new JTextField();
JButton zeroButton = new JButton();

tableNoTextField.setBounds(new Rectangle(171, 39, 89, 25));
   tableNoTextField.addMouseListener(new
Frame1_tableNoTextField_mouseAdapter(this));

   noOfGuestField.setBounds(new Rectangle(302, 39, 48, 25));
   noOfGuestField.addMouseListener(new
Frame1_noOfGuestField_mouseAdapter(this));

zeroButton.setText("0");
zeroButton.addMouseListener(new java.awt.event.MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
       zeroButton_mouseClicked(e);
     }
   });

void zeroButton_mouseClicked(MouseEvent e) {
   if(focus == 0 && tablePanel.isVisible() )
     {
      inputTableNo = inputTableNo + "0";
      tableNoTextField.setText(inputTableNo);
     }
   if(focus == 1)
     {
      guestNumber = guestNumber + "0";
      noOfGuestField.setText(guestNumber);
     }
 }

void tableNoTextField_mouseClicked(MouseEvent e) {
     focus = 0;
     System.out.println("The focus is "+ focus);
 }

 void noOfGuestField_mouseClicked(MouseEvent e) {
     focus = 1;
     System.out.println("The focus is "+ focus);
 }

Basically when I click on the noOfGuestField the int variable focus
becomes 1 so when I click on the zero button 0 appears inside the
noOfGuestField and vice versa if I click on the tableNoTextField the
int variable focus becomes 0 and when I click on the zero button 0
appears inside it.

I then repeated the same code for all the numbers from 1 to 9 and it
seem to work.

What do you think??

Thanks for your advices.

> What you could do is have a variable, currentField for example,  that holds
> the 'active' JTextField object. (Remember to init it to the first
[quoted text clipped - 21 lines]
> > tableNoTextField.  Then I want to click on the noOfGuestField and click
> > on the 0 button and the 0 appears inside it.
Ralf Seitner - 27 Jul 2006 14:48 GMT
Max010 schrieb:
> This is what I ve done and it seem to work altough there may be more
> efficient and elegant solutions:
[Code snippet]

Hi!
To be honest, I think your solution makes it more complicated than it
is. You really should think about using a MouseListener to determine
which component has the focus. I would advice you to use such low-level
listeners (like MouseListener) only if you really need them.
For example: If you use a FocusListener you also can handle a
focuschange if someone used the tab-key to change the focus, but also
you recognize the focuschange, if the mouse is clicked.

I wrote a little example. You can have a look at it, and perhaps it
helps... (although it is not perfect...)
It demonstrates, you do not need an extra listener for every button with
a number on it and it uses a FocusListener instead of a MouseListener.

import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Calculator extends JFrame {

    JTextField lastFocus;
    JButton[] buttons;
    JButton enter;
   
    public Calculator() {
        super();
        setTitle("Calculator Example");
        JPanel textFieldPanel = new JPanel();
        JTextField textField1 = new JTextField(10);
        JTextField textField2 = new JTextField(10);
        MyFocusListener focusListener = new MyFocusListener();
        textField1.addFocusListener(focusListener);
        textField2.addFocusListener(focusListener);
        textFieldPanel.add(textField1);
        textFieldPanel.add(textField2);
       
        ButtonListener numberListener = new ButtonListener();
       
        buttons = new JButton[10];
        for (int i=0;i<buttons.length;i++) {
            buttons[i] = new JButton(""+i);
            buttons[i].addActionListener(numberListener);
        }
        enter = new JButton("Enter");
        enter.addActionListener(new EnterButtonListener());
       
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(0,3));
        buttonPanel.add(buttons[7]);
        buttonPanel.add(buttons[8]);
        buttonPanel.add(buttons[9]);
        buttonPanel.add(buttons[4]);
        buttonPanel.add(buttons[5]);
        buttonPanel.add(buttons[6]);
        buttonPanel.add(buttons[1]);
        buttonPanel.add(buttons[2]);
        buttonPanel.add(buttons[3]);
        buttonPanel.add(buttons[0]);
        buttonPanel.add(enter);
       
        add(textFieldPanel,BorderLayout.NORTH);
        add(buttonPanel,BorderLayout.CENTER);
        lastFocus = textField1;
        setVisible(true);
        pack();
    }
   
    public static void main(String[] args) {
        Calculator calc = new Calculator();
    }
   
    private class MyFocusListener implements FocusListener {
        public void focusGained(FocusEvent e) {
            lastFocus = (JTextField) e.getSource();
        }
        public void focusLost(FocusEvent e) {       
        }
    }
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String text = lastFocus.getText();
            text = text + e.getActionCommand();
            lastFocus.setText(text);
        }
    }
    private class EnterButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            // do something...
        }
    }
}

hope that helps!
bye, Ralf
Guido Zijlstra - 27 Jul 2006 15:27 GMT
Well, if it does what you want it to, it's a working solution. You could
"improve" the code a bit by using the object oriented nature of java to
reduce code duplication etc. Have a look at the code below i hacked together
to do what you want (i think).

It reduces the code duplication by having all the buttons use the same event
routine. Also the two textfields use the same event method and it uses the
JTextField object stored in a variable to reference the correct field which
means you don't have to build an if-tree anymore.

[code]

import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FieldInput {

   JTextField currentField = null;

   public FieldInput() {

       JFrame mainFrame = new JFrame("Field Input Test");
       mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       JPanel mainPanel = new JPanel();

       mainPanel.add(new JLabel("Table :"));
       JTextField tableField = createTextField();
       mainPanel.add(tableField);
       mainPanel.add(new JLabel("Guest :"));
       JTextField guestField = createTextField();
       mainPanel.add(guestField);

       JPanel buttonPanel = new JPanel();
       for (int x = 0; x < 10; x++) {
           mainPanel.add(newButton(x));
       }

       currentField = tableField;

       mainFrame.setContentPane(mainPanel);
       mainFrame.pack();
       mainFrame.setVisible(true);
   }

   private JTextField createTextField() {
       JTextField field = new JTextField();
       field.setColumns(15);
       field.addMouseListener(new java.awt.event.MouseAdapter() {
           public void mouseClicked(MouseEvent e) {
               fieldMouseClicked(e);
           }
       });
       return(field);
   }

   private JButton newButton(int x) {
       String buttonText = Integer.toString(x);
       JButton button = new JButton(buttonText);
       button.addMouseListener(new java.awt.event.MouseAdapter() {
           public void mouseClicked(MouseEvent e) {
               buttonMouseClicked(e);
           }
       });
       return(button);
   }

   private void fieldMouseClicked(MouseEvent e) {
       currentField = (JTextField)e.getSource();
   }

   private void buttonMouseClicked(MouseEvent e) {
       JButton button = (JButton)e.getSource();
       String buttonText = button.getText();
       currentField.setText(currentField.getText() + buttonText);
   }

   public static void main(String[] args) {
       FieldInput inputPanel = new FieldInput();
   }

}

[/code]

Happy Coding,
Guido

> This is what I ve done and it seem to work altough there may be more
> efficient and elegant solutions:
[quoted text clipped - 79 lines]
> > > tableNoTextField.  Then I want to click on the noOfGuestField and click
> > > on the 0 button and the 0 appears inside it.
Guido Zijlstra - 27 Jul 2006 11:54 GMT
What you could do is have a variable, currentField for example,  that holds
the 'active' JTextField object. (Remember to init it to the first
JTextField)

You create methodes for either the focusGained or mouseClicked event (or
both) for the two JTextFields in which you set the currentField to the
JTextField that just got clicked.

Then in your button events you use currentField.setText to update the
selected JTextField. This should make sure that the JTextField you clicked
last (or selected via Tabbing to it) will get all the numbers you press
until you select to other textfield.

Have Fun,
Guido

> Thanks for your reply,
>
[quoted text clipped - 5 lines]
> tableNoTextField.  Then I want to click on the noOfGuestField and click
> on the 0 button and the 0 appears inside it.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.