我有一个JDialog,它是在JFrame中单击按钮打开的。每次我关闭JDialog并再次单击并打开JDialog时,它会在屏幕上向上移动(大约30个像素)。我尝试修复帧位置,使用setLocationRelativeTo(null)并尝试使用Toolkit.getDefaultToolkit()修复它.getScreenSize();但它不起作用。它只是向上,直到它在屏幕上方。为什么会这样?
// Play Hook Frame
hookDialog = new JDialog(frame, "Play Hook", true);
hookDialog.setSize(450, 250);
hookDialog.setLocation(dim.width / 2 - hookDialog.getSize().width / 2,
dim.height / 2 - hookDialog.getSize().height / 2);
hookDialog.getContentPane().setBackground(bgColor);
hookDialog.setResizable(false);
hookDialog.getContentPane().setLayout(null);
...
JButton btnPlayHook = new JButton("Play Hook");
customizeButton(btnPlayHook);
btnPlayHook.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isHookPressed) {
JOptionPane.showMessageDialog(frame,
"Please press Find Hook button first", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
for (int i = 0; i < hooks.size(); i++) {
int intMin1 = (int) (hooks.get(i).getStartTime() / 60);
int intMin2 = (int) (hooks.get(i).getEndTime() / 60);
int intSec1 = (int) (hooks.get(i).getStartTime() % 60);
int intSec2 = (int) (hooks.get(i).getEndTime() % 60);
String min1 = intMin1 + " min";
String min2 = intMin2 + " min";
String sec1 = intSec1 + " sec";
String sec2 = intSec2 + " sec";
String elem = "Hook" + (i + 1) + ": " + min1 + " "
+ sec1 + " - " + min2 + " " + sec2;
if (!listElements.contains(elem))
listElements.addElement(elem);
}
hookDialog.setVisible(true);
}
}
});
答案 0 :(得分:0)
这会将对话框置于屏幕中心。
这样做:
hookDialog.setLocationRelativeTo(null);
如果不起作用:
hookDialog.getContentPane().setLocationRelativeTo(null);
答案 1 :(得分:-1)
在您的系统上试用此代码。将您的逻辑添加到此基础,并查看它何时开始表现不佳。
public static void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
final JDialog hookDialog = new JDialog(frame, "Play Hook", true);
hookDialog.setSize(100, 100);
hookDialog.setLocationRelativeTo(null);
hookDialog.setResizable(false);
hookDialog.getContentPane().setLayout(null);
final JButton btnPlayHook = new JButton("Play Hook");
frame.getContentPane().add(btnPlayHook);
btnPlayHook.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
hookDialog.setVisible(true);
}
});
frame.setVisible(true);
}
});
}