Получить несколько значений из JPanel в пользовательском интерфейсе - PullRequest
0 голосов
/ 12 марта 2019

Следующий код открывает пользовательский интерфейс с четырьмя полями, в которые пользователь может записать некоторую информацию.Некоторые значения могут уже появиться в полях из предыдущих использований.

Как я могу получить / сохранить эти значения, когда пользователь нажимает "ОК"?

Значения, чтобы получить :

  1. url ( JTextField )
  2. имя пользователя ( JTextField )
  3. пароль ( JPasswordField )
  4. оператор ( 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

1 Ответ

0 голосов
/ 12 марта 2019

Вы можете поместить все свои поля JTextFields в коллекцию List, как это

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() ) ;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...