下面的代码打开一个具有四个字段的UI,用户可以在其中写入一些信息。某些值可能已经出现在以前使用的字段中。
当用户单击“确定”时,我如何获取/保存这些值?
获取的值
我以为这些值会保存在JPanel object panelForm中,但事实并非如此。
我需要ActionListener吗?如果需要,为什么?
JPanel panelForm = new JPanel(new GridBagLayout());
JTextField url1 = new JTextField("https:testing.com");
JTextField username1 = new JTextField("theDude");
JTextArea statement = new JTextArea("This statement can becomme very very very long :)");
statement.setLineWrap(true);
statement.setWrapStyleWord(true);
// statement will be written in at least 3 rows
// before a scroll bar will be integrated
statement.setRows(3);
JScrollPane scrollPane = new JScrollPane(statement);
Insets insets = new Insets(2,2,2,2);
GridBagConstraints constraints = new GridBagConstraints(0,0,1,1,1,1,GridBagConstraints.WEST,GridBagConstraints.NONE,
insets,0,0);
panelForm.add(new JLabel("Enter url: "),constraints);
// move to the next cell of the column (or to the next "row")
constraints.gridy++;
panelForm.add(new JLabel("Enter username: "),constraints);
constraints.gridy++;
panelForm.add(new JLabel("Enter password: "),constraints);
constraints.gridy++;
panelForm.add(new JLabel("Enter statement: "), constraints);
// move to the next cell of the row (or to the next "column")
constraints.gridx = 1;
//go again to the first row
constraints.gridy = 0;
// Make the component wide enough to fill its display area horizontally, but do not change its height.
constraints.fill = GridBagConstraints.HORIZONTAL;
panelForm.add(url1,constraints);
constraints.gridy++;
panelForm.add(username1,constraints);
constraints.gridy++;
// with the columns number you adjust the size
// of all fields since I use "ridBagConstraints.HORIZONTAL" everywhere
panelForm.add(new JPasswordField(25),constraints);
constraints.gridy++;
panelForm.add(scrollPane,constraints);
int option = JOptionPane.showConfirmDialog(null,panelForm, "Fill all the fields",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
if (option == JOptionPane.OK_OPTION) {
} else {
// if the user clicks on "Cancel" or "x" the code terminates
System.exit(0);
}
输出:
发布于 2019-03-12 08:02:18
您可以将所有JTextFields放在列表集合中,如下所示
List<JTextField> list = new ArrayLists<JTextField>();
for (int i=0; i < maxFields; i++) {
JTextField textField = new JTextField();
list.add( textField );
}
在这之后,当点击确定按钮时,你就会得到它们
for( JTextField f : list ) {
System.out.println( f.getText() ) ;
}
https://stackoverflow.com/questions/55112021
复制相似问题