使Java Swing模态对话框的行为类似于Mac OSX对话框
作者:互联网
我正在编写一个小型应用程序,它要求ProgressBar出现在框架的TitleBar的中央,这在Mac OSX应用程序中很常见.我有两个问题:
1.我已经完成了定位,但是必须对父框架的TitleBar高度进行硬编码.有没有一种“软”的方法来获取TitleBar的高度?
在对话框的构造函数中:
Dimension dimensionParentFrame = parent.getSize();
Dimension dimensionDialog = getSize();
int x = parent.getX() + ((dimensionParentFrame.width - dimensionDialog.width)/2);
setLocation(x, parent.getY() + 22); // TODO HARD CODE WARNING TITLE HEIGHT
2.即使对话框是模式对话框,我仍然可以单击父框架并将其移动.如何使对话框“贴”到父框架?也就是说,当父框架移动时,对话框也随之移动,就好像附加了该对话框一样.
任何帮助/指针将不胜感激.
这是代码:
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ModalDialogDemoFrame extends JFrame
{
ModalDialogDemoFrame modalDialogDemo;
public ModalDialogDemoFrame()
{
modalDialogDemo = this;
setBounds(100, 100, 400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton buttonDialog = new JButton("Open Dialog");
buttonDialog.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
// Create a Modal Dialog with this Frame as Parent.
ModalDialog modalDialog = new ModalDialog(modalDialogDemo, true);
modalDialog.setVisible(true);
}
});
getContentPane().add(buttonDialog, BorderLayout.CENTER);
}
/**
* @param args
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
ModalDialogDemoFrame window = new ModalDialogDemoFrame();
window.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}
import java.awt.Dimension;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ModalDialog extends JDialog
{
public ModalDialog(JFrame parent, boolean modal)
{
super(parent, modal);
Dimension dimensionParentFrame = parent.getSize();
setSize(new Dimension((parent == null) ? 300 : dimensionParentFrame.width / 2, 75));
Dimension dimensionDialog = getSize();
int x = parent.getX() + ((dimensionParentFrame.width - dimensionDialog.width)/2);
setLocation(x, parent.getY() + parent.getInsets().top);
setUndecorated(true);
setModal(modal);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JButton buttonClose = new JButton("Close");
buttonClose.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
getContentPane().add(buttonClose, BorderLayout.CENTER);
}
}
解决方法:
int titleBarHeight = frame.getInsets().top;
Even though the Dialog is modal, I can still click on the parent Frame and move it.
然后您在做错事,因为这不应该发生.
发布您的SSCCE来演示此问题.
标签:jdialog,java,macos,swing,modal-dialog 来源: https://codeday.me/bug/20191013/1910164.html