Kenny
Kenny

Reputation: 177

Set focus in a JPanel

I want my focus in the CenterPanel.java, but the focus is in the TopPanel.java class.

Main.java

public class Main {
    public static void main(String[] args) {
        new MainFrame();
    }
}

MainFrame.java

public class MainFrame extends JFrame {
    public MainFrame() {
        super();
        setTitle("Title");
        setVisible(true);
        MainPanel mainpanel = new MainPanel();
        setContentPane(mainpanel);
        pack();
    }
}

MainPanel.java (Called from Main.java)

public class MainPanel extends JPanel {
    private TopPanel topPanel;
    private CenterPanel centerPanel;
    public MainPanel() {
        createComponents();
        addComponents();
    }

    private void createComponents() {
        centerPanel = new CenterPanel();
        topPanel = new TopPanel(centerPanel);
    }

    private void addComponents() {
        add(centerPanel);
        add(topPanel, BorderLayout.NORTH);
    }
}

TopPanel.java

public class TopPanel extends JPanel {
    private JButton aButton;
    private CenterPanel centerPanel;

    public TopPanel(CenterPanel c) {
        centerPanel = c;
        createComponents();
        addComponents();
    }

    private void createComponents() {
        aButton = new Button("Button");
    }

    private void addComponents() {
        add(aButton);
    }
}

CenterPanel.java

public class CenterPanel extends JPanel {
    public CenterPanel() {
        setFocusable(true);
        setRequestFocusEnabled(true);
        requestFocus();

        addKeyListener(new MoveController());
    }
}

MoveController.java

public class MoveController extends KeyAdapter {
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("Pressed");
    }

    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println("Released");
    }
}

Upvotes: 1

Views: 3187

Answers (2)

camickr
camickr

Reputation: 324118

You should be using requestFocusInWndow(), not requestFocus(). Read the API documentation for the reason.

Also, you can only request focus on a component when the component is displayed in a visible GUI. Given the structure of your code it is not easy to access the "CenterPanel" once you make the GUI visible.

Check out Dialog Focus which shows how you can use the RequestFocusListener to request focus on a component even when the GUI is not yet visible.

Upvotes: 3

StanislavL
StanislavL

Reputation: 57381

Move the setVisible(true) to be the last in you main() method

Move the requestFocus(); call from the constructor and call it after the layout is done (may be even after the setVisible() call.

NOTE: It's better to use KeyBindings rather than KeyListener to rpocess separate events. KeyListener is good if you need realy multiple key events (e.g. typing)

Upvotes: 3

Related Questions