How to transfer focus to JPanel in a normal mouse click in Java? For some reason this does not happen automatically. What could be the reason? Program Listing:

public class Test extends JFrame implements FocusListener, MouseMotionListener { private int datePanelHeight =30; private ChartPanel chartPanel; Test() throws IOException { super("Графическое приложение"); this.setBackground(Color.WHITE); setBounds(50,50,1000, 450); this.setVisible(true); this.setVisible(false); addToolBar(); MenuBar mb = new MenuBar(); setMenuBar(mb); Menu f=new Menu("Файл"); Menu v=new Menu("Вид"); mb.add(f); mb.add(v); chartPanel = new ChartPanel(this.getContentPane().getWidth(), this.getContentPane().getHeight()); add(chartPanel); chartPanel.requestFocus(); addKeyListener(chartPanel); this.setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); System.out.println("this.getComponentCount() = "+this.getComponentCount()); } private void addToolBar(){ JToolBar tb = new JToolBar("Панель ирструментов", JToolBar.HORIZONTAL); tb.add(new JButton("Кнопка")); tb.setFloatable(true); add(tb, BorderLayout.NORTH); JTextField tf = new JTextField("0",3); tf.setMaximumSize(new Dimension(30,100)); tf.setHorizontalAlignment(JTextField.RIGHT); tb.add(tf); tb.addKeyListener(chartPanel); System.out.println("this.getComponentCount() = "+tb.getComponentCount()); } public static void main(String[] args) throws IOException { new FinanceMarketFrame(); } 

Screenshot of the program: http://clip2net.com/s/3AusFy9 Focus from the keyboard (using the tab) is transmitted successfully. When you click the mouse on the panel, the focus remains in the JTextField component. Why in this case the focus is not transmitted?

  • one
    add a focus request to the handler on clicking the panel ( requestFocusInWindow() ) - zRrr
  • What is the difference between the usual 'requestFocus ()' and 'requestFocusInWindow ()'? - Nikolay

0