有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于显示消息的java JDialog vs JOptionPane vs JPanel

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

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

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

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

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

我想问,这是一种错误的方法吗?它会导致性能和可视化问题吗?我应该使用JOptionPaneJDialog来实现这些过程吗


共 (1) 个答案

  1. # 1 楼答案

    JPanel只是一个用来存放其他组件的容器

    JDialog是一个通用对话框,可以通过添加其他组件进行自定义。(详见How to add components to JDialog

    JOptionPane可以被认为是一个特殊用途的对话框。从javadoc开始(添加强调):

    JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.

    如果你深入研究JOptionPane的源代码,你会发现像showInputDialog()这样的方法实际上创建了一个JDialog,然后用JOptionPane填充它

    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配对,让用户知道系统正在工作

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