The problem is I couldn't figure out a way to take user input, what is the best jcomponent that will take processes up to the size of the array ?
There isn't anything like best component to receive inputs. Use cases of the components vary from context to context. In your case, you want to receive number value only. You could setup Document filter as described here for this purpose.
https://stackoverflow.com/questions/7632387/jtextarea-only-with-numbers-but-allowing-negative-values
Then you could create button and configure click listener on it and then retrieve the jTextarea value and then process it further according to your requirement.
I have summarized the whole process into this simple code snippet. You can modify it according to your need.
DocumentFilter to stop user entering text and negative integers
import javax.swing.text.*;
import java.util.regex.*;
public class PositiveNumberOnlyFilter extends DocumentFilter
{
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.insertString(offset, text, attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.replace(offset, offset + length, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.replace(offset, length, text, attr);
}
public boolean containsOnlyNumbers(String text)
{
Pattern pattern = Pattern.compile("^[1-9]\\d*$");
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
}
Demo Main Class
import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;
public class SimpleNumberOnlyTextAreDemo implements ActionListener {
JLabel labelOne;
JTextArea textArea;
JButton button;
SimpleNumberOnlyTextAreDemo() {
JFrame f = new JFrame();
labelOne = new JLabel();
labelOne.setBounds(50, 25, 200, 30);
textArea = new JTextArea();
textArea.setBounds(50, 75, 200, 25);
button = new JButton("Click To Create Array");
button.setBounds(50, 150, 200, 30);
button.addActionListener(this);
f.add(labelOne);
f.add(textArea);
f.add(button);
f.setSize(350, 350);
f.setLayout(null);
f.setVisible(true);
DocumentFilter onlyNumberFilter = new AxisJTextFilter();
((AbstractDocument) this.textArea.getDocument()).setDocumentFilter(onlyNumberFilter);
}
@Override
public void actionPerformed(ActionEvent e) {
String text = textArea.getText();
labelOne.setText("Input is := " + text);
}
public static void main(String[] args) {
SimpleNumberOnlyTextAreDemo simpleNumberOnlyTextAreDemo = new SimpleNumberOnlyTextAreDemo();
}
}