Следующий код открывает пользовательский интерфейс с четырьмя полями, в которые пользователь может записать некоторую информацию.Некоторые значения могут уже появиться в полях из предыдущих использований.
Как я могу получить / сохранить эти значения, когда пользователь нажимает "ОК"?
Значения, чтобы получить :
- url ( JTextField )
- имя пользователя ( JTextField )
- пароль ( JPasswordField )
- оператор ( JTextArea )
Я думал, что значения будут сохранены в JPanel объекте 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);
}
Вывод:
![enter image description here](https://i.stack.imgur.com/pNieT.png)