Example usage for javax.swing.event DocumentListener DocumentListener

List of usage examples for javax.swing.event DocumentListener DocumentListener

Introduction

In this page you can find the example usage for javax.swing.event DocumentListener DocumentListener.

Prototype

DocumentListener

Source Link

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JTextComponent textcomp = new JTextPane();
    textcomp.setText("Initial Text");
    textcomp.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent evt) {
            int off = evt.getOffset();
            System.out.println("off:" + off);
            int len = evt.getLength();
            System.out.println("len:" + len);
            try {
                String str = evt.getDocument().getText(off, len);
                System.out.println(str);
            } catch (BadLocationException e) {
            }/*  ww w.j  av  a 2s.com*/
        }

        public void removeUpdate(DocumentEvent evt) {
            int off = evt.getOffset();
            System.out.println("off:" + off);
            int len = evt.getLength();
            System.out.println("len:" + len);
        }

        public void changedUpdate(DocumentEvent evt) {
            int off = evt.getOffset();
            System.out.println("off:" + off);
            int len = evt.getLength();
            System.out.println("len:" + len);
        }
    });
}

From source file:Main.java

public static void main(String[] args) {
    JPanel mainPanel = new JPanel();
    JTextField field = new JTextField(20);
    JTextField field1 = new JTextField(20);

    field.getDocument().addDocumentListener(new DocumentListener() {
        @Override//from  ww w .  j a va  2  s  . c o m
        public void changedUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateLabel(e);
        }

        private void updateLabel(DocumentEvent e) {
            field1.setText(field.getText());
        }
    });

    mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
    mainPanel.add(field);
    mainPanel.add(field1);

    JFrame frame = new JFrame();
    frame.getContentPane().add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:AddingDocumentListenerJTextFieldSample.java

public static void main(String args[]) {
    final JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);/*from  w  ww. ja  v a2  s .  c o m*/
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type : " + typeString);
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            System.out.println("Length: " + length);
        }
    };
    textField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JPanel topPanel = new JPanel();
    topPanel.setPreferredSize(new Dimension(200, 200));
    topPanel.setBackground(Color.WHITE);

    JTextArea chatArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(chatArea);

    JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
    mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    mainPanel.add(topPanel, BorderLayout.CENTER);
    mainPanel.add(scrollPane, BorderLayout.SOUTH);

    chatArea.getDocument().addDocumentListener(new DocumentListener() {

        @Override/*from   w w w.  jav  a  2  s.  c  o m*/
        public void insertUpdate(DocumentEvent e) {
            updateLineCount();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateLineCount();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateLineCount();
        }

        private void updateLineCount() {
            int lineCount = chatArea.getLineCount();
            if (lineCount <= 4) {
                chatArea.setRows(lineCount);
                mainPanel.revalidate();
            }
        }
    });

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(mainPanel);
    f.pack();
    f.setVisible(true);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);//ww w.  j a  v a2s  . co  m
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 100);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    JTextPane textPane = new JTextPane();
    JTextField tf = new JTextField("is");
    String word = "";
    Highlighter highlighter = new UnderlineHighlighter(null);

    textPane.setHighlighter(highlighter);
    textPane.setText("This is a test");
    panel.setLayout(new BorderLayout());
    panel.add(new JLabel("Enter word, then press ENTER key: "), "West");
    panel.add(tf, "Center");

    final WordSearcher searcher = new WordSearcher(textPane);
    tf.addActionListener(e -> {/*from  w  w  w . j a  v  a 2s. co m*/
        String w = tf.getText().trim();
        int offset = searcher.search(w);
        if (offset == -1) {
            return;
        }
        try {
            textPane.scrollRectToVisible(textPane.modelToView(offset));
        } catch (BadLocationException ex) {
        }

    });
    textPane.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent evt) {
            searcher.search(word);
        }

        @Override
        public void removeUpdate(DocumentEvent evt) {
            searcher.search(word);
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
        }
    });
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(panel, "South");
    f.add(new JScrollPane(textPane), "Center");
    f.setSize(400, 400);
    f.setVisible(true);
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
    textField1.setFormatterFactory(new AbstractFormatterFactory() {
        @Override/* ww w. jav a2s . co m*/
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
    attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
    final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
    textField2.setFormatterFactory(new AbstractFormatterFactory() {

        @Override
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    textField2.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            double t1a1 = (((Number) textField2.getValue()).doubleValue());
            if (t1a1 > 100) {
                textField2.setFont(new Font(attributes));
                textField2.setForeground(Color.red);
            } else {
                textField2.setFont(new Font("Serif", Font.BOLD, 16));
                textField2.setForeground(Color.black);
            }
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.SOUTH);
    frame.setVisible(true);
    frame.pack();
}

From source file:UndoExample1.java

public static void main(String[] args) {
    try {//ww  w  . j ava  2  s  .co m
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new UndoExample1();
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent evt) {
            System.exit(0);
        }
    });
    f.setSize(250, 300);
    f.setVisible(true);

    // Create and show a frame monitoring undoable edits
    JFrame undoMonitor = new JFrame("Undo Monitor");
    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    undoMonitor.getContentPane().add(new JScrollPane(textArea));
    undoMonitor.setBounds(f.getLocation().x + f.getSize().width, f.getLocation().y, 400, 200);
    undoMonitor.setVisible(true);

    pane.getDocument().addUndoableEditListener(new UndoableEditListener() {
        public void undoableEditHappened(UndoableEditEvent evt) {
            UndoableEdit edit = evt.getEdit();
            textArea.append(edit.getPresentationName() + "(" + edit.toString() + ")\n");
        }
    });

    // Create and show a frame monitoring document edits
    JFrame editMonitor = new JFrame("Edit Monitor");
    final JTextArea textArea2 = new JTextArea();
    textArea2.setEditable(false);
    editMonitor.getContentPane().add(new JScrollPane(textArea2));
    editMonitor.setBounds(undoMonitor.getLocation().x,
            undoMonitor.getLocation().y + undoMonitor.getSize().height, 400, 200);
    editMonitor.setVisible(true);

    pane.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent evt) {
            textArea2.append("Attribute change\n");
        }

        public void insertUpdate(DocumentEvent evt) {
            textArea2.append("Text insertion\n");
        }

        public void removeUpdate(DocumentEvent evt) {
            textArea2.append("Text removal\n");
        }
    });
}

From source file:JTextFieldSample.java

public static void main(String args[]) {
    String title = (args.length == 0 ? "TextField Listener Example" : args[0]);
    JFrame frame = new JFrame(title);
    Container content = frame.getContentPane();

    JPanel namePanel = new JPanel(new BorderLayout());
    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField nameTextField = new JTextField();
    nameLabel.setLabelFor(nameTextField);
    namePanel.add(nameLabel, BorderLayout.WEST);
    namePanel.add(nameTextField, BorderLayout.CENTER);
    content.add(namePanel, BorderLayout.NORTH);

    JPanel cityPanel = new JPanel(new BorderLayout());
    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setDisplayedMnemonic(KeyEvent.VK_C);
    JTextField cityTextField = new JTextField();
    cityLabel.setLabelFor(cityTextField);
    cityPanel.add(cityLabel, BorderLayout.WEST);
    cityPanel.add(cityTextField, BorderLayout.CENTER);
    content.add(cityPanel, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Command: " + actionEvent.getActionCommand());
        }/*from w  ww.j a  v a  2  s  .co m*/
    };
    nameTextField.setActionCommand("Yo");
    nameTextField.addActionListener(actionListener);
    cityTextField.addActionListener(actionListener);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        }
    };
    nameTextField.addKeyListener(keyListener);
    cityTextField.addKeyListener(keyListener);

    InputVerifier verifier = new InputVerifier() {
        public boolean verify(JComponent input) {
            final JTextComponent source = (JTextComponent) input;
            String text = source.getText();
            if ((text.length() != 0) && !(text.equals("Exit"))) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(source, "Can't leave.", "Error Dialog",
                                JOptionPane.ERROR_MESSAGE);
                    }
                };
                SwingUtilities.invokeLater(runnable);
                return false;
            } else {
                return true;
            }
        }
    };
    nameTextField.setInputVerifier(verifier);
    cityTextField.setInputVerifier(verifier);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    cityTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:UndoExample5.java

public static void main(String[] args) {
    try {/*from www.j av  a2  s.co m*/
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new UndoExample5();
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent evt) {
            System.exit(0);
        }
    });
    f.setSize(250, 300);
    f.setVisible(true);

    // Create and show a frame monitoring undoable edits
    JFrame undoMonitor = new JFrame("Undo Monitor");
    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);
    undoMonitor.getContentPane().add(new JScrollPane(textArea));
    undoMonitor.setBounds(f.getLocation().x + f.getSize().width, f.getLocation().y, 400, 200);
    undoMonitor.setVisible(true);

    pane.getDocument().addUndoableEditListener(new UndoableEditListener() {
        public void undoableEditHappened(UndoableEditEvent evt) {
            UndoableEdit edit = evt.getEdit();
            textArea.append(edit.getPresentationName() + "(" + edit.toString() + ")\n");
        }
    });

    // Create and show a frame monitoring document edits
    JFrame editMonitor = new JFrame("Edit Monitor");
    final JTextArea textArea2 = new JTextArea();
    textArea2.setEditable(false);
    editMonitor.getContentPane().add(new JScrollPane(textArea2));
    editMonitor.setBounds(undoMonitor.getLocation().x,
            undoMonitor.getLocation().y + undoMonitor.getSize().height, 400, 200);
    editMonitor.setVisible(true);

    pane.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent evt) {
            textArea2.append("Attribute change\n");
        }

        public void insertUpdate(DocumentEvent evt) {
            textArea2.append("Text insertion\n");
        }

        public void removeUpdate(DocumentEvent evt) {
            textArea2.append("Text removal\n");
        }
    });
}