大佬教程收集整理的这篇文章主要介绍了通过几个曲线球在Swing JTextArea上强制使用最大字符,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
您可以使用DocumentFilter来限制最大大小,请参阅本文档部分,其中提供了您需要的有效示例。
以这个为例,我使用了上面示例文件中的组件:
import java.awt.borderLayout;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import components.documentSizefilter;
public class Test {
public static voID main(String[] args) {
new TestFrame().setVisible(true);
}
private static class TestFrame extends JFrame{
private JTextFIEld textFIEld;
private DefaultStyleddocument doc;
private JLabel remaningLabel = new JLabel();
public TestFrame() {
setLayout(new borderLayout());
textFIEld = new JTextFIEld();
doc = new DefaultStyleddocument();
doc.setdocumentFilter(new documentSizefilter(500));
doc.adddocumentListener(new documentListener(){
@OverrIDe
public voID changedupdate(documentEvent E) { updateCount();}
@OverrIDe
public voID insertupdate(documentEvent E) { updateCount();}
@OverrIDe
public voID removeupdate(documentEvent E) { updateCount();}
});
textFIEld.setdocument(doc);
updateCount();
add(textFIEld, borderLayout.CENTER);
add(remaningLabel, borderLayout.soUTH);
setLOCATIOnrelativeTo(null);
pack();
}
private voID updateCount()
{
remaningLabel.setText((500 -doc.getLength()) + " characters remaining");
}
}
}
我正在尝试向Swing JLabel和JTextArea添加功能,例如:
x
是它们到达字符前剩余的字符数最多500KeyEvent.VK_BACK_SPACE
),他们将“释放”一个字符,并且计数增加。因此,如果他们剩余400个字符,并键入退格键,则标签现在显示为“剩余401个字符”我有90%的功能都在工作,但是有一些错误,并且不知道如何实现上面的最后一项(突出显示的文本上的批量命令)。这是我所拥有的:
Boolean ignoreInput = false;
int charMax = 500;
JLabel charCntLabel = getLabel();
JTextArea myTextArea = getTextArea();
myTextArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent E) {
return;
}
@Override
public void keyReleased(KeyEvent E) {
// If we should be ignoring input then set make sure we
// enforce max character count and remove the newly typed key.
if(ignoreInput)
myTextArea.setText(myTextArea.getText().subString(0,myTextArea.getText().length()));
}
@Override
public void keyPressed(KeyEvent E) {
String charsRemaining = " characters remaining";
int newLen = 0;
// The key has just been pressed so Swing hasn't updated
// the text area with the new KeyEvent.
int currLen = myTextArea.getText().length();
// Adjust newLen depending on whether the user just pressed
// the BACkspace key or not.
if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
newLen = currLen - 1;
ignoreInput = false;
}
else
newLen = currLen + 1;
if(newLen < 0)
newLen = 0;
if(newLen == 0)
charCntLabel.setText(charMax + " characters maximum!");
else if(newLen >= 0 && newLen < charMaX)
charCntLabel.setText((charMax - newLen) + charsRemaining);
else if(newLen >= charMaX) {
ignoreInput = true;
charCntLabel.setText("0 " + charsRemaining);
}
}
});
上面的代码运行良好,但是有一些错误:
提前致谢。
以上是大佬教程为你收集整理的通过几个曲线球在Swing JTextArea上强制使用最大字符全部内容,希望文章能够帮你解决通过几个曲线球在Swing JTextArea上强制使用最大字符所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。