问下各位大神,在java编写的程序中点击菜单栏的一个菜单项,比如在格式菜单下的字体和颜色,弹出一个窗口

在java编写的程序中,点击菜单栏里的一个菜单项,比如说在格式菜单下的字体和颜色,弹出一个窗口,怎么使这个窗口在原窗口的中央。并且在这个窗口上执行功能不受影响

你说的是打开非模态对话框。

如果模态对话框不关闭,无法操作主窗体。如果非模态对话框不关闭,仍然可以操作主窗体。

//构造模态对话框

final Dialog d = new Dialog(this, "模态对话框", true);

//构造非模态对话框

final Dialog d = new Dialog(this, "模态对话框", false);


样例程序如下:

import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame implements ActionListener {
JButton btnModel, btnNonModel;

public Main() {
super("对话框");
this.setLayout(new FlowLayout());

btnModel = new JButton("打开模态对话框");
btnNonModel = new JButton("打开非模态对话框");

this.add(btnModel);
this.add(btnNonModel);

btnModel.addActionListener(this);
btnNonModel.addActionListener(this);

this.setSize(200, 200);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    new Main();
}

@Override
public void actionPerformed(ActionEvent arg0) {
JButton btn = (JButton) arg0.getSource();
if(btn == btnModel) { //打开模态对话框
final Dialog d = new Dialog(this, "模态对话框", true);
            d.setSize(800, 600);
            d.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    d.setVisible(false);
                }
            });
            d.setVisible(true);
}
else if(btn == btnNonModel) { //打开非模态对话框
final Dialog d = new Dialog(this, "非模态对话框", false);
            d.setSize(800, 600);
            d.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    d.setVisible(false);
                }
            });
            d.setVisible(true);
}
}
}追问

首先,非常感谢你的回答!你回答的是创建一个子窗口嘛,我运行了下,没问题。不过,我问题的重点是:要怎么设置才能让打开的子窗口始终居于父窗口的中部,也就是说不管父窗口在什么位置打开,然后打开的子窗口都要在父窗口的中部(不是嵌在父窗口里,哈哈)。

追答

在

d.setSize(200, 200);

后添加代码:

d.setLocationRelativeTo(this);

使子窗体出现在父窗体中央。

温馨提示:内容为网友见解,仅供参考
第1个回答  2017-06-17
new XX().setLocationRelativeTo(this)
相似回答