Skip to main content

Focus getting stuck in JDK1.4.1_03

2 replies [Last post]
vijayakumarpl
Offline
Joined: 2005-02-08
Points: 0

Below is my sample program. There are 3 buttons b0, b1, b2. When i press b1, i hide b1 and remove b1 and requestFoucs for b0. But what happens is b2 gets focus and only when i move the mouse over the frame b0 gets focus.

<br />
import javax.swing.*;<br />
import java.awt.event.*;<br />
public class FocusLost<br />
{<br />
    public static void main(String s[])<br />
    {<br />
        final JFrame fr = new JFrame("FoucsLost");<br />
        final JButton b0 = new JButton("Zero");<br />
        final JButton b1 = new JButton("One");<br />
        JButton b2 = new JButton("Two");<br />
        b1.addActionListener(new ActionListener()<br />
                {<br />
                public void actionPerformed(ActionEvent e)<br />
                {</p>
<p>                b1.setVisible(false);<br />
                fr.getContentPane().remove(b1);<br />
                b0.requestFocus();<br />
                }<br />
                });<br />
        FocusListener fl = new FocusListener()<br />
        {<br />
            public void focusGained(FocusEvent e)<br />
            {<br />
                System.out.println("focusGained : " + ((JButton)e.getSource()).getText());<br />
            }<br />
            public void focusLost(FocusEvent e)<br />
            {<br />
                System.out.println("focusLost : " + ((JButton)e.getSource()).getText());<br />
            }<br />
        };</p>
<p>        b0.addFocusListener(fl);<br />
        b1.addFocusListener(fl);<br />
        b2.addFocusListener(fl);</p>
<p>        fr.getContentPane().add(b0,"North");<br />
        fr.getContentPane().add(b1);<br />
        fr.getContentPane().add(b2,"South");<br />
        fr.setSize(200,200);<br />
        fr.setVisible(true);</p>
<p>    }<br />
}</p>
<p>

Admin added code tags for readability

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kleopatra
Offline
Joined: 2003-06-11
Points: 0

> Below is my sample program. There are 3 buttons b0,
> b1, b2. When i press b1, i hide b1 and remove b1 and
> requestFoucs for b0. But what happens is b2 gets
> focus and only when i move the mouse over the frame
> b0 gets focus.
>

[code snipped]

wrap the requestFocus into an invokeLater - this will work around the problem in pre1.4.2

Greetings
Jeanette

oleg.sukhodolsky
Offline
Joined: 2006-02-17
Points: 0

I believe this is bacause of the bug 4648816 (Sometimes focus requests on LW components are delayed). It's fixed in 1.4.2. As a workaround for this you could try to send some event (e.g. using EventQueue.invokeLater()) just after b2 receives focus.

Hope this helps, Oleg.