import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; import java.io.IOException; public class Array extends JFrame{ private JTextField number = new JTextField(10); private JLabel result; int num; ArrayList<Integer> list = new ArrayList<>(); public static void main(String[] args){ Array frame = new Array(); frame.setTitle("Collections"); frame.setSize(700, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public Array() { add(new JLabel("You will enter 5 integers."), BorderLayout.NORTH); setLayout(new FlowLayout(FlowLayout.LEFT, 10,20)); add(new JLabel("Enter a number and click the enter button:")); add(number); JButton jbtEnter = new JButton("Enter"); jbtEnter.setToolTipText("This will store your number in the program"); add(jbtEnter); jbtEnter.addActionListener(new EnterListener()); JButton jbtDisplay = new JButton("Display"); jbtDisplay.setToolTipText("This will display all the integers in numberical order"); add(jbtDisplay); jbtDisplay.addActionListener(new DisplayListener()); result = (new JLabel("")); add (result); } class EnterListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ try{ int i = 0; if (i < 5){ num = Integer.parseInt(number.getText()); list.add(num); number.setText(null); i++; } catch (IndexOutOfBoundsException ex){ JOptionPane.showMessageDialog(null, "Error. You cannot exceed the limit of 5 entries. click other button.", "Error", JOptionPane.ERROR_MESSAGE); } } } class DisplayListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { Collections.sort(list); result.setText("The numbers you have entered, listed in numerical order is: " + list ); } } }
How can I make the user stop entering after 5 entries? the catch is to tell the user they can longer add entries.