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?