我有两个类 - 一个代表JFrame
,另一个代表JPanel
。在JPanel
我有JComponents
我想要用来捕获用户输入。在JFrame
我有一个JButton
,当用户点击JPanel
时会显示JDialog
。以下是实现此目的的代码:
扩展JFrame
。
public class ControlPanel extends JFrame {
public JButton display;
ControlPanel() {
this.createUI();
// button action
this.display.addActionListener((ActionEvent) -> {
AddUser ad = new AddUser();
JDialog dialog = new JDialog(this,
Dialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible(true);
dialog.setSize(300, 300);
dialog.add(ad);
});
}
public void createUI() {
this.setTitle("Dispalying a JPanel on JDialog");
this.setSize(new Dimension(300, 300));
this.setVisible(true);
this.setLayout(new BorderLayout(5, 5));
this.display = new JButton("Display");
this.add(new JLabel("North", JLabel.CENTER), BorderLayout.NORTH);
this.add(this.display, BorderLayout.CENTER);
this.add(new JLabel("South", JLabel.CENTER), BorderLayout.SOUTH);
this.add(new JLabel("East"), BorderLayout.EAST);
this.add(new JLabel("West"), BorderLayout.WEST);
}
public static void main(String[] args) {
ControlPanel cp = new ControlPanel();
}
}
扩展JPanel
。
此面板是我希望添加到 JDialog
的面板。
public class AddUser extends JPanel {
public AddUser() {
this.prepareUI();
}
public void prepareUI() {
this.setPreferredSize(new Dimension(200, 200));
this.setLayout(new GridLayout(1, 4, 5, 5));
this.add(new JLabel("Label1"));
this.add(new JLabel("Label2"));
this.add(new JLabel("Label2"));
this.add(new JLabel("Label2"));
/* Code to test if the panel is displaying fine.
* The panel is displaying fine.
* JFrame fr = new JFrame();
fr.setVisible(true);
fr.setSize(300, 300);
fr.setLayout(new BorderLayout(5, 5));
fr.add(this, BorderLayout.CENTER);
fr.pack();*/
}
public static void main(String[] args) {
AddUser ad = new AddUser();
}
}
注意:我这样做是因为我希望面板为模态 - 用户在完成之前不得与JFrame
上的组件进行交互使用JPanel
。
问题:显示Jpanel
时,AddUser ad = new AddUser();
[此一个:JDialog
]未显示。
问题:我的代码出了什么问题,如何解决?
单击display
按钮时输出如下。