Java向JOptionPane添加组件

标签 java swing joptionpane

我正在尝试为简单的数据输入对话框创建自定义面板。我创建了一个自定义面板,在其中添加标签和文本字段。我正在尝试将其添加到 JOptionPane 中进行显示。

当我调用它时,我的组件不会显示,但 JOptionPane 按钮会显示。这样做的正确方法是什么?

这是我创建自定义面板并调用 JOptionPane 的位置:

    public class ListenCustEdit implements ActionListener {
    @Override
    @SuppressWarnings("empty-statement")
    public void actionPerformed(ActionEvent e) {
        TestPanel panel = new TestPanel();
        int input = JOptionPane.showConfirmDialog(frame, panel, "Edit Customer:"
                        ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        if (input == 0) {
            // OK
            JOptionPane.showMessageDialog(frame,"Changes savewd");
        } else {
            // Cancel
            JOptionPane.showMessageDialog(frame, "No changes were saved");
        }
    }
}

这是我的自定义面板类:

public class TestPanel extends JPanel {

JTextField custIdTextField;
JTextField companyTextField;
JTextField firstNameTextField;
JTextField lastNameTextField;

public TestPanel() {
    initUI();
}

public final void initUI() {
    
    // create the panel and set the layout
    JPanel main = new JPanel();
    main.setLayout(new GridLayout(4,4));
    
    // create the labels
    JLabel custIdLabel = new JLabel("Cust Id: ");
    JLabel companyLabel = new JLabel("Company: ");
    JLabel firstNameLabel = new JLabel("First Name: ");
    JLabel lastNameLabel = new JLabel("Last Name: ");
    
    // create the text fields
    custIdTextField = new JTextField();
    companyTextField = new JTextField();
    firstNameTextField = new JTextField();
    lastNameTextField = new JTextField();
    
    // add componets to panel
    main.add(custIdLabel);
    main.add(custIdTextField);
    main.add(companyLabel);
    main.add(companyTextField);
    main.add(firstNameLabel);
    main.add(firstNameTextField);
    main.add(lastNameLabel);
    main.add(lastNameTextField);
}

最佳答案

您需要将主面板添加到 TestPanel 中。

public final void initUI() {
    // ...
    add(main);
}

关于Java向JOptionPane添加组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15346377/

相关文章:

java - 从不同的 jar 构建可执行文件

java - CouchDB Java 库由 Maven 下载,但不被 IntelliJ 识别

java - JOptionPane中的猜数字游戏,JPanel不显示(Java)

Java - JTabbedPane - 添加新面板时出现 ArrayIndexOutOfBoundsException

java - 用 Java 创建简单的条形图 - 读取数据并输出条形图

java - 删除确定按钮

JavaFX 按钮在第一次单击时没有响应

java - 从java代码运行bat文件并等待它执行TestComplete脚本 - 无法执行:(

java - 使用文档监听器限制文本字段中的字符

Java 与 JOptionpane GUI 和 elseif 值