Java requestFocus() not working at the constructor - java

In my Java Swing Application Reuestfocus method not working at the Constructor. But it works if I used requestfocus along with button action listener. I want set Requestfocus at the form load. I dont understand whats the wrong here. P.S I use JInternal Frame
txtItemName.requestFocusInWindow (); // did not work
txtItemName.requestFocus (); // did not work
public ItemMgt() {
initComponents();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
txtItemName.requestFocus(); // did not work
}
});
}
private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
txtItemName.requestFocus(); // did not work.
}

The case might by that your component is not visible, so the GUI manager can not set focus on it.
As is specified in documentation:
(..) component must be displayable, focusable, visible and all of its ancestors (with the exception of the top-level Window) must be visible for the request to be granted.
Generally you should avoid to have so robust logic in constructor. Your graphic components should be constructed first. When this is finished they should be adjusted to your preferences.
Instead of requestFocus(), it is recomended to use requestFocusInWindow() for more please visit the tutorial: How to Use the Focus Subsystem

If you are using Netbeans IDE, then its much easier. Just make sure that all controls before your textbox are not focusable by unchecking the 'focusable' property in the Properties window. This will leave your textbox as the first focusable control thus allowing it to receive focus when the internal frame is opened

Related

Why is componentShown() not called?

I have a CardDetailsPanel class which contains several JLabels and JTextFields. This class in contained in a AddCardsPanel and is initialized as follows:
cardDetailsPanel = new CardDetailsPanel(true);
add(cardDetailsPanel, java.awt.BorderLayout.CENTER);
I also have a JLabel that contains instructions. I want to update this label when the CardDetailsPanel first appears and when focus changes to each JTextField. I have found the addFocusListener() method that will work for the later. However, my compenentShown() method isn't working for the former:
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
(Okay, I know this is ugly. It was generated by NetBeans.)
private void formComponentShown(java.awt.event.ComponentEvent evt) {
this.frame = (BaseballFrame) this.getParent().getParent().getParent().getParent().getParent().getParent();
}
(Yah, this is even uglier. I'll deal with the chained getParent() calls later. I want to do other things here as well.)
So why doesn't my listener get called? And how do I write a listener that will perform some actions whenever my CardDetailsPanel appears on the screen?
Use an AncestorListener as described in dialog focus.
When a JDialog (or JFrame for that matter) is made visible, focus is placed on the first focusable component by default. There may be times when you want to change this behaviour. The obvious solution would be to invoke the requestFocusInWindow() method on the component you wish to receive focus. The problem is that this doesn’t work all the time.
...
The problem is .. a component can’t request focus unless it has been added to a “realized” dialog. A realized dialog basically means that the Swing JDialog has been added to a peer component that represents a dialog on the underlying OS. This occurs when you invoke the pack() or setVisible(true) methods on the JDialog.
And that is where the ancestor listener comes in handy. For a component in a modal dialog, it will be fired once the component becomes visible, and is realized & focusable.
Edit:
The above comment applies to components in any Swing container, including JFrame and JPanel.

Disable JFrame but Want Access to Menu Windows

I dont know how to make this with simple and easy code.
I can just go to each piece of my code and use setEnabled to false on each component, but I want a easy way.
I want to disable the entire frame, but still want to close/maximize/minize it. do you understand?
And if I use setEnabled(false) on my frame, it disables that options too, the options of windows menu bar you know?
Thanks alot in advance..
Simple,Put all your components in a JPanel and disable the JPanel :-)
You can use a code snippet like below. Insert this method/routine in a utility class. Since the method is static you can call it without that class's instance. And make invocations to this method to enable/disable components (menu items, buttons, text fields etc.)
// Let's say you have a JFrame object called myFrame
// and a reference to its content pane.
// Container container = myFrame.getContentPane();
public static void toggleAbilities(Container container, boolean enabled)
{
Component[] components = container.getComponents();
for(Component component: components)
component.setEnabled( enabled );
}
If you get stuck, I can post overall working code as well.
(Toggling the ability of a set of buttons in a JFrame)

Detecting Focus on (frame + components) in swing

I have a small dialog frame that appears, and within this frame are a series of buttons and a textbox.
I need the frame to be able to detect when the user has put focus on something else on the screen (being: anything besides the frame and its components), so I can close down the frame.
Any advice on how to go about this? I've been trying at focus solutions for hours, to no solution!
Try using a WindowStateListener
The WindowEvent parameter it provides can tell you if the window has lost focus through the getNewState() method.
class MyFocusLostListener implements WindowStateListener {
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == WindowEvent.WINDOW_LOST_FOCUS) {
e.getWindow().setVisible(false);
}
}
}
need the frame to be able to detect when the user has put focus on something else on the screen
Use a WindowListener and listen for windowDeactivated.
listen to property changes of the property "permanentFocusOwner" of the KeyboardFocusManager. On being notified, check if the new focusOwner is in the child hierarchy under the frame, if not - close the frame.
Edit: seeing the answers suggesting a Window/StateListener - they are better than mine for a top-level window :-) Listening to the keyboardFocusManager is a good approach for containers deeper down in the hierarchy, implemented f.i. in the CellEditorRemover of a JTable (to decide if a pending edit should be terminated)

Programmatic close of JFrame

What's the programmatic equivalent of clicking the close (x) button in the upper right corner of a JFrame?
There's the dispose() method but that's not the same thing, since a JFrame can be set to do several different things upon closing (not to mention if there's a WindowListener involved)
You tell the component to dispatch an event. In this case, you want it do dispatch a Window Closing event.
private void exit() {
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
When you hit the x on a JFrame, the system can be set to do various things. The default is that the window is simply hidden with setVisible(false) I believe.
You can set a frame to do different things on close--you can have it dispose, hide or call code based on setDefaultCloseOperation. Here are the options:
DO_NOTHING_ON_CLOSE: Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
HIDE_ON_CLOSE: Automatically hide the frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE: Automatically hide and dispose the frame after invoking any registered WindowListener objects.
EXIT_ON_CLOSE: Exit the application using the System exit method. Use this only in applications.
But I think what you are after is setVisible(false).
You have to insert the call into the AWT message queue so all the timing happens correctly, otherwise it will not dispatch the correct event sequence, especially in a multi-threaded program.
public void closeWindow()
{
if(awtWindow_ != null) {
EventQueue.invokeLater(new Runnable() {
public void run() {
awtWindow_.dispatchEvent(new WindowEvent(awtWindow_, WindowEvent.WINDOW_CLOSING));
}
});
}
}

Java Swing: dispose() a JFrame does not clear its controls

I have a closeWindow() method which uses dispose() for the current JFrame to close down. When I show the window again, the controls (textboxes, lists, tables etc.) still have their previous values in place that were there when I dispose():d the frame... Why is that? Is there another way to completley close and clear a frame?
This is the code that another JFrame uses to show the other window, am I doing something wrong here?
#Action
public void showAddProductToOrderView() {
if (addProductToOrderView == null) addProductToOrderView = new AddProductToOrderView(this);
addProductToOrderView.setVisible(true);
}
Disposing a window will not clear its child text components. Dispose will release native resources. The javadoc for java.awt.Window also states:
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
As suggested by others, create a new instance each time instead. If that's to expensive I believe your best option is to clear sub components when the view becomes visible, e.g. by overriding setVisible.
EDIT:
Remove the null check to create a new frame each time.
#Action
public void showAddProductToOrderView() {
addProductToOrderView = new AddProductToOrderView(this);
addProductToOrderView.setVisible(true);
}
I don't know about the rest of your code, if there's something else depending on the frame being reused. For example, if you have attached listeners, ensure they are unregistered to not leak them.
The simplest thing to do would be to re-create the whole frame (using its constructor) before using show() to show it again. That will give you a whole new set of components, assuming that the constructor creates and places them.

Categories

Resources