JOptionPane with multiple inputs on different lines

痞子三分冷 提交于 2019-12-01 19:22:40

问题


I'd like to create a JOptionPane that allows a user to select an IP address and port to connect to. It should be structured as such,

IP Address: [textfield here]

Port: [textfield here]

Cancel OK

The labels should be aligned to the left, and the textfields should be left aligned too. I can't really model the storyboard here, but basically the textfields shouldn't be misaligned, even if there is a space between the labels and the textfields.

Each label and textfield pair should be on seperate lines, and the Cancel OK buttons should be aligned to the right, below the textboxes.

Is there any way to do this in code?


回答1:


See this example that seems similar in layout.

The example

Right align

Right aligns the text in the labels, which I think looks better, using this:

labels.add(new JLabel("User Name", SwingConstants.RIGHT));

For left aligned text, change it to:

labels.add(new JLabel("User Name"));

Improvement

It is done using a nested layout, GridLayout instances in the WEST and CENTER of a BorderLayout.

It might be better done using a more powerful layout such as MigLayout or more modern J2SE layout such as BoxLayout or GroupLayout.

GroupLayout can provide the type of alignment this UI needs, while not stretching the CENTER fields to the same width (which is also fixable in a nested layout as above, but requires 2 more constraining panels). I believe the other two could do the job as well, but don't have as much experience with them.




回答2:


Create a custom dialog (jdialog) or use JOptionPane.showInputDialog, see this tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html



来源:https://stackoverflow.com/questions/10834040/joptionpane-with-multiple-inputs-on-different-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!