首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swing JFormattedTextField校正多行粘贴

Swing JFormattedTextField校正多行粘贴
EN

Stack Overflow用户
提问于 2015-09-05 05:53:50
回答 2查看 105关注 0票数 0

JFormattedTextField有一个bug。它不支持多行输入,但允许粘贴多行文本。我知道如何禁用复制/粘贴功能,但这不是我想要的。是否有可能拦截“粘贴”操作并从传入字符串中删除所有\n

臭虫证明:

代码语言:javascript
复制
package com;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SwingTest {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(new SimpleFTF());
        f.pack();
        f.setVisible(true);
    }

    public static class SimpleFTF extends JPanel {
        public SimpleFTF(){
            JFormattedTextField field = new JFormattedTextField("    ");
            add(field, java.awt.BorderLayout.CENTER);
        }
    }
}

试着粘贴:

代码语言:javascript
复制
1
2
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-05 08:48:46

代码语言:javascript
复制
/*Note This code works but if initial condition when you execute the code it will throw exception the the code works  
 Sorry but I don't know much about swing
*/
package com;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class SwingTest 
{
    public static void main(String[] args) 
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(new SimpleFTF());
        f.pack();
        f.setVisible(true);
    }
    public static class SimpleFTF extends JPanel 
    {            
        public SimpleFTF()
        {
            JFormattedTextField field = new JFormattedTextField("    ");  
           field.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    modify();   
                }
                @Override
                public void removeUpdate(DocumentEvent e) { 
                }
                @Override
                public void changedUpdate(DocumentEvent e) {                       
                }
                public void modify()
                {
                    String text=field.getText();
                    if(text.contains("\n"))
                        text=text.replaceAll("\n", "");
                        text=text.trim();
                        field.setText(text);
                }
            });                    
            add(field, java.awt.BorderLayout.CENTER);            
        }
    }
}
票数 2
EN

Stack Overflow用户

发布于 2015-09-05 06:10:08

您可以在JFormattedTextField上编写一个事件,因此如果粘贴了某个事件,它将删除\n ascii为10个字符并更新该字段。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32409973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档