Swing JFormattedTextField修正多行粘贴

时间:2015-09-05 05:53:50

标签: java swing copy-paste jformattedtextfield

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

错误证明:

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);
        }
    }
}

尝试粘贴:

1
2

2 个答案:

答案 0 :(得分:2)

/*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);            
        }
    }
}

答案 1 :(得分:1)

你可以在JFormattedTextField上写一个事件,所以如果粘贴了什么东西,它会删除\ n ascii是10个字符并更新字段。