如何设置"JOptionPane.showMessageDialog"的位置

Sal*_*eek 7 java layout swing position

我想让JOptionPane.showMessageDialog消息显示出来

  • 屏幕上的任何位置.
  • 相对于JFrame.(不在JFrame的中心)

例如,这将在作为参数提供的JFrame的中心显示消息 thisFrame

 JOptionPane.showMessageDialog(thisFrame, "Your message.");
Run Code Online (Sandbox Code Playgroud)

这将在屏幕中心显示与任何JFrame无关的消息.

JOptionPane.showMessageDialog(null, "Your message.");
Run Code Online (Sandbox Code Playgroud)
  • 我想要的是在任何我想要的地方设置消息的位置

  • 我想要的是设置消息相对于JFrame的位置(不在JFrame的中心)

怎么样?

Nei*_*man 8

你需要的是什么

    final JOptionPane pane = new JOptionPane("Hello");
    final JDialog d = pane.createDialog((JFrame)null, "Title");
    d.setLocation(10,10);
    d.setVisible(true);
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用d.setLocationRelativeTo(someparent); 相对于任何UI组件定位它. (5认同)

gia*_*kis 5

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;

public class CustomDialog extends JDialog {
    private JPanel myPanel = null;
    private JButton yesButton = null;
    private JButton noButton = null;

    public CustomDialog(JFrame frame, boolean modal, String myMessage) {
    super(frame, modal);
    myPanel = new JPanel();
    getContentPane().add(myPanel);
    myPanel.add(new JLabel(myMessage));
    yesButton = new JButton("Yes");
    myPanel.add(yesButton);
    noButton = new JButton("No");
    myPanel.add(noButton);
    pack();
    //setLocationRelativeTo(frame);
    setLocation(200, 200); // <--
    setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)