Skip to main content

Focuslistener-How I would like to work it

No replies
leo_test
Offline
Joined: 2004-04-27
Points: 0

I have the following sample-code:

<br />
package at.HexLib.GUI.test;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class SampleFocus extends JFrame {

  public SampleFocus(String titel) {
    setTitle(titel);
    JTextField txtField1 = new JTextField(&quot;default-click&quot;);
    JTextField txtField2 = new JTextField(&quot;alternative-Text&quot;);
    JTextField txtField3 = new JTextField(&quot;own diaolog textfield&quot;);

    JTextArea dummyLabel = new JTextArea(10, 20);
    dummyLabel.setText(&quot;empty textarea, which is focusable&quot;);

    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    add(txtField1);
    add(dummyLabel);
    add(txtField2);

    JDialog altDialog = new JDialog(this);
    altDialog.add(txtField3);
    altDialog.setVisible(true);
    altDialog.pack();

    FocusAdapter myFocusListner = new FocusAdapter() {

      @Override
      public void focusGained(FocusEvent e) {
        if (e.getComponent() instanceof JTextField) {
          System.out.println(&quot;gained for TextField: &quot;
                             + ((JTextField) e.getComponent()).getText());
        } else {
          System.out.println(&quot;gained for component: &quot; + e.getComponent());
        }
      }
    };

    txtField1.addFocusListener(myFocusListner);
    txtField2.addFocusListener(myFocusListner);
    txtField3.addFocusListener(myFocusListner);

    // dummyLabel.addFocusListener(myFocusListner);
  }

  public static void main(String[] args) {
    JFrame frame = new SampleFocus(&quot;FocusListener  - sample&quot;);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

  }
}

When I switch from the Frame to the dialog I get the proper event. When I switch back to the Frame I get as well the proper FocusEvents. My problem is, that when I switch back, I get as well the focusevents for the component which I am not interested in.
e.g.
Select 'default-click' ==> Dialog/Textfield ==> Frame/'empty textarea'
Result: I get a FocusGained-Event for 'default-click' although the component has NOT the focus.
Desired Result: Either
- Component 'default-click' does not get the FocusEvent OR
- distinguish if the component really received the Event properly (e.g. I could have clicked into it as well)
Workaround I found:
Attach to the JTextArea as well a FocusListener. Problem is, that this would mean, I need to attach to ALLLL of my components a Listener. Which is hardly possible. Any ideas?
Thx LeO