如何设置JOptionPane的位置?

我有一个启动窗口,在程序加载时弹出。 这个启动窗口使用方法setAlwaysOnTop(true) ,这是我希望保留的。

当程序的一个单独部分弹出JOptionPane以通知用户需要更新软件时,会出现问题。 在Linux上,它出现在Splash窗口的前面,但在Windows上它出现在后面,用户几乎看不到,然后可能会坐30分钟 – 小时才能找到它尚未加载的原因。

我想要实现的解决方案是

  • 强制JOptionPane在屏幕上的其他位置弹出
    要么
  • 更改JOptionPane出现的位置,使其位于初始屏幕的顶部或底部。

我能看到的唯一一个可以做到这一点的函数是setLocationRelativeTo(Component myComponent)方法。 但这并不好,因为没有什么比这更好了(并没有任何礼物!)。

这种事情有可能吗? 如果是这样我该如何去做呢?

这是我的SSCCE(根据他们的答案中的SeniorJD代码):

 public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final Splash splash =new Splash(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } final Frame frame = new Frame("Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); splash.dispose(); } }); } } @SuppressWarnings("serial") public class Frame extends JFrame implements ActionListener{ Frame(String title){ super(title); JButton button = new JButton("Button"); add(button); setAlwaysOnTop(true); setSize(500, 500); setLocationRelativeTo(getParent()); setAlwaysOnTop(true); button.addActionListener(this); actionPerformed(null); } @Override public void actionPerformed(ActionEvent e) { JOptionPane optionPane = new JOptionPane("Option Pane"); optionPane.showMessageDialog(this, "Message: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tristique gravida congue."); } } @SuppressWarnings("serial") public class Splash extends JFrame { public Splash() throws HeadlessException { setAlwaysOnTop(true); setUndecorated(true); setVisible(true); setSize(600, 450); setLocationRelativeTo(getParent()); } } 

这更能模仿我的用户所看到的行为。 如何将JOptionPane移动到闪屏之外?

您应该将frame设置为JOptionPane的父级:

 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final JFrame frame = new JFrame("Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Button"); frame.add(button); frame.setAlwaysOnTop(true); frame.setSize(500, 500); frame.setLocation(500, 500); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane optionPane = new JOptionPane("Option Pane"); optionPane.showMessageDialog(frame, "Message!"); // if you put null instead of frame, the option pane will be behind the frame } }); frame.setVisible(true); } }); } } 

如果

 setLocationRelativeTo(null); 

在Windows上我没有很好地展示它我会将它的大小设置为比启动画面稍微大一点,所以它会更加引人注目或者像SeniorJD建议的那样。