0

I think my code will illustrate the problem, but basically I have a button in a Panel in a Panel in a Panel, and I want to get rid of that third Panel, but if I do I can't requestFocus anymore, because then the button disappears.

Here's my code:

import javax.swing.JFrame;

public class A{

    private JFrame frame = new JFrame();    
    private C c = new C();

    public A() {

        //Now it works
        frame.add(c.getPanel());
        frame.pack();
        frame.setVisible(true);         

        //Now it won't
        //c.getPanel().requestFocusInWindow();      
    }

    public static void main(String[] args) {
        new A();
    }
} 

and

import javax.swing.JButton;
import javax.swing.JPanel;

public class C {

    private JPanel mainpanel;
    private JButton button;

    public C(){
        button = new JButton("Back");

        //This fixes the issue, if you comment that same line in getPanel()
        //mainpanel = createPanel();
    }

    private JPanel createPanel() {

        JPanel panel = new JPanel();
        panel.add(button);

        return panel;   
    }

    public JPanel getPanel(){
        mainpanel = createPanel();
        return mainpanel;
        //I actually want it to be return createPanel(); getting rid of mainpanel altogether
    }
}

This is just example code, I left out everything that isn't important.

I want to call createPanel() in getPanel() to update the Panel before it's used, and I want the focus so I can navigate by Keyboard.

What am I doing wrong?

  • @trashgod Nowhere, since it doesn't change anything. edit: It doesn't solve the problem is what I mean. – Lennart Bergmann Aug 03 '14 at 14:29
  • If you don't invoke `pack()` _before_ `setVisible()`, it will likely be called at a less convenient time. Also, [Don't use `setSize()` when you really mean to override `getPreferredSize()`](http://stackoverflow.com/q/7229226/230513). – trashgod Aug 03 '14 at 14:33
  • Ok, I call pack, and I just took out 'setSize()' because it's not necessary, but the problem's still there. – Lennart Bergmann Aug 03 '14 at 14:37
  • 1
    @user3692435: Don't you think `c.getPanel()` is creating a new instance of `JPanel` for each call. Now since you added the `JButton` on this new `JPanel` it will obviously be removed from the previous `JPanel` it is on and placed on the new `JPanel` that is being created with the call to `getPanel()`. But now when you calling `c.getPanel().requestFocusInWindow()` this newly created `JPanel` is never added to the already laid components, hence you are unable to see what is going on. – nIcE cOw Aug 03 '14 at 14:41

0 Answers0