我使用Jetbrains Intellij的GUI设计器生成了JDialog(因为这是一个快速的一次性GUI项目)。在对话框中我有一个JScrollPane,我想在运行时插入组件
所以,在滚动窗格中,我勾选了#34; Custom Creation"将项添加到我的java类,我的代码现在大致如下:
公共类MyDialog扩展了JDialog { //其他领域 私有JButton addButton; private JScrollPane scrollPane;
public BuilderCreationDialog() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
// other action listeners
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
onAdd();
}
});
}
private void onAdd() {
addFieldJPanel("valueA", "valueB");
}
private void addFieldJPanel(final String name, final String type) {
final JPanel fieldPanel = new JPanel();
fieldPanel.add(new JLabel(name));
fieldPanel.add(new JLabel(type));
final JButton removalButton = new JButton();
removalButton.addActionListener((e) -> {
// do something
});
fieldPanel.add(removalButton);
fieldPanel.revalidate();
fieldPanel.repaint();
fieldPanel.setVisible(true);
scrollPane.add(fieldPanel);
pack();
scrollPane.revalidate();
scrollPane.repaint();
}
public static void main(String[] args) {
MyDialog dialog = new MyDialog();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
private void createUIComponents() {
scrollPane = new JBScrollPane();
}
}
然而,当我点击按钮时,scollPane仍为空。我错过了什么?