How can I set the location of a JOptionPane?

前端 未结 2 1290
生来不讨喜
生来不讨喜 2020-12-20 08:37

I have a splash window that pops up while the program loads. This splash window uses the method setAlwaysOnTop(true), which is something I would prefer to keep.

相关标签:
2条回答
  • 2020-12-20 08:54

    You should set the frame as a parent of 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);
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-20 09:04

    if

    setLocationRelativeTo(null);
    

    does not show it for some reason nicely on Windows I would either set the size of it to be slighty bigger than the splash screen so it would be more noticeable or do as SeniorJD suggested.

    0 讨论(0)
提交回复
热议问题