我正在使用Java Swing开发一个应用程序,有时我需要在出现以下情况时显示消息:
当用户点击“添加”按钮时,由于TCP连接,需要相对较长的时间。我正在使用JPanel
向用户显示“处理...”。当用户点击“添加”按钮时,我会更改包含setVisible(true)
消息的面板的"processing..."
。
如果添加正确,我会以相同的方式向用户显示消息"added"
(setVisible
)
当用户输入错误的输入时,我会以同样的方式显示消息。
为此,我创建了不同的面板,并根据我的设计进行了定制。但是,当我使用JDialog
或JOptionPane
时,我无法完全自定义。
我想问一下,这是一种错误的做法吗?它是否会导致性能和可视化问题?我应该使用JOptionPane
还是JDialog
来实现这些流程?
答案 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 bar与JDialog
配对,以便让用户知道系统正在运行。
如果您发布示例代码,此处的社区成员可能会为您提供有关如何在应用程序中最好地使用这些组件的更具体指导。