Reputation: 577
I used Java and Swing.
I have two windows MainWindow
and PointWindow
.
MainWindow
is a JFrame window.
PointWindow
extends JWindow
.
I want to keep PointWindow
always on top (never under other windows or components). I set in constructor of PointWindow
a setAlwaysOnTop(true)
but problem is when I click to to MainWindow
(focus), next on different way for example click on my desktop (empty space) and try to drag PointWindow
then it is under my MainWindow
.
There is any way to keep the PointWindow
always on top of all components ?
EDIT
In constructor I tried using a WindowListener
as below
this.addWindowListener(new WindowAdapter() {
@Override
public void windowDeactivated(WindowEvent e) {
toFront();
}
@Override
public void windowLostFocus(WindowEvent e) {
toFront();
}
});
... but it do not work, the events are not catched
Upvotes: 0
Views: 1364
Reputation: 577
SOLUTION
I add a MouseAdapter
as a MouseListener
to PointWindow
and when mousePressed
event is detected then do toFront()
and work fine but there is one side effect, it means that there is a moment when window is hide and show (very fast).
Upvotes: 0
Reputation: 1745
If both windows belongs to the same application, the
setAlwaysOnTop(true);
method should do, what you want.
If your window have to stay on top, even if your application lost focus, you have to push it periodically back on top. If another window got the focus, you can not controll that, but you can use a thread to push your window back to top.
In the following example, fr is your window
Thread th = new Thread(){
public void run(){
boolean live = true;
while(live){
try{
fr.toFront();
fr.setAlwaysOnTop(true);
}catch(Exception e1){
e1.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
This code will push your window back to front every 100ms, it should be anough for most applications. This is not the best solution, but it should work
EDIT:
if you just want to the window to be on front of your other window (event after focus regain), you can add and
a FocusListener to your JFrame and call toFront on your window, when focusGained(FocusEvent e) event fires.
Or you could create the JWindow with the frame as parent: new JWindow(jframeParent); this way, your JWindow will recieve all events.
Or just using an undecorated JFrame instead of the JWindow
EDIT2:
If you just want the window to be on top, when you click it, a MouseListener is the right way to do it.
Upvotes: 0