问题描述
当我调用 jdialog 类时,我一遍又一遍地遇到这个问题,但没有显示任何内容,这是 jdialog 接口的代码:
public JMovie() {
JFrame f = new JFrame();
jdialog jmovie = new jdialog(f,"JMovie Dialog");
jmovie.setLayout(new BorderLayout());
okbutton = new JButton("Ok");
cancelbutton = new JButton("Cancel");
title = new JLabel("Title",SwingConstants.RIGHT);
date = new JLabel("Date made on ",SwingConstants.RIGHT);
price = new JLabel("Price",SwingConstants.RIGHT);
inputdate = new JLabel("dd/mm/yyyy");
Ttitle = new JTextField(null,15);
TMadeon = new JTextField(null,10);
TPrice = new JTextField(null,6);
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jb = new JPanel();
jl = new JPanel();
okbutton.addActionListener(this);
cancelbutton.addActionListener(this);
Ttitle.setName("Title");
TMadeon.setName("Date Made on");
TPrice.setName("Price");
jb.add(okbutton);
jb.add(cancelbutton);
title.setAlignmentX(Component.RIGHT_ALIGNMENT);
date.setAlignmentX(Component.RIGHT_ALIGNMENT);
price.setAlignmentX(Component.RIGHT_ALIGNMENT);
JPanel south = new JPanel(new FlowLayout());
south.add(jb,BorderLayout.soUTH);
JPanel west = new JPanel(new GridLayout(3,1));
west.add(title,BorderLayout.WEST);
west.add(date,BorderLayout.WEST);
west.add(price,BorderLayout.WEST);
JPanel center = new JPanel(new GridLayout(3,1));
center.add(jp3,FlowLayout.LEFT);
center.add(jp2,FlowLayout.LEFT);
center.add(jp1,FlowLayout.LEFT);
inputdate.setEnabled(false);
jmovie.setSize(350,150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
}
这是接口 JMovie DIAlog 的代码,我在另一个类中调用它。
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(btnMAdd))
{
JMovie ne = new JMovie();
ne.setVisible(true);
}
}
当我运行它时显示:
解决方法
首先,变量名不应以大写字符开头。有些变量是正确的,有些则不是。遵循 Java 约定并保持一致!
jmovie.setSize(350,150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
组件应该在对话框可见之前添加到对话框中。
所以代码应该是:
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
jmovie.setSize(350,300);
jmovie.setVisible(true);
您应该使用 pack()
而不是 setVisible(...)。这将允许所有组件以其首选大小显示。
JFrame f = new JFrame();
此外,您不应该创建 JFrame。要传递给 JDialog 的参数是当前可见的 JFrame。
因此,在您的 ActionListener 中,您可以使用以下逻辑获取当前帧:
Window window = SwingUtilities.windowForComponent( btnMAdd );
现在,当您创建对话框时,您将窗口作为参数传递:
JMovie ne = new JMovie(window);
并且您使用此值来指定对话框的父窗口。