I've made a gui for my application. The JFrame has 2 JPanels, panel1 & panel2. panel1 is just that, a JPanel with a custom painting that repaints itself every 5 ms.
panel2 is my first attempt at a CardLayout implementation: it contains JPanels subPanel1 & subPanel2. subPanel1 contains a JComboBox and is added to panel2: panel2.add(subPanel1);
.
subPanel2 has the .setLayout(new CardLayout());
command, and I add 3 new JPanels into it, with appropiate itemListener and all. Of course I also add it: panel2.add(subPanel2);
Now to the problem: focusing components in Java. I have knowledge of methods setFocusable(boolean)
and requestFocus()
. But I can't make them behave in any logical way.
First, the root problem of them all: When the combobox gets the focus, I can't unfocus it at all (tried clicking everywhere with cursor).
Following are experiments I've conducted:
1) without any code speaking to focus throughout the application the combobox starts with the focus, no matter which order panel1 and panel2 are added to the JFrame.
2) if I set panel1.setFocusable(true);
(in its constructor) it will start with the focus
3) if I set panel1.setFocusable(false);
and also request focus to it, it doesn't get it. (only thing that works as expected)
4) if I set panel2, subPanel1, or subPanel2 unfocusable individually or in any combination, they can still receive focus (the combobox, that is, which is the only component able to register focus).
5) if I set the combobox unfocusable, I'm still able to scroll between the cards in the CardLayout with the box' itemListener, but the focus doesn't stick to it. In fact panel1 still registers keyboard-inputs
So really I am very confused about the whole 'focus' thing. Maybe it is not what I assume it is? What I am trying to do is entirely block all interaction with panel2 untill a flag (which is evaluated every 5 ms) is true. Am I correct to assume that unlike JPanels, the JComboBox automatically has a mousebuttonListener to gain focus when clicked? if no, then how do I completely disable the JComboBox and all components the current card is displaying?
Is it normal behavior that components within an unfocusable component are still focusable?
See Question&Answers more detail:
os