[英]JDialog not centered over parent JFrame
我試圖讓我的JDialog在單擊按鈕時彈出到JFrame的中心。 我有JOptionPanel可以在父JFrame上正確彈出,但是JDialog是相對於JFrame彈出而不是在中心彈出。
這些按鈕實際上是我的代碼中的JMenuItem,但是我在這里將它們寫為JButton來使事情變得簡單而直接。
這是我的代碼:
從我的父級JFrame調用:
JButton about = new JButton("About");
about.addActionListener(new ActionListener() { //this one IS NOT in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
new AboutDialog(MyJFrame.this);
}
});
JButton exit = new JButton("Exit");
exit.addActionListener(new ActionListener() { //this one IS in the center of MyJFrame
public void actionPerformed(ActionEvent e) {
if(JOptionPane.showConfirmDialog(MyJFrame.this, "Are you sure you want to exit ?","",JOptionPane.YES_NO_OPTION) == 0)
System.exit(0);
}
});
AboutDialog類
public class AboutDialog extends JDialog{
public AboutDialog(JFrame parent) {
setLocationRelativeTo(parent);
setLayout(new BorderLayout());
...
謝謝
setLocationRelativeTo(parent);
在將所有組件添加到對話框並打包對話框之后以及使對話框可見之前,需要執行以上代碼。
在您當前的代碼中,對話框的大小為(0,0),因此無法正確居中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.