我有一个JTextArea
,我希望用户输入一个人的地址。我知道用户将输入的有效地址不会超过 5 行
和 10 列
。所以我将它设置为 JTextArea (5,10)
。这样效果很好。
问题是,当用户持续按 enter
超过 5 次时,文本区域将开始调整大小。我不想将文本区域放在 JScrollPane
中,因为用户输入的文本不适合滚动。
问题:我们如何禁止 JTextArea
在用户按下 enter
时调整大小?
这是我的代码:
public class JTextAreaDemo {
private JFrame frame;
JTextAreaDemo(){
frame= new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new net.miginfocom.swing.MigLayout());
frame.setVisible(true);
frame.setLocationRelativeTo(null);
JLabel label=new JLabel("Address :");
JTextArea address= new JTextArea(5,20);
frame.add(label,"cell 0 0");
frame.add(address, "cell 1 0");
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new JTextAreaDemo();
}});
}
}
最佳答案
你可以尝试使用DocumentFilter
,例如:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTextArea area;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
area = new JTextArea();
((AbstractDocument)area.getDocument()).setDocumentFilter(getFilter(5));
add(new JScrollPane(area));
}
private DocumentFilter getFilter(final int lineCount) {
return new DocumentFilter(){
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
if(area.getLineCount()<=lineCount && area.getLineOfOffset(area.getCaretPosition())<lineCount)
if(text.contains("\n") && area.getLineCount()<lineCount)
super.replace(fb, offset, length, text, attrs);
else if(!text.contains("\n"))
super.replace(fb, offset, length, text, attrs);
}
};
}
}
关于java - 当用户按 Enter 时禁用 JTextArea 调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29819664/