从文本字段中保存文本,而无需单击或按下Java swing中的“保存”按钮

时间:2018-07-18 13:11:19

标签: java swing

如何在不单击或不按下Java swing中的保存按钮的情况下保存在textField中输入的文本。

1 个答案:

答案 0 :(得分:2)

您需要使用DocumentFilter并使用以下命令将其添加到JTextField中:((AbstractDocument) textbox.getDocument()).setDocumentFilter(filter);进行添加。这是 MCVE 的示例:

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Example extends JFrame {

    JTextField textbox = new JTextField(" ", 20);

    public Example() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        DocumentFilter filter = new DocumentFilter() {
            @Override
            public void insertString(DocumentFilter.FilterBypass fb, int offset, String string,
                AttributeSet attr) throws BadLocationException {
                super.insertString(fb, offset, string, attr);
                System.out.println("Inserted!");
            }

            public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
                throws BadLocationException {
                super.remove(fb, offset, length);
                System.out.println("removed!");
            }

            public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
                AttributeSet attrs) throws BadLocationException {
                super.replace(fb, offset, length, text, attrs);
                System.out.println("replaced!");
            }
        };

        ((AbstractDocument) textbox.getDocument()).setDocumentFilter(filter);
        panel.add(textbox);
        add(panel);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        new Example();
    }
}