Jav*_*ner 1 java user-interface swing jbutton joptionpane
我希望在应用程序前面显示警告showConfirmDialog窗口,即使GUI移动到不同的位置,如果我不移动应用程序并按"关闭ALT + X"按钮,但是如果我将应用程序移动到第二个屏幕,它可以正常工作警告showConfirmDialog窗口停留在旧位置,如何随GUI一起移动警告窗口,请给我指示,谢谢.
关闭ALT + X按钮
//close window button
JButton btnCloseWindow = new JButton("Close ALT+X");
btnCloseWindow.setMnemonic('x');
btnCloseWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame();
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to close the application?", "Please Confirm",JOptionPane.YES_NO_OPTION);
//find the position of GUI and set the value
//dialog.setLocation(10, 20);
if (result == JOptionPane.YES_OPTION)
System.exit(0);
}
});
Run Code Online (Sandbox Code Playgroud)
到目前为止,我试图将GUI的位置设置为showConfirmDialog,但是没有用.
JOptionPane应该相对于其父窗口定位自己.由于您使用新创建的和未显示的JFrame作为对话框的父窗口,因此对话框只知道在屏幕中居中.
所以这里的关键不是只使用任何旧的JFrame作为父窗口,而是使用当前显示的JFrame或其显示的组件之一作为父组件,即JOptionPane.showConfirmDialog方法调用的第一个参数.
那么如果你让你的JButton最终并将其传递给你的方法调用呢?
// **** make this final
final JButton btnCloseWindow = new JButton("Close ALT+X"); // ***
// ....
btnCloseWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JFrame frame = new JFrame(); // **** get rid of this ****
// ***** note change? We're using btnCloseWindow as first param.
int result = JOptionPane.showConfirmDialog(btnCloseWindow ,
"Are you sure you want to close the application?",
"Please Confirm",JOptionPane.YES_NO_OPTION);
// ......
Run Code Online (Sandbox Code Playgroud)