我无法将框架设置为对话框的所有者.通常当我扩展jdialog类来创建对话框时,我使用超级(框架)来指定对话框的所有者,以便当您按Alt选项卡时,它们都不会脱节.但是当我使用新的jdialog对话框= new jdialog()创建一个对话框时,我无法将框架指定为对话框的所有者.
以上示例以上两种方法.顶部点击按钮打开一个没有扩展jdialog的对话框. Bottom Click按钮打开一个扩展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); } }
原文地址:https://www.jb51.cc/java/124979.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。