問題是我找不到一種方法來接受用戶輸入,什麼是最好的jcomponent將採取進程的數組大小?
沒有任何東西像接收輸入的最佳組件。組件的用例因上下文而異。在你的情況下,你只想收到數字值。您可以按照此處所述爲此設置文檔過濾器。
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();
}
}
你調試和檢查什麼是空?你確定用戶只能輸入「號碼/號碼」還是檢查他是否做到了? – Thomas
可能的重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) – f1sh
將太複雜的行拆分爲幾個基本的行,對indexOf的結果使用局部變量並逐步進行調試,或使用System.err.println打印局部變量的值 編寫一個專用於解析字符串有很多不同的輸入,因爲它們可能有誤(用戶輸入) – Aubin