1

我想知道如何将组件动态添加到 JDialog。我知道这里有一个关于 SO 的类似问题,但正如你所见,我将他的解决方案作为我的代码的一部分。

所以想法是,在单击按钮时,我需要在对话框中添加一个组件。示例代码如下:

import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test extends JFrame {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public static void main(String args[]) {
    Test test = new Test();
    test.createDialog();
}

public void createDialog() {
    DynamicDialog dialog = new DynamicDialog(this);
    dialog.setSize(300, 300);
    dialog.setVisible(true);
}
}

class DynamicDialog extends JDialog {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public DynamicDialog(final JFrame owner) {
    super(owner, "Dialog Title", Dialog.DEFAULT_MODALITY_TYPE);
    final JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    final JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(Box.createRigidArea(new Dimension(3, 10)));
    panel.add(createLabel("Click on add"));
    panel.add(Box.createRigidArea(new Dimension(23, 10)));
    panel.add(createLabel("To add another line of text"));
    panel.add(Box.createHorizontalGlue());
    mainPanel.add(panel);
    mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
    buttonPanel.add(Box.createHorizontalGlue());

    JButton button = new JButton();
    button.setText("Add another line");
    buttonPanel.add(button);
    mainPanel.add(buttonPanel);
    mainPanel.add(Box.createRigidArea(new Dimension(3, 10)));

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            Container contentPane = owner.getContentPane();
            JPanel _panel = new JPanel();
            _panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
            _panel.add(Box.createHorizontalGlue());
            _panel.add(createLabel("Added!"));
            contentPane.add(_panel);

            contentPane.validate();
            contentPane.repaint();
            owner.pack();
        }
    });

    pack();
    setLocationRelativeTo(owner);
    this.add(mainPanel);
}

JLabel createLabel(String name) {
    JLabel label = new JLabel(name);
    return label;
}
}
4

1 回答 1

3

如果您将它添加到主面板,它将起作用,您将它添加到框架的内容窗格中,它似乎没有出现在任何地方。

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {

        JPanel _panel = new JPanel();
        _panel.setLayout(new BoxLayout(_panel, BoxLayout.X_AXIS));
        _panel.add(Box.createHorizontalGlue());
        _panel.add(createLabel("Added!"));
        mainPanel.add(_panel);

        mainPanel.validate();
        mainPanel.repaint();
        owner.pack();
    }
})
于 2013-10-11T16:35:28.373 回答