gpt4 book ai didi

java - 如何将 JFrame 设置为 JDialog 的父级

转载 作者:搜寻专家 更新时间:2023-10-30 21:08:50 25 4
gpt4 key购买 nike

我无法将框架设置为对话框的所有者。通常,当我扩展 JDialog 类来创建对话框时,我会使用 super(frame) 来指定对话框的所有者,这样当您按 alt+tab。但是当我使用像 JDialog dialog = new JDialog() 这样的 new 创建对话框时,我无法将框架指定为对话框的所有者。

以下示例演示了上述两种方法。 Top Click 按钮打开一个未扩展 JDialog 的对话框。 底部单击 按钮打开一个带有扩展 JDialog 的对话框。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class DialogEx {

public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new DialogEx().createUI();
}
};
EventQueue.invokeLater(r);
}

private void createUI() {
final JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());

JButton button1 = new JButton("Top Click");
JButton button2 = new JButton("Bottom Click");

button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new DialogExtend(frame).createUI();
}
});

button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
new DialogWithoutExtend(frame).cretaUI();
}
});

frame.setTitle("Test Dialog Instances.");
frame.add(button1, BorderLayout.NORTH);
frame.add(button2, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 200));
frame.setVisible(true);
}

class DialogExtend extends JDialog {
private JFrame frame;
public DialogExtend(JFrame frame) {
super(frame);
this.frame = frame;
}

public void createUI() {
setLocationRelativeTo(frame);
setTitle("Dialog created by extending JDialog class.");
setSize(new Dimension(400, 100));
setModal(true);
setVisible(true);
}
}

class DialogWithoutExtend {

private JFrame frame;
public DialogWithoutExtend(JFrame frame) {
this.frame = frame;
}

public void cretaUI() {
JDialog dialog = new JDialog();
dialog.setTitle("Dialog created without extending JDialog class.");
dialog.setSize(new Dimension(400, 100));
dialog.setLocationRelativeTo(frame);
dialog.setModal(true);
dialog.setVisible(true);
}
}
}

最佳答案

对话框(或窗口)的所有者只能在构造函数中设置,因此设置它的唯一方法是使用将所有者作为参数的构造函数,例如:

class DialogWithoutExtend {

private JFrame frame;
public DialogWithoutExtend(JFrame frame) {
this.frame = frame;
}

public void cretaUI() {
JDialog dialog = new JDialog(frame);
dialog.setTitle("Dialog created without extending JDialog class.");
dialog.setSize(new Dimension(400, 100));
dialog.setLocationRelativeTo(frame);
dialog.setModal(true);
dialog.setVisible(true);
}
}

关于java - 如何将 JFrame 设置为 JDialog 的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com