Как добавить пользовательский ввод из текстового поля в массив? - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь добавить пользовательский ввод из текстового поля в массив при нажатии кнопки Добавить. Кнопка Display отображает весь массив. Я уже инициализировал массив (array = new String [10]) в другом месте программы. Я инициализировал счетчик 0 как частную переменную. Если пользователь вводит более 10 строк, ввод не должен быть добавлен. Любой совет?

    // if add button is clicked
    if (e.getSource() == btnAdd){

        /*input = textInput.getText();
        output = textOutput.getText() + input + "\n";
        textOutput.setText(output);*/

        // get user input from text field
        input = textInput.getText();  

        // clear text input field
        textInput.setText("");

        /*do {

            array[counter] = input;
            counter++;

        } while (counter < 11);

        if (counter > 10){

            picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
            picBottom.setC(Color.RED);
        }*/

        // add user input to array if counter is within array length
        if (counter <= 10){

            array[counter] = input;
            counter++;
        }

        // display no more space available if counter is outside of array length
        else {

            picBottom = new TextPicture(new String("No Space Available"), new Font("TimesRoman", Font.ITALIC, 30), new Color(0));
            picBottom.setC(Color.RED);
        }
    }

    // if display button is clicked
    else if (e.getSource() == btnDisplay){

        // go through array & display each string
        for (int i = 0; i <= counter; i++){

            output += array[i];
            textOutput.setText(output);
        }
    }

1 Ответ

1 голос
/ 02 апреля 2020

Вот минимальный пример:

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 300, 300);

JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 150));

JTextField txtField = new JTextField("");
txtField.setPreferredSize(new Dimension(200, 30));

JButton button = new JButton("Push me");
button.addActionListener((ActionEvent arg0) -> {
    if(counter < 10){
        array[counter] = txtField.getText();
        counter++;
        txtField.setText("");
        txtField.requestFocus();
    }
    else{
        System.out.println("No Space Available");
    }


    System.out.println(Arrays.toString(array));
});
panel.add(txtField);
panel.add(button);

frame.add(panel);
frame.setVisible(true);
...