是否有办法将java帧发送到每个其他打开的程序的前面?我知道你可以用
JFrame.setAlwaysOnTop(true);
但是它总是在前面。我希望它只在某个函数被调用时发生。例如,当我按下一个帧上的按钮时,它将使用Thread.sleep(10000)等待10秒,但我希望它只是将帧移到前面,以防你在窗口外点击一秒钟。有什么建议吗?
看看Window#toFront
你可能还想看一下
-
WindowListener
- Swing
Timer
注意在GUI环境中使用Thread.sleep
,如果使用不当,这将导致窗口停止更新(绘制)
这是令人惊讶的繁琐。
确切的行为也可能取决于操作系统。但至少在Windows上,对frame.toFront()
的调用将而不是必然将窗口带到前面。相反,它会导致任务栏中相应的条目闪烁几秒钟。我尝试了
f.setAlwaysOnTop(true);
f.setAlwaysOnTop(false);
基本上是工作的,但是在窗口被带到前面之后,它是不是"活动的",并且我没有尝试使它活跃工作(例如请求焦点等)。
我现在找到的(可靠的)工作(至少在Windows上)的唯一解决方案是
if (!f.isActive())
{
f.setState(JFrame.ICONIFIED);
f.setState(JFrame.NORMAL);
}
但不知道是否有更优雅的解决方案。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class FrameToTopTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Bring me to top after 3 seconds");
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
triggerBringToFront(f, 3000);
}
});
f.getContentPane().add(button);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static void triggerBringToFront(final JFrame f, final int delayMS)
{
Timer timer = new Timer(delayMS, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// This will only cause the task bar entry
// for this frame to blink
//f.toFront();
// This will bring the window to the front,
// but not make it the "active" one
//f.setAlwaysOnTop(true);
//f.setAlwaysOnTop(false);
if (!f.isActive())
{
f.setState(JFrame.ICONIFIED);
f.setState(JFrame.NORMAL);
}
}
});
timer.setRepeats(false);
timer.start();
}
}