Caret(s)

Hello,
I'm currently working on a Java Application which displays Persian characters(right to left writing but numbers are left to right) in JFrame. Whenever I push space bar, the caret jumps to the right direction(left to right writing).
What is the best/easiest way to solve this problem?
I will be delighted to get any suggestion/sample code.
Thanks
David Safara
[email protected]

Hmmm, interesting one.
I think what you need here is a keyListener, so that when the user enters any character other thana number or the space bar (keyCode() = 32 I think) the space character entered is deleted and the caret position moves to zero, then the most recently entered character (next right) and so on - it should be not too difficult to solve.
Then, if the user enters numbers (keyCode() = 48 to 57), the instruction to 'setCaretPosition(0)' and write the recent character right-to-left would be ignored.
Does this make sense to you?

Similar Messages

  • Arrow keys up and down no longer working NOT caret browsing.

    I'm running the Nightly 64-bit build on Windows 7. Two or three nights ago one of the updates came down the pipes and my arrow keys stopped working correctly. When typing in either a url or search if you try to scroll through it will only hit the top and bottom (and hitting down responds like I've hit the up) I've checked caret browsing and disabled all addons to test and still no luck. In the search area I've noticed it only hits 1/3 of the suggestions. Why is this happening? I've had to resort to typing out the full url and search or using the mouse which is sometimes annoying given I used to just hit one down arrow and press enter no need to move my right hand from the keyboard at all.

    Since you are Testing the unstable Nightly channel builds, you may be better off getting help in http://forums.mozillazine.org/viewforum.php?f=23 where many Testers hang out as almost everybody here uses Releases and maybe Betas.

  • How to change the size of the caret in a JTextPane

    I have text of different font sizes and the default caret height is the height of the text with the maximum font size. How do I change the caret height so that it matches the height of the text with the specified font size ?

    This has been a real pain in the butt to figure out, but I think I finally got it. If you create your own caret (subclass of DefaultCaret) then you override its paint() and damage() methods. I was having all kinds of problems with this though. I was getting pieces of carets left behind when I moved with the arrow keys, etc... from the helps I found. The arrow keys were my big problem.
    I think I finally figured out that the damage() simply does need to specify an area a little bigger than the old caret so it can blank it out. Then I think others had a logic problem, and Sun does not make this problem clear. What happens it that I think repaint() calls paint() who then uses the bigger x, y, height and width parameters that got set in damage(), which was causing my problems because the damage size was bigger than the size I wanted to create my caret with. What I do is figure out my area from the font I am using (another trick) and make them (the charWd and charHt) variables class variables. I calculate them in damage, use a bigger area to blank out my old caret in damage, and then used the correct caret size I calculated in damage() in paint(), instead of the rectangle values that seem to get passed from damage() to paint(). That was the problem in other examples.
    Here is my code:
    run with java caretPain
    run with java caretPain -1 to see my fixed version
    run with java caretPain -2 to see some problems
    // written by: Stan Towianski
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Hashtable;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.undo.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    import javax.swing.plaf.*;
    import java.net.URL;
    import java.io.*;
    import java.beans.*;
    public class caretPain extends JFrame {
    static caretPain CRTP2;
    JPanel contentPane;
    JTextPane textPane;
    JTextPane textPane2;
    JScrollPane scrollPane;
    JSplitPane splitPane;
    String newline = "\n";
    static final int MAX_CHARACTERS = 300100;
    static int FrameWidth = 500;
    static int FrameHeight = 300;
    String caretType = "blockOutline";
    static int useSpecialCaret = 0;
    DefaultCaret useCaret = new MyCaret();
    public caretPain() {
    textPane = new JTextPane( new DefaultStyledDocument() );
    textPane2 = new JTextPane( new DefaultStyledDocument() );
    if ( useSpecialCaret == 1 )
    System.out.println( "using special caret 1" );
    textPane.setCaret( useCaret );
    else if ( useSpecialCaret == 2 )
    System.out.println( "using special caret 2" );
    textPane.setCaret( new WsCaret() );
    textPane.setCaretPosition(0);
    textPane.setMargin(new Insets(5,5,5,5));
    scrollPane = new JScrollPane(textPane);
    textPane.setPreferredSize(new Dimension(FrameWidth, FrameHeight));
    JScrollPane scrollPane = new JScrollPane(textPane);
    //Create a split pane for the change log and the text area.
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
    textPane, textPane2 );
    splitPane.setOneTouchExpandable(true);
    //Add the components to the frame.
    contentPane = new JPanel(new BorderLayout());
    contentPane.add(splitPane, BorderLayout.CENTER);
    setContentPane(contentPane);
    class MyCaret extends DefaultCaret
    int charWd = 30;
    int charHt = 30;
    // draw the caret
    public void paint(Graphics g)
    System.err.println( "entered MyCaret.paint()" );
    if ( ! isVisible() )
    System.err.println( "exiting because not visible" );
    return;
    try {
    JTextComponent c = getComponent();
    int dot = getDot();
    Rectangle r = c.modelToView(dot);
    System.err.println("caret: text position: " + dot +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    g.setColor(c.getCaretColor());
    //g.drawLine(r.x, r.y + r.height - 1, r.x + 14, r.y + r.height - 1);
    System.err.println( "caretType =" + caretType ); //+ " component =" + c.toString() );
    if ( caretType.equals( "blockOutline" ) )
    g.drawRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "block" ) )
    g.fillRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "bar" ) )
    g.drawLine( r.x, r.y, r.x, r.y + charHt );
    catch (BadLocationException e) {
    System.err.println( "bad caret loc" + e);
    // specify the size of the caret for redrawing
    // and do repaint() -- this is called when the
    // caret moves
    //protected synchronized void damage(Rectangle r)
    public synchronized void damage(Rectangle r)
    System.err.println( "entered MyCaret.damage()" );
    System.err.println("caret.damage(): text position: " + getDot() +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    //FontMetrics fm = g.getFontMetrics();
    //System.out.println( "textPane getfont =" + textPane.getFont() );
    //System.out.println( "\n\n read in attribs font size =" + textPane.getInputAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    //int ii = Integer.parseInt( (String) textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    int ii = Integer.parseInt( String.valueOf( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) ) );
    //System.out.println( "textPane input attrib font size =" + ii );
    Font f = new Font( "ff", Font.PLAIN, ii );
    //System.out.println( "textPane input attrib font =" + f );
    FontMetrics fm = getFontMetrics( f );
    //FontMetrics fm = g.getFontMetrics();
    //FontMetrics fm = getFontMetrics( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    //MutableAttributeSet inputAttributes = getInputAttributes();
    //String fs = textPane.getAttribute( "FontSize" );
    //System.out.println( "\n\n read font size =" + textPane.getCharacterAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    charWd = fm.charWidth( 'k' );
    charHt= fm.getHeight();
    //System.out.println( "font width =" + charWd + " font height =" + charHt + " font =" + fm.toString());
    if ( r == null )
    System.err.println( "caret.damage() return on rectangle == null" );
    return;
    x = r.x - 2;
    y = r.y - 2; // + r.height - 2;
    width = charWd + 4; //textPane.getColumnWidth();
    height = charHt + 4; //textPane.getRowHeight();
    System.err.println("caret.damage(): set caret width, height, x, y =" + width + "," + height + "," + x + "," + y );
    repaint();
    //repaint();
    public class WsCaret extends DefaultCaret {
    transient private int[] flagXPoints = new int[3];
    transient private int[] flagYPoints = new int[3];
    public WsCaret() {
    this.setBlinkRate(500);
    public void paint(Graphics g) {
    if(isVisible()) {
    JTextComponent component = this.getComponent();
    TextUI mapper = component.getUI();
    Rectangle r = null;
    try {
    r = mapper.modelToView(component, this.getDot());
    catch(BadLocationException exc) {}
    //System.out.println( "rect r =" + r.toString() );
    //g.drawLine(r.x, r.y, r.x, r.y + r.height - 1);
    //g.drawLine(r.x+1, r.y, r.x+1, r.y + r.height - 1);
    g.drawRect( r.x, r.y, 10, r.height );
    Document doc = component.getDocument();
    if (doc instanceof AbstractDocument) {
    Element bidi = ((AbstractDocument)doc).getBidiRootElement();
    if ((bidi != null) && (bidi.getElementCount() > 1)) {
    // there are multiple directions present.
    flagXPoints[0] = r.x;
    flagYPoints[0] = r.y;
    flagXPoints[1] = r.x;
    flagYPoints[1] = r.y + 4;
    flagYPoints[2] = r.y;
    flagXPoints[2] = (true) ? r.x + 5 : r.x - 4;
    System.out.println( "going g.fillPolygon" );
    g.fillPolygon(flagXPoints, flagYPoints, 3);
    protected synchronized void damage(Rectangle r) {
    if (r != null) {
    this.x = r.x - 4;
    this.y = r.y;
    //there must be a better way to doing this, but for now you
    //just increase the width so that it will cover the new caret's size
    this.width = 20; // the original width is 10
    this.height = r.height;
    //this.height = r.height + 20;
    //this.height = 10;
    repaint();
    //The standard main method.
    public static void main(String[] args) {
    if ( args.length > 0 )
    System.out.println( "found arg so will use special caret." );
    if ( args[0].equals( "-1" ) )
    useSpecialCaret = 1;
    else if ( args[0].equals( "-2" ) )
    useSpecialCaret = 2;
    else
    System.out.println( "found no arg so will standard caret." );
    System.out.println( "give arg: -1 to get Stan\'s working caret" );
    System.out.println( "give arg: -2 to get another example\'s caret" );
    try
    CRTP2 = new caretPain();
         catch (Exception ex)
    System.out.println("Error creating CRTP2: " + ex);
    ex.printStackTrace();
    System.exit(0);
    CRTP2.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void windowActivated(WindowEvent e) {
    CRTP2.textPane.requestFocus();
    CRTP2.setTitle( "This is my title you" );
    CRTP2.pack();
    CRTP2.setVisible(true);

  • How to get the caret inside a custom editor?

    I was reading through old posts the other day and noticed this by Rob Camick in this thread Re: Problem in cell selection in JTable Java Swing :
    camickr wrote:
    All KeyEvents are passed to the editor for the cell and the editor is psuedo invoked. That is, the caret is not placed on the text field used as the editor, but the character typed is added to the editor.This set me thinking about a known issue in my app which I had shelved for a "rainy day": how to get the caret into the cell editor component. I thought I'd get it out and look at it. I tried the following, in my custom cell editor:
      public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                                                 int row, int column)
        JTextField ec = (JTextField) editorComponent;
        ec.setText((String) value);
        if ("".equals(ec.getText()))
          ec.setCaretPosition(0);
        else
          ec.selectAll();
        return editorComponent;
      }But it has no effect whatsoever, the user still can't type something in and then press the backspace key to useful effect. Has anyone out there solved this problem? (And why, oh why, is the caret not put into the cell editor by default, if it's a component that has a caret?)

    Replying to my own post, in case what I ended up with is of some help to others. The desired behaviour was that anything the cell contained from the previous edit would be replaced by what the user types in the current edit, i.e.:
    user starts edit, types 234, stops editing, cell displays 234...user single-clicks on cell, types 567, stops editing, cell displays 567
    My code is as follows:
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row,
                                                     int column)
          final JTextField ec = (JTextField) editorComponent;
          ec.setText((String) value);
          // selectAll, so that whatever the user types replaces what we just put there
          ec.selectAll();
          SwingUtilities.invokeLater(new Runnable()
            public void run()
              // make the component take the keyboard focus, so the backspace key works
              ec.requestFocus();
              SwingUtilities.invokeLater(new Runnable()
                public void run()
                  // at this point the user has typed something into the cell and we
                  // want the caret to be AFTER that character, so that the next one
                  // comes in on the RHS
                  ec.setCaretPosition(ec.getText().length());
          return editorComponent;
        }

  • Caret character in numbers (iWork09) not working with german keyboard

    The caret caracter used to express "power to" in formulas can not be typed into formulas with the german keyboard layout. Using the caret key nothing happens. For text and strings in cells the caret key works. In iWork08 everything is fine. For formulas the caret character has such to be inserted using copy and paste.
    This is more or less a bug report. I could not find a way to tell Apple directly.
    Matthias

    Thanks
    I'm glad to get this info because I thaught that it was linked to physical keyboards which it isn't.
    Report sent:
    *Your tracking number for this issue is Bug ID# 6491581.*
    Hello
    +In Numbers '09 we are unable to type the caret in this kind of formula =2^3 when we are using a keyboard layout where this key is a dead one.+
    +I tested Numbers in three languages:+
    English
    French
    German.
    +They behave exactly the same way with the keyboards layout where caret is a deadkey.+
    +Examples of tested layouts:+
    French,
    German,
    Swedish
    +At this time, we must use the Character Palette (or a copy paste) to enter the caret.+
    +I wish to add that this bug strikes only in the "edit formula" tool.+
    +Whe we type the content of a string, it works.+
    +We may use the caret to type the circumflex above thr e in this example:+
    +="c'est" & " le même"+
    Yvan KOENIG (from FRANCE mardi 13 janvier 2009 10:47:05)

  • Creating a bitmap copy of a TextFlow object without the caret [cursor]

    Hey all
    I'm currently working on creating a bitmap copy of a TextFlow object and I am looking at hiding the caret. What would be the best way forward, using the focusmanager to 'unfocus' the TextFlow object, or is there some more direct approach available? I know there is a cursormanager in Flex, but this is an AS3 only project.
    Cheers for your thoughts once again
    emd

    I think I've just done something similar to what you need (except I'm adjusting the width of the bitmap according to that of the text), and so far I have seen no cursor
    Here's the code. You'll need to adjust it depending on how many containers (Sprites) you are drawing the TextFlow to.
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx"
                   applicationComplete="init()">
        <fx:Declarations>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <s:Group id="groupText" width="560" />
        <fx:Script>
            <![CDATA[
                import flashx.textLayout.container.ContainerController;
                import flashx.textLayout.conversion.TextConverter;
                import flashx.textLayout.elements.TextFlow;
                import mx.core.UIComponent;
                private function init() : void
                    var text : String = "Greek god gives mints.";
                    var fontSize : int = 24;
                    //We create a textflow with some text and set it's font size, just as an example.
                    var flow : TextFlow = TextConverter.importToFlow(text, TextConverter.PLAIN_TEXT_FORMAT);
                    flow.fontSize = 24;
                    //We'll use a single container (and consecuently a single controller)
                    var container : Sprite = new Sprite()
                    var controller : ContainerController = new ContainerController(container);
                    flow.flowComposer.addController(controller);
                    //This is kind of weird, but I saw it in a TLF example, and it works.
                    //It seems you have to "stretch" the container.
                    controller.setCompositionSize(this.stage.stageWidth, this.stage.stageHeight);
                    flow.flowComposer.compose();
                    //Set the text's actual width and height as the composition size.
                    controller.setCompositionSize(controller.getContentBounds().width,
                        controller.getContentBounds().height);
                    //Redraw.
                    flow.flowComposer.updateAllControllers();
                    //As BitmapData's draw method takes an IBitmapDrawable,
                    //we'll need to wrap the Sprite instance in an UIComponent.
                    var tf : UIComponent = new UIComponent();
                    tf.addChild(container);
                    //Create an instance of BitmapData and "draw the container" into it.
                    var bd : BitmapData = new BitmapData(controller.getContentBounds().width,
                        controller.getContentBounds().height + 2, true, 0x000000);
                    bd.draw(tf);
                    //Create a Bitmap with the text's data and add it to the application.
                    var bmp : Bitmap = new Bitmap(bd);
                    var ui : UIComponent = new UIComponent();
                    ui.addChild(bmp);
                    this.groupText.addElement(ui);           
            ]]>
        </fx:Script>
    </s:Application>
    Hope it helps,
    Sebastián.

  • Find caret position of search text in jEditorPane

    Hi All,
    I am looking for a way to find the Caret position in a jeditor pane for the search text that i supply. The Jeditor pain is setup for text/html and when i find the index of my search text "ANCHOR_d" in the jeditor pane is 27000 something but the caret position is 7495 how do you find the caret position of the search text ??
    Any help is appriciated.
    I am also looking into getting abnchoring to work in the jeditorpane html text but as of yet i have been unsuccessful.
    Kind Regards,
    Wurns

    Search the underlying document, not the editor pane. Play around with this example, which I threw together the other day for a somewhat similar problem with JTextPane involving newlines, and modified for your need.
    Note: Please do not program by exception.import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.text.Document;
    public class SearchEditorPane {
       JFrame frame = new JFrame ("Search JTextPane Test");
       String html = "<HTML><BODY><P>This is <B>some</B>" +
                    " <I>formatted</I>" +
                    " <FONT color=#ff0000>colored</FONT>" +
                    " html.</P>" +
                    "<P>This is a <FONT face=Comic Sans MS>" +
                    "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                    "And this is a new division</div>" +
                    "</BODY></HTML>";
       JEditorPane editorPane = new JEditorPane ("text/html", html);
       JPanel panel = new JPanel ();
       JTextField textField = new JTextField (10);
       JButton button = new JButton ("Find");
       Document doc = editorPane.getDocument ();
       void makeUI () {
          editorPane.setText ("<HTML><BODY><P>This is <B>some</B>" +
                " <I>formatted</I>" +
                " <FONT color=#ff0000>colored</FONT>" +
                " html.</P>" +
                "<P>This is a <FONT face=Comic Sans MS>" +
                "comic <br>\n<br>\nsans ms</FONT> section</P><div>" +
                "And this is a new division</div>" +
                "</BODY></HTML>");
          button.addActionListener (new ActionListener () {
             public void actionPerformed (ActionEvent e) {
                // Programming by exception is BAD, don't copy this style
                // This is just to illustrate the solution to the problem at hand
                // (Sorry, uncle-alice, haven't reworked it yet)
                try {
                   Matcher matcher = Pattern.compile (textField.getText ())
                   .matcher (doc.getText (0, doc.getLength ()));
                   matcher.find ();
                   editorPane.setCaretPosition (matcher.start ());
                   editorPane.moveCaretPosition (matcher.end ());
                   editorPane.requestFocus ();
                } catch (Exception ex) {
                   JOptionPane.showMessageDialog (frame, "Not Found!\n" + ex.toString ());
                   //ex.printStackTrace();
          panel.add (textField);
          panel.add (button);
          panel.setPreferredSize (new Dimension (300, 40));
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          frame.setSize (300, 300);
          frame.add (editorPane, BorderLayout.CENTER);
          frame.add (panel, BorderLayout.SOUTH);
          frame.setLocationRelativeTo (null);
          frame.setVisible (true);
       public static void main (String[] args) {
          SwingUtilities.invokeLater (new Runnable () {
             public void run () {
                new SearchEditorPane ().makeUI ();
    }db

  • How to change the caret/selection color of text input controls?

    Hello JavaFX Community,
    i'm new to JavaFX. I'm using it since i saw the huge steps forward with version 2.0.
    I have the task to migrate a software from Swing to JavaFX. As a part of our corporate design, we used a special color for the caret and text selection. I couldn't find any information about changing the caret color in JavaFX 2, so i'd like to ask you and i'd be very thankful for an advise.
    There is a cross-post at StackOverflow:
    http://stackoverflow.com/questions/10057989/how-to-change-the-caret-color-in-javafx-2-0
    Thanks and best regards.

    This might be possible, but it is not trivial. You cannot do it with a standard API at this time, you will have to look into creating a skin that allows for these properties to be controlled.
    For example, the color of the caret is currently controlled in the TextFieldSkin (look for the "caretPath" property). Just forcing a color change in a subclassed skin is not so hard. Something like this:
    public class MyTextFieldSkin extends TextFieldSkin {
      public MyTextFieldSkin() {
        this.caretPath.fillProperty().unbind();
        this.caretPath.fillProperty().set(Color.RED);
    }However, it gets trickier if this color must be dynamic and if you want other things to be changed as well. It is a place to start though.
    Many of the skins methods and properties are 'protected' though, so atleast in Skin subclasses you have a lot of options to introduce new features and behaviour.

  • Invisible caret in Sun ONE Studio 5 SE - Java Editor with black background

    How to change caret color in Sun ONE Studio 5 SE - Java Editor?
    The caret blinks changing its color between black and the background color.
    I have changed the background color of the editor to black (the first thing I do whenever presented to a new editor...) But the caret changes its color between black and the background color, that is black - result: the caret becomes invisible.
    Is it possible to change the behaviour of the caret? It could blink changing its color between the background color and a color that is visible (for dark backgrounds, white; for clear backgrounds, black).

    I've found the solution myself.
    Brief description:
    Tools | Options
    Editing | Editor Settings | Java Editor
    tab Expert
    Insertion Point Color = [255,255,255]
    Overwrite Caret Color = [255,255,255]

  • When using the placholder attribute in an input field with a dark background, why can't the blinking caret be white on focus?

    Chrome and Safari both do this, making it clear to the user that they're in the field and ready to type. Currently the caret will take the color property but only once the user has started typing. This seems like it would be a worthwhile feature to bake into the next build of FF.

    I have a separate java class that gets my data and returns a Result object. Do you mean java.sql.ResultSet?
    In my main servlet I do the following:
    request.setAttribute("supporttracker",
    supporttracker.findsupporttracker(monthYear));
    and then in my JSP I can iterate through the Result
    like the following with no problems:
    <c:forEach var="supporttracker" begin="0"
    items="${supporttracker.rows}" varStatus="counter">
    My problem is that I can only iterate through this
    once in the page whereas I have no problem doing
    multiple forEach loops through other types of
    lists/collections such as an ArrayList. Right, because a ResultSet is a database cursor and doesn't act the same way that an ArrayList does. It's more like an InputStream - once you read it, you close it. If you want to re-read it, you have to re-initialize it again.
    Iterators behave that way, too. Once you walk through them, you have to re-initialize them.
    I've looked
    on the web and in a couple of books, I first thought
    it may be scope or some attribute in forEach that I
    was missing but I'm stumped. It seems like it's
    because the pointer to the result set is at the end
    of the result set when trying the second iteration,
    but I thought by using the begin="0" would put the
    pointer at the first row again, on my second
    iteration I'm getting no rows/data outputed.
    Please help and thanks in advance!The better thing to do is for your method to return a List of objects, one per row, that represent what the ResultSet returns. Have that method iterate through the ResultSet, loading the rows into the List, and close it before you leave in a finally block. A database cursor is a scarce resource, so it's a good idea to close it as soon as you can.
    %

  • How to get the location of the caret?

    Hello
    I want to get the location of the caret. Not the offset of the document.
    I have tried the Caret.getMagicCaretPosition(), but I think it gives me a point in viewport.
    How can I get the absoult location of the caret(the location on screen ,not in viewport)?
    Thank you very much.
    Best wishes

    Thankyou ,You reply seems to help me ,but I am still confused that this method returns void ,how can I get the result of the point on screen?
    When I want the caret location (the caret belongs to a JTextPane) on screen, I invoke :
    SwingUtilities.convertPointToScreen(textPane.getCaret().getMagicCaretPositon(),textPane);
    but how can I get the result of the convertion?
    Thank you!

  • FW: Caret Location Right Justified for LI when using HTMLEditorKit

    It appears that when using the HTMLEditorKit and inserting any sort of list
    item (ordered list or unordered list) into a view (while in edit mode), the
    caret is initially *---------| right justified with respect to the bullet
    image. If the identical html is loaded all at once however the caret is *-|
    left justified with respect to the bullet image. Is this a bug in
    HTMLEditorKit?

    Sure it is. In this special case IBM's JDK does a better job (at least under Linux).
    Generally I'm totally disappointed by the whole HTML package. I've been trying to implement a really primitive WYSIWIG-HTML-editor which understands <p>, <ul>, <h1> <b>, <i> and <a href>. It is a nightmare!
    - Dynamically modifying the document's structure (e.g., by making a <li> out of a <p>) works more or less, but you have absolutely no control over caret movement, and different JDK's make it differently!
    - The HTMLDocument inserts crude "extra-tags" (e.g., those <p-implied>'s. You never know exactly the structure of your document, and after a long debugging session you notice that the HTMLDocument was bluntly inserting yet another artificial element you did not specify. No docs at all what's going on.
    - It is nearly unbelievable how complicated so simple things like
    are internally modelled.
    - Frankly spoken: The whole document model sucks. Has to be harmonized with XML, DOM, JDOM, and all those nice new technologies where Java does a good job (unless you need a GUI...)
    If anybody has an idea to make it properly -> pls let me know
    thx
    Karl

  • JEditorPane: transforming between caret position in html and text/plain

    Hi all,
    I've done quite a bit of searching, and found problems similar to this one, but not this exactly, so I'll try asking it here.
    I have a JEditorPane with HTMLEditorKit, which I'm using for a WYSIWYG text editor. When the user wants to insert something, say an image, I get the caret position and insert a String into the document's underlying text.
    The problem is that if we are the WYSIWYG mode, the caret position isn't the same as the caret position in text/plaain mode.
    So if the underlying text is
    <html>
      <body>
         Some text
      </body>
    </html>the user will just see "Some text". If they place the caret between "Some" and "text", editorPane.getSelectionStart() will return '5'. But I want to insert my text at position '16' in the plain text.
    Is there a simple way to go back and forth between these two positions? Or to have getSelectionStart() to return the index relative to the text/plain mode?
    Thanks!
    Tim

    Very poor that no one answered this one.
    Did you still need the answer?
    I have 'a' answer. But not a complete one.
    In fact I only found this in search for an answer for my problem:
    http://forums.sun.com/thread.jspa?threadID=5409216&tstart=0
    Did you actually just test out what you knew so far to test what happens?
    If you were to use the HTMLEditorKit.insertHTML function, it just wants the visual caret position. So '5' would have been reasonably correct for you.
    I was doing something like this:
                   HTML.Tag tag = null;
                   Pattern p = Pattern.compile("\\s*\\<\\s*(\\w+).*", Pattern.MULTILINE|Pattern.DOTALL);
                   Matcher m = p.matcher(text);
                   if (m.matches())
                        tag = HTML.getTag(m.group(1));
                   kit.insertHTML(doc, offset,// +1
                                  text, 0,// 0
                                  0,// 0
                                  tag);
    Assuming you were inserting a tag, my code there checks what tag it is, and if that is known by the java implementation, assigns that to 'tag', so that the element is correctly inserted.
    If it is not known, we just use 'null'. Which for me wasn't such a great result.
    In fact, nothing really was a great result, as with the default java implementation being buggy (so far as I can see) it inserted to the wrong position and caused all sorts of anomalies.
    Hope you worked it out. And if you did, and have a better result than what I have, maybe you can let me know what you did!
    Sincerely,
    sean

  • How to get the component who has caret?

    I put more than one JTextField on the Panel.
    I want to get the one who owns the caret of synchronized.

    look at it
    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/KeyboardFocusManager.html#getFocusOwner()
    regards
    Aniruddha

  • Is caret positioning in right-to-left oriented jtextpane corruptable?

    Dear all -
    Below is a serious problem. I hope I can get help from you experts out there; otherwise, I think it is a bug that should be reported to the JDK developers.
    I am writing an editor using my own keyboard layout to type in Arabic. To do so, I use jTextPane, and my own implementation of DocumentFilter (where I map English keys to Arabic letters). I start by i) setting the component orientation of jTextPane to be from RIGHT_TO_LEFT, and ii) attaching a caretListener to trace the caret's position.
    The problem (I think it is a bug just like what is recorded here: http://bugs.adobe.com/jira/browse/SDK-16315):
    Initially as I type text in Arabic, there is one-to-one correspondence between where I point my mouse and where the caret displays, basically, the same place. However, a problem occurs (and can always be re-produced) when I type a word towards the end of the line, follow it by a space character, and that space character causes the word to descend to the next line as a result of a wrap-around. Now, as I point my mouse to that first line again, the location where I click the mouse and the location where the caret flashes are no longer coincident! Also, the caret progression counter is reversed! That is, if there are 5 characters on Line 1, then whereas initially the caret starts from Position 0 on the right-hand side and increases as more text is added from right to left, it is now reversed where the the caret now increases from left to right for the first line, but correctly increases from right to left in the second line! yes funny stuff and very hard to describe to.
    So, here is an example. I wrote the code below (JDK1.6_u10, on Netbeans 6.5 RC2) to make it easy to reproduce the problem. In the example, I have replaced the keys A, S, D, F and G with their Arabic corresponding letters alif, seen, daal, faa and jeem. Now, type these letters inside the double quotes (without the double quotes) including the two spaces please and watch out for the output: "asdfg asdfg ". Up until you type the last g and before you type space, all is perfect, and you should notice that the caret position correctly moves from 0 upwards in the printlines I provided. When you type that last space, the second word descends as a result of the wrap-around, and hell breaks loose! Notice that whereas the mouse and caret position are coincident on the second line, there is no way to fine-control the mouse position on the first line any more. Further, whereas adding text on the second line is intuitive (i.e., you can insert more text wherever you point your mouse, which is also where the caret would show up), for the first line, if you point the mouse any place over the written string, the caret displays in a different place, the any added text is added in the wrong place! All this because the caret counter is now reversed, which should never occur. Any ideas or fixes?
    Thank you very much for reading.
    Mohsen
    package workshop.onframes;
    import java.awt.ComponentOrientation;
    import java.awt.Rectangle;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    public class NewJFrame1 extends javax.swing.JFrame {
    public NewJFrame1() {
    initComponents();
    jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    CaretListener caretListener = new CaretListener() {
    public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot == mark) {
    try {
    Rectangle cc = jTextPane1.modelToView(dot);
    System.out.println("Caret text position: " + dot +
    ", view location (x, y): (" + cc.x + ", " + cc.y + ")");
    } catch (BadLocationException ble) {
    System.err.println("CTP: " + dot);
    } else if (dot < mark) {
    System.out.println("Selection from " + dot + " to " + mark);
    } else {
    System.out.println("Selection from " + mark + " to " + dot);
    jTextPane1.addCaretListener(caretListener);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane3 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jTextPane1.setAutoscrolls(false);
    jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextPane1KeyTyped(evt);
    jScrollPane3.setViewportView(jTextPane1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jTextPane1KeyTyped(java.awt.event.KeyEvent evt) {
    if (evt.getKeyChar() == 'a') {
    evt.setKeyChar('\u0627');
    } else if (evt.getKeyChar() == 's') {
    evt.setKeyChar('\u0633');
    } else if (evt.getKeyChar() == 'd') {
    evt.setKeyChar('\u062f');
    } else if (evt.getKeyChar() == 'f') {
    evt.setKeyChar('\u0641');
    } else if (evt.getKeyChar() == 'g') {
    evt.setKeyChar('\u062c');
    public
    static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame1().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
    }

    Hi Mohsen,
    I looked at it and indeed, I see what you describe. Sorry, but I can't shed any light. I tried to figure out what software component, or combination of components, is the cause of the problem. I see several candidates:
    1) The JTextPane
    2) The Document
    3) RTL support
    4) BIDI support
    5) Interpretation (by any other software component) of the left and right arrow key
    6) The font
    To clarify number 6: I know virtually nothing of Arabic language (apart from it being written from right to left). I remember however that the actual representation of a letter is dependent of its position between other letters: front, middle and end. What I see to my astonishment is that it seems that the rendering is also aware of this phenomenon. When you insert an A between the S and D of ASDFG, the shape of the S changes. Quite magic.
    I tried to add a second textpane with the same Document, but a different size, to see what would happen with number one if one types text in number two and vice versa.
    In my first attempt, the font that you set on textpane one was gone after I set its document to number two. For me that is very strange. The font was set to the textpane, not to the document. The separation betweem Model and View seems not very clear in this case. So I now also set that font on the second textpane.
    I will post the changed code so that you may experiment some more and hopefully will find the problem.
    You might be interested in a thread on java dot net forums that discusses a memory leak for RTL [http://forums.java.net/jive/message.jspa?messageID=300344#300344]
    Piet
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class NewJFrame1 extends JFrame {
        private static final long serialVersionUID = 1L;
        public NewJFrame1() {
         initComponents();
         // jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         this.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         CaretListener caretListener = new CaretListener() {
             public void caretUpdate(CaretEvent e) {
              int dot = e.getDot();
              int mark = e.getMark();
              if (dot == mark) {
                  try {
                   Rectangle cc = jTextPane1.modelToView(dot);
                   System.out.println("Caret text position: " + dot
                        + ", view location (x, y): (" + cc.x + ", "
                        + cc.y + ")");
                  } catch (BadLocationException ble) {
                   System.err.println("CTP: " + dot);
              } else if (dot < mark) {
                  System.out.println("Selection from " + dot + " to " + mark);
              } else {
                  System.out.println("Selection from " + mark + " to " + dot);
         jTextPane1.addCaretListener(caretListener);
        private KeyAdapter toArabic = new KeyAdapter() {
         public void keyTyped(KeyEvent evt) {
             jTextPane1KeyTyped(evt);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        // @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
         jScrollPane3 = new JScrollPane();
         jTextPane1 = new JTextPane();
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         jTextPane1.setFont(new Font("Tahoma", 0, 24)); // NOI18N
         jTextPane1.setAutoscrolls(false);
         jTextPane1.addKeyListener(toArabic);
         jScrollPane3.setViewportView(jTextPane1);
         GroupLayout layout = new GroupLayout(getContentPane());
         getContentPane().setLayout(layout);
         layout.setHorizontalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.DEFAULT_SIZE, 159,
                   Short.MAX_VALUE).addContainerGap()));
         layout.setVerticalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.PREFERRED_SIZE, 85,
                   GroupLayout.PREFERRED_SIZE).addContainerGap(
                   GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
         pack();
        }// </editor-fold>
        private void jTextPane1KeyTyped(KeyEvent evt) {
         if (evt.getKeyChar() == 'a') {
             evt.setKeyChar('\u0627');
         } else if (evt.getKeyChar() == 's') {
             evt.setKeyChar('\u0633');
         } else if (evt.getKeyChar() == 'd') {
             evt.setKeyChar('\u062f');
         } else if (evt.getKeyChar() == 'f') {
             evt.setKeyChar('\u0641');
         } else if (evt.getKeyChar() == 'g') {
             evt.setKeyChar('\u062c');
        public static void main(String args[]) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
              final NewJFrame1 frameOne = new NewJFrame1();
              frameOne.setLocationRelativeTo(null);
              frameOne.setVisible(true);
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                   Document doc = frameOne.jTextPane1.getDocument();
                   JTextPane textPane2 = new JTextPane();
                   textPane2.setFont(new Font("Tahoma", 0, 24)); // NOI18N
                   textPane2.setAutoscrolls(false);
                   textPane2.setDocument(doc);
                   textPane2.addKeyListener(frameOne.toArabic);
                   JFrame frameTwo = new JFrame();
                   frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frameTwo.add(new JScrollPane(textPane2));
                   frameTwo.setSize(400, 300);
                   frameTwo.setLocationByPlatform(true);
                   frameTwo.setVisible(true);
                   frameTwo
                        .applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        // Variables declaration - do not modify
        private JScrollPane jScrollPane3;
        private JTextPane jTextPane1;
        // End of variables declaration
    }

  • Not only NO SONG ON PAGE, but NO CARET showing!

    RE: http://web.mac.com/lorna6/iWeb/4TH%20DOWN/Eric%20.html
    PROBLEM:
    At the site above, the .mov song that I placed there about a month ago now does not play. Not only does it not play, but the caret (sideways "V") isn't even there. Usually after any kind of edit, the caret shows up on the page until I either edit out the page for the new .mov file, or do it the fast way with MassReplaceIt.
    RUN-UP TO THE PROBLEM:
    Because I edited out three of Chris' pages on my website, I had to edit out the three .js files for those pages, so I went to MassReplaceIt to do so. When I clicked the Replace button, however, the window readout of the files listed them all as "File Not Found."
    So I quit MassReplaceIt, went to my iDisk, edited the three .js files for Chris, and all was fine; the songs for those three pages played.
    However, I remembered that when I was previously in MassReplaceIt, one of the files was not correctly written. The file for Eric (manager of the rock band) was spelled Eric .js, with the space after Eric. (Why does this happen? I did not do that.)
    So I went to my iDisk, found the Eric files, including a lot of the old, incorrect Eric files with the tilde (~) preceding the file to show that it was invalid. I edited the incorrect file to read Eric.js (eliminated the space after Eric.)
    I then went to MassReplaceIt, deleted the incorrect Eric fle, hit the + button to put in the new, corrected Eric file, and thought that it would be OK.
    Then I went back to check the page in Safari for the song, and as I said, not only is there no song from his band, but neither is there the CARET!
    I cleared the cache, cleared the history, went to another site, returned to my website -- several times. Still no song on Eric's page.
    ** I realize that the MassReplaceIt issue and the No Song on Eric's Page are separate issues. I included the MassReplaceIt issue only to be complete in giving the history of this puzzle.
    Meanwhile, the band is playing in a huge contest this Saturday and I'm dropping the ball for Eric by not having the band's music on my page. (OK, I admit it is a very small, lightweight ball, more like a pingpong rather than a basketball, but it's me dropping a ball.)
    HOW CAN I GET THE SONG ONTO THE PAGE? DO I HAVE TO MAKE A NEW .MOV FILE AND PUT IT ONTO THE PAGE? OR SOMETHING EASIER?
    Lorna in Southern California

    I think your problem does revolve around the
    mysterious "Space" character in your page names.
    Here is your URL again...
    http://web.mac.com/lorna6/iWeb/4TH%20DOWN/Eric%20.html
    See on the end how there is a "%20" in
    "Eric%20.html". This indicates that you have placed
    a space after "Eric" when you typed the page name.
    Your .js file and your songfile are just fine...
    http://web.mac.com/lorna6/iWeb/4TH%20DOWN/Eric%20_file
    s/Eric.js
    http://web.mac.com/lorna6/iWeb/4TH%20DOWN/Eric%20_file
    s/Dirty%20Business.mov
    .......... Lorna says ...............................................
    James, everything is OK now, but I have a question:
    The two files directly above also have that %20% in them. So why is it wrong in the first file you mentioned, but not in these two directly above?
    The problem, though is that there is a naming
    inconsistency (with the "%20" space character). You
    have fixed the filename of the "Eric.js" file, but
    not all the other referring URLs perhaps.
    The easiest thing to do at this point is to publish
    the page again. This is going to be easy, because
    you are going to have to take the space (after
    "Eric") out anyway.
    .......... Lorna says ...............................................
    Question is: Why did this suddenly begin? Eric's page was fine before. Then suddenly, not.
    One thing I have learned thanks to your post is that I should check the Page tab for how I entered a name. Also to be very sure NOT to hit the Space bar at the end of a word if I am typing out the name of a file!
    Thanks, James. You saved Eric's day and mine.
    Lorna in Southern California

Maybe you are looking for

  • 2 computers and 1 AirTunes: How to remotely disconnect 1 to play the other?

    I am trying to decide between squeezebox duet and airport express in order to stream music from two computers to one amplifier. Obviously not at the same time. But I don't want to have to run into one room to disconnect one computer from the AirTunes

  • F4 help for custome field

    Dear All, I have created one 'Z' InfoObject for some characteristic and i am using the same in mandatory selection parameter for query also. Now this query run monthly only and accordingly data will be loaded and manipulated. So when i choose F4 for

  • Multiple JPEGs Kills Ps CS5

    This is weird, and not just a little annoying...  I have over 3,000 .jpg files to edit from a recent cross-country trip. The files were originally shot in RAW format and edited in ACR6.x in CS5, and now I wish to crop/stitch/&c. in Photoshop.  Howeve

  • Scrolling Issue on MacBook Pro

    This is a very small issue but I want people to be aware of it: Ever since updating to the latest version of iTunes, I can't scroll like I used to on my MacBook Pro's touch pad. I used to be able to type in a letter and then when I did a two finger s

  • MDT 2012 - Settings Per Task Sequence

    I recently converted to MDT 2012 after running MDT 2010 for awhile (which has been great). Johan had written up an article (http://www.deployvista.com/Home/tabid/36/EntryID/139/language/en-US/Default.aspx) that allows you to do settings per task sequ