Java Swing jTextField如果限制输入的位数?
1个回答
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class DocumentTest extends JFrame
{
final static int docLength = 3;//表示可输入文本的最大长度
public DocumentTest()
{
super("DocumentTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((d.width-570)/2,(d.height-215)/2,570,215);
Document doc = new DefaultStyledDocument();
doc.addDocumentListener(new DocumentListener(){
public void insertUpdate(DocumentEvent e)
{
final Document document = e.getDocument();
if (document.getLength()>docLength)
{
try
{
new Thread(new Thread(){
public void run()
{
try
{
document.remove(1,document.getLength()-1);
}
catch (Exception exp)
{
System.out.println("Error: "+ exp.toString());
}
}
}).start();;
}
catch (Exception ex)
{
System.out.println("Error: "+ ex.toString());
}
}
}
public void removeUpdate(DocumentEvent e)
{}
public void changedUpdate(DocumentEvent e)
{
}
});
JTextArea area = new JTextArea(doc,"",30,40);
JPanel pane = new JPanel();
pane.add(area);
setContentPane(pane);
setVisible(true);
}
public static void main(String [] args)
{
new DocumentTest();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class DocumentTest extends JFrame
{
final static int docLength = 3;//表示可输入文本的最大长度
public DocumentTest()
{
super("DocumentTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((d.width-570)/2,(d.height-215)/2,570,215);
Document doc = new DefaultStyledDocument();
doc.addDocumentListener(new DocumentListener(){
public void insertUpdate(DocumentEvent e)
{
final Document document = e.getDocument();
if (document.getLength()>docLength)
{
try
{
new Thread(new Thread(){
public void run()
{
try
{
document.remove(1,document.getLength()-1);
}
catch (Exception exp)
{
System.out.println("Error: "+ exp.toString());
}
}
}).start();;
}
catch (Exception ex)
{
System.out.println("Error: "+ ex.toString());
}
}
}
public void removeUpdate(DocumentEvent e)
{}
public void changedUpdate(DocumentEvent e)
{
}
});
JTextArea area = new JTextArea(doc,"",30,40);
JPanel pane = new JPanel();
pane.add(area);
setContentPane(pane);
setVisible(true);
}
public static void main(String [] args)
{
new DocumentTest();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询