Reputation: 1
I am trying to add the user input from the text field into an array when I click the Add Button. The Display Button displays the whole array. I already initialized the array (array = new String[10]) else where in the program. I initialized the counter to 0 as a private variable. If the user enters more than 10 strings, the input should not be added. Any advice?
// 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);
}
}
Upvotes: 0
Views: 2419
Reputation: 331
Here you have a minimum example:
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);
Upvotes: 1