quarta-feira, 9 de julho de 2014

Focus no JInternalFrame

E quando eu penso que, não terei de mexer mais com algum projeto em Swing, me engano e lá vamos nós...

Nesse projeto que estava desenvolvendo, estava usando JInternalFrame para confecção de telas. Quando uma tela era aberta, eu queria que ela fosse aberta com o focus. Depois de muito pesquisar, achei a solução na própria documentação.

Segue solução para o problema:

protected void createFrame() {
    MyInternalFrame frame = new MyInternalFrame();
    frame.setVisible(true);
    desktop.add(frame);
    try {
        frame.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
}

Também descrevo abaixo algumas boas práticas no uso de JInternalFrame, retiradas da documentação da API.

Rules of Using Internal Frames

If you have built any programs using JFrame and the other Swing components, then you already know a lot about how to use internal frames. The following list summarizes the rules for using internal frames. For additional information, see How to Make Frames and The JComponent Class.
You must set the size of the internal frame.
If you do not set the size of the internal frame, it will have zero size and thus never be visible. You can set the size using one of the following methods: setSizepack, orsetBounds.
As a rule, you should set the location of the internal frame.
If you do not set the location of the internal frame, it will come up at 0,0 (the upper left of its container). You can use the setLocation or setBounds method to specify the upper left point of the internal frame, relative to its container.
To add components to an internal frame, you add them to the internal frame's content pane.
This is exactly like the JFrame situation. See Adding Components to the Content Pane for details.
Dialogs that are internal frames should be implemented using JOptionPane or JInternalFrame, not JDialog.
To create a simple dialog, you can use the JOptionPane showInternalXxxDialog methods, as described in How to Make Dialogs.
You must add an internal frame to a container.
If you do not add the internal frame to a container (usually a JDesktopPane), the internal frame will not appear.
You need to call show or setVisible on internal frames.
Internal frames are invisible by default. You must invoke setVisible(true) or show() to make them visible.
Internal frames fire internal frame events, not window events.
Handling internal frame events is almost identical to handling window events. See How to Write an Internal Frame Listener for more information.
Se alguém precisar de alguma ajuda no inglês, deixe um comentário, que eu dou uma forçinha.

Referência:
http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html

Nenhum comentário: