問題は、ユーザーの入力を受け入れる方法を見つけられず、配列のサイズまでプロセスをとるのに最適なjcomponentは何ですか?
入力を受信するのに最適なコンポーネントはありません。コンポーネントのユースケースは、コンテキストによって異なります。あなたのケースでは、あなただけの数値を受け取りたいです。この目的のためにここに記載されているように、Document filterをセットアップすることができます。
https://stackoverflow.com/questions/7632387/jtextarea-only-with-numbers-but-allowing-negative-values
その後は、ボタンを作成し、それをクリックリスナを設定し、JTextAreaの値を取得し、あなたの条件に応じて、さらにそれを処理することができます。
この単純なコードスニペットにプロセス全体をまとめました。必要に応じて変更することができます。
DocumentFilterユーザー入力テキストおよび負の整数
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;
}
}
デモメインクラス
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();
}
}
を停止するには、あなたは、デバッグおよびnullであるかどうか確認しましたか?ユーザーが「番号/番号」だけを入力できることを確認しましたか、または彼がそれをしたかどうかを確認しましたか? – Thomas
[NullPointerExceptionとは何か、それを修正する方法は?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) ) – f1sh
複雑すぎる行をいくつかの基本要素に分割し、indexOfの結果にローカル変数を使用し、ステップごとにデバッグするか、System.err.printlnを使用してローカル変数の値を出力します。 文字列にはさまざまな入力があります。誤った入力をする可能性があります。 – Aubin