有没有办法在每个其他打开的程序前发送java框架。我知道你可以使用
JFrame.setAlwaysOnTop(true);
但这只是保持在前面。我希望它只发生在调用某个函数时。例如,当我按下一个框架上的一个按钮时,它将使用Thread.sleep(10000)等待十秒钟,但是如果您单击窗口一秒钟,我希望它只是前面的框架。有什么建议吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
令人惊讶的是,这非常繁琐。
确切的行为可能还取决于操作系统。但至少在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();
}
}