日期:2014-05-20  浏览次数:20625 次

怎样限制对JTextField可输入数据范围进行限制?
现在该控件的可输入数据为:【1,356】,怎样可对其进行动态限制?如:357等不可输入!

------解决方案--------------------
要自己也另写一个方法来操作了
------解决方案--------------------
看看这个吧.
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class TestText {
public static void main(String[] args) {
TextTestFrame frame = new TextTestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}

class TextTestFrame extends JFrame {
private WxtIntegerTextField field;

public TextTestFrame() {
setTitle( "TextTest ");
JPanel panel = new JPanel();
add(panel);
field = new WxtIntegerTextField();
field.setColumns(3);
JLabel label = new JLabel( "输入(1-356): ");
panel.add(label);
panel.add(field);
}
}

class WxtIntegerTextField extends JTextField {
private WxtIntegerDocument plainDoc = null;

public WxtIntegerTextField() {
super();
setDocument(plainDoc = new WxtIntegerDocument(this));
setHorizontalAlignment(JTextField.RIGHT);
}
}

class WxtIntegerDocument extends PlainDocument {
private JTextComponent myComponent = null;

public WxtIntegerDocument(JTextComponent txtComponent) {
myComponent = txtComponent;
}

public void insertString(int offset, String s, AttributeSet attributeSet)
throws BadLocationException {
if (s != null) {
StringBuffer buffer = new StringBuffer(s);
for (int i = buffer.length() - 1; i > = 0; i--) {
char ch = buffer.charAt(i);
if (!Character.isDigit(ch) && ch != ', ')
buffer.deleteCharAt(i);
}
s = buffer.toString();
}
super.insertString(offset, s, attributeSet);
}

public void replace(int offset, int length, String s,
AttributeSet attributeSet) throws BadLocationException {
String Value = myComponent.getText();
String str = " ";
String Result = " ";
if (myComponent.getText().length() > 0) {
str = myComponent.getText().substring(0, 1);
if (s.equals( "- ")) {
if (offset == 0 && !(str.equals( "- "))) {
Result = s + Value;
} else {
Toolkit.getDefaultToolkit().beep(); // Transfer the System 's
// ring
return;
}
} else {
Result = Value.substring(0, offset) + s
+ Value.substring(offset);
}
} else {
if (s.equals( "- ")) {
// super.insertString(offset, s, attributeSet);
Toolkit.getDefaultToolkit().beep(); // Transfer the System 's
// ring
return;
} else {
Result = s;
}
}

try {
long value = Long.parseLong(Result);
if (value > 356 || value <= 0) {
Toolkit.getDefaultToolkit().beep(); // Transfer the System 's
// ring
return;
}
} catch (Exception ex) {
Toolkit.getDefaultToolkit().beep(); // Transfer the System 's ring
return;
}
super.replace(offset, length, s, attributeSet);
}

}

------解决方案--------------------
up

相关资料更多>