Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * JLibs: Common Utilities for Java
 * Copyright (C) 2009  Santhosh Kumar T <santhosh.tekuri@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

import javax.swing.text.DefaultCaret;
import javax.swing.text.JTextComponent;

public class Main {
    /**
     * sets text of textComp without moving its caret.
     *
     * @param textComp  text component whose text needs to be set
     * @param text      text to be set. null will be treated as empty string
     */
    public static void setText(JTextComponent textComp, String text) {
        if (text == null)
            text = "";

        if (textComp.getCaret() instanceof DefaultCaret) {
            DefaultCaret caret = (DefaultCaret) textComp.getCaret();
            int updatePolicy = caret.getUpdatePolicy();
            caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
            try {
                textComp.setText(text);
            } finally {
                caret.setUpdatePolicy(updatePolicy);
            }
        } else {
            int mark = textComp.getCaret().getMark();
            int dot = textComp.getCaretPosition();
            try {
                textComp.setText(text);
            } finally {
                int len = textComp.getDocument().getLength();
                if (mark > len)
                    mark = len;
                if (dot > len)
                    dot = len;
                textComp.setCaretPosition(mark);
                if (dot != mark)
                    textComp.moveCaretPosition(dot);
            }
        }
    }
}