JDialog vs JOptionPane vs JPanel For Show Message

时间:2017-03-01 17:45:39

标签: java swing jpanel joptionpane jdialog

我正在使用Java Swing开发一个应用程序,有时我需要在出现以下情况时显示消息:

  1. 当用户点击“添加”按钮时,由于TCP连接,需要相对较长的时间。我正在使用JPanel向用户显示“处理...”。当用户点击“添加”按钮时,我会更改包含setVisible(true)消息的面板的"processing..."

  2. 如果添加正确,我会以相同的方式向用户显示消息"added"setVisible

  3. 当用户输入错误的输入时,我会以同样的方式显示消息。

  4. 为此,我创建了不同的面板,并根据我的设计进行了定制。但是,当我使用JDialogJOptionPane时,我无法完全自定义。

    我想问一下,这是一种错误的做法吗?它是否会导致性能和可视化问题?我应该使用JOptionPane还是JDialog来实现这些流程?

1 个答案:

答案 0 :(得分:2)

JPanel只是用来容纳其他组件的容器。

JDialog是一个通用对话框,可以通过添加其他组件进行自定义。 (有关详细信息,请参阅How to add components to JDialog

JOptionPane可以被视为一个特殊目的对话框。从javadoc(强调添加):

  

JOptionPane可以轻松弹出 标准对话框 ,提示用户输入值或通知他们。

如果您深入了解JOptionPane的来源,您会发现像showInputDialog()这样的方法实际上会创建JDialog,然后使用JOptionPane <填充它/ p>

public static Object showInputDialog(Component parentComponent,
    Object message, String title, int messageType, Icon icon,
    Object[] selectionValues, Object initialSelectionValue)
    throws HeadlessException {
    JOptionPane    pane = new JOptionPane(message, messageType,
                                          OK_CANCEL_OPTION, icon,
                                          null, null);

    pane.setWantsInput(true);
    pane.setSelectionValues(selectionValues);
    pane.setInitialSelectionValue(initialSelectionValue);
    pane.setComponentOrientation(((parentComponent == null) ?
        getRootFrame() : parentComponent).getComponentOrientation());

    int style = styleFromMessageType(messageType);
    JDialog dialog = pane.createDialog(parentComponent, title, style);

    pane.selectInitialValue();
    dialog.show();
    dialog.dispose();

    Object value = pane.getInputValue();

    if (value == UNINITIALIZED_VALUE) {
        return null;
    }
    return value;
}

根据您的说明,听起来您可以使用JOptionPane.showConfirmDialog()来确认已添加用户。

在您的申请时间内,您可能需要将progress barJDialog配对,以便让用户知道系统正在运行。

如果您发布示例代码,此处的社区成员可能会为您提供有关如何在应用程序中最好地使用这些组件的更具体指导。