Custom caret

Hello,
I would like to write a selection text Caret for JTextComponent. But the selected text color is not paint with :
myTextComponent.getSelectedTextColor();
In my exemple, it's ORANGE. But the selected text is always paint with black or red colors.
I would like some help ! Thanks.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.plaf.TextUI;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
@SuppressWarnings("serial")
public class ExtendedCaretSelection extends DefaultCaret {
     private Highlighter.HighlightPainter caretPainter = new CaretPainter();
     private Color defaultColor = Color.GRAY;
     public ExtendedCaretSelection() {
          super();
     @Override
     protected Highlighter.HighlightPainter getSelectionPainter() {
          return caretPainter;
     public class CaretPainter extends DefaultHighlightPainter {
          public CaretPainter() {
               super(defaultColor);
          @Override
          public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
               Rectangle alloc = bounds.getBounds();
               try {
                    // --- determine locations ---
                    TextUI mapper = c.getUI();
                    Rectangle p0 = mapper.modelToView(c, offs0);
                    Rectangle p1 = mapper.modelToView(c, offs1);
                    // --- render ---
                    Color color = c.getSelectionColor();
                    c.getSelectedTextColor();
                    if (color == null) {
                         g.setColor(defaultColor);
                    else {
                         g.setColor(color);
                    if (p0.y == p1.y) {
                         // same line, render a rectangle
                         Rectangle r = p0.union(p1);
                         g.fillRect(r.x, r.y, r.width, r.height);
                         return r;
                    else {
                         // different lines
                         alloc.width = c.getWidth();
                         int p0ToMarginWidth = alloc.x + alloc.width - p0.x;
                         g.fillRect(p0.x, p0.y, p0ToMarginWidth, p0.height);
                         if ((p0.y + p0.height) != p1.y) {
                              g.fillRect(alloc.x, p0.y + p0.height, alloc.width, p1.y
                                        - (p0.y + p0.height));
                         g.fillRect(alloc.x, p1.y, (p1.x - alloc.x), p1.height);
                         c.repaint();
                         return alloc;
               catch (BadLocationException e) {
                    // can't render
               return null;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Go2 {
     public static void main(String[] args) {
          final JFrame frame = new JFrame();
          frame.setSize(300, 300);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JTextPane editor = new JTextPane();
          ExtendedCaretSelection caret = new ExtendedCaretSelection();
          editor.setCaret(caret);
          editor.setSelectionColor(Color.YELLOW);
          editor.setSelectedTextColor(Color.ORANGE);
          frame.setContentPane(editor);
          frame.setVisible(true);
          editor.setText("\taaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " +
                 "bbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbb.\n" +
                 "ccccccccccccccccccccccccc cccccccccccccccccccccccccccccccccccc.\n" +
                 "ddddddddddddddddddddddddddd dddddddddddddd.\n" +
                 "eeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeee eeeeeeeeeeeeeee eeeeeeeeeeeeeeeeeeeee " +
                 "eeeeeeeeeeeeeeeeeeee eeeeeeeeeeeee eeeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeeeeeeeeeeeeeeee.");
               StyledDocument doc = editor.getStyledDocument();
               Style baseStyle = doc.addStyle("base", null);
             StyleConstants.setFontFamily(baseStyle, "Lucida Sans Unicode");
             StyleConstants.setFontSize(baseStyle, 18);
             StyleConstants.setLeftIndent(baseStyle, 10f);
             Style red = doc.addStyle("red", baseStyle);
             StyleConstants.setForeground(red, Color.red);
             StyleConstants.setBackground(red, Color.CYAN);
             doc.setCharacterAttributes(22, 10, red, false);
}

Seems to work ok for me using JDK1.4.2 on XP.

Similar Messages

  • Help on custom caret painting

    Hello all!
    I am developing a very custom editor (not only characters, but also drawings, etc) --
    therefore need a caret blinking somewhere text exists.
    Tried out the following code:
    * Paints only caret.
    * @param pGraphics
    * @param pLineHeight
    private void paintCaret(Graphics pGraphics, int pLineHeight) {
         final int x = getCaretX();
         final int y = getCaretY();
         if (x < 0 || y < 0) return;
         pGraphics.setXORMode(Color.BLACK);
         pGraphics.setColor(Color.WHITE);
         pGraphics.fillRect(x, y, CARET_WIDTH, pLineHeight);
    //     caretOn =! caretOn;
         }Cursor blinking is done this way:
         caretBlinkTimer.schedule(new SwingTimerTask() {
              protected void doRun() {
                   final int x = getCaretX();
                   final int y = getCaretY();
                   if (x < 0 || y < 0) return;
                   repaint(x, y, CARET_WIDTH, lineHeight);
         }, 0/*start_jetzt!*/, CARET_BLINK_RATE);The paintComponent(Graphics) code knows if to paint caret only, or more -- to save machine resources, deducing it from area of "dirty" clip rectangle to be repainted.
    Well, what's the problem?
    The problem exists. The editor backgound is somehow yellow color. When application starts and editor is shown up, I can observe the default gray color instead yellow in place of hidden-by-blinking timer caret. In the same situation, if I select another component (out of this editor), which currently paints itself using a kind of turqoise, the caret turns itself in turqoise, and hidden caret even worse, in a kind of violet (I suppose is inverse of turqoise).
    I tried a lot of "dances with flute" around problem, but it doesn't help at all... You see, Graphics has color settings only by setColor(Color) and setXORMode(Color). And, what more (I know 4 sure) the pGraphics object is a brand new one, each another time the "paintComponent(Graphics)" is invoked...
    So, please, any ideas are accepted. Helping me, you help a lot of people with similar problems.
    Thank you in advance.

    What an ungodly amount of the code for the task!
    I tried
    SELECT * FROM SCCM_GetNextServiceWindow('00811A9E08221600', 4)
    Which is said mean "Occurs the Third Monday of every 1 month(s)" and it returned 2015-03-17. Which is a Tuesday. But it is the third Tuesday.
    Turns out that I have British settings on that instance, DATEFIRST is 1. If do SET DATEFIRST 7, I get 2015-03-23. Which is a Monday, but the wrong one.
    The current setting of DATEFIRST can be detected with @@DATEFIRST, and that would make the code even more complex.
    My gut reaction would be to start over and do it all in C#, where at least I don't have to bother about SET DATEFIRST.
    Or maybe first inspect that the ScheduleToken is correct. Maybe it is, but to me that is just an incomprehensible hex string.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Caret disappears in RTL mode

    Hi
    If i set the ComponentOrientation of a JTextField to RIGHT_TO_LEFT and set its horizontal alignment to RTL and start entering some English text or numbers into it the caret suddenly disappears. How can I solve this issue? I have written a Caret myself that fixes this problem to somehow but it's far from perfect and does not paint the caret according to BIDI elements. Does anybody have a solution?
    The sample code that demonstrates the problem is given below:
    import javax.swing.*;
    import java.awt.*;
    public class MainFrame {
        public static void main(String[] args) throws Exception {       
            JFrame frame = new JFrame();
            JTextField textField = new JTextField(20);       
            textField.setHorizontalAlignment(JTextField.RIGHT);
            textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            frame.getContentPane().add(textField);
            frame.pack();
            frame.setVisible(true);
    }And here's my custom caret:
    import javax.swing.text.DefaultCaret;
    import javax.swing.text.JTextComponent;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Position;
    import javax.swing.plaf.TextUI;
    import java.awt.*;
    public class ImprovedCaret extends DefaultCaret {
        private transient Position.Bias dotBias;
        public ImprovedCaret() {
            super();
            setBlinkRate(500);
        public void install(JTextComponent c) {
            super.install(c);
            dotBias = Position.Bias.Backward;
        public void paint(Graphics g) {
            if (isVisible()) {
                JTextComponent comp   = getComponent();
                TextUI         mapper = comp.getUI();
                Rectangle      clip   = g.getClipBounds();
                Rectangle      rect   = null;
                try {
                    rect = mapper.modelToView(comp, getDot(), dotBias);
                } catch (BadLocationException ble) {
                    // should never happen
                    ble.printStackTrace();
                if (rect != null) {
                    if (rect.x >= clip.x + clip.width) {
                        rect.x = clip.x + clip.width - 1;
                    g.setColor(comp.getCaretColor());
                    g.drawLine(rect.x, rect.y,  rect.x, rect.y + rect.height - 1);
        protected synchronized void damage(Rectangle r) {
            if (r != null) {
                x     = r.x - 4;
                y     = r.y;
                width = 10;
                height = r.height;
                repaint();
    }Thanks in advance,
    Behrang S.

    I just came up with a quick and dirty trick:
    import javax.swing.text.DefaultCaret;
    import javax.swing.*;
    import java.awt.*;
    public class ImprovedCaret extends DefaultCaret {
        public ImprovedCaret() {
            super();
            setBlinkRate(((Integer) UIManager.get("TextField.caretBlinkRate")).intValue());
        public void paint(Graphics g) {
            if (isVisible()) {
                Rectangle clip   = g.getClipBounds();
                g.setClip(clip.x, clip.y, clip.width + 5, clip.height);
                super.paint(g);
                g.setClip(clip.x, clip.y, clip.width, clip.height);
    }Using this as the caret class the caret won't disappear anymore. I'm not sure but I think the one of the PlainView or the FieldView classes are bogus: they don't calculate a correct clip bound and they should start painting the characters at a smaller X (possibly current x - 5 or 4) value.
    Regards,
    Behrang S.

  • Basics of caret appearance/disappearance

    I have a jdk 1.4.2 applet consisting of several complex visual components on the form. Each visual component contains some combination of JTextField, JButton and/or JTable. I'm trying to troubleshoot a program bug where each JTextField, either standalone or as part of a visual component, is capable of displaying a blinking caret independently, meaning several blinking carets could appear on the form simultaneously, even though only field has the keyboard focus. These carets are appearing because of the applet's logic in response to a user action. This wasn't by choice or design, but that's how it came to be. I also have a case where the entire form has no blinking caret at all. My goal is to have only one blinking caret present on the form.
    I've gone through the code but so far haven't come across anything obvious. I should mention that the code is replete with all kinds of listeners (focus, action, key etc), their handlers, and some standard methods like isFocusable overriden. I'm trying to approach the issue from a different angle. The most basic answer I'm seeking is: what set of conditions must be present in order for (a) a caret to disappear at a textfield and for it appear at a different textfield (b) a caret to remain at a textfield while another caret appears at a different textfield, and (c) a caret to disappear from a textfield and not appear anywhere else?

    what set of conditions must be present in order for....Every text component has a Caret associated with it. The default behaviour is that the Caret is made non-visible when the text component loses focus. Then when the text component gains focus the Caret is made visible again.
    So there are no normal conditions that would cause the behaviour you describe. So you must have some custom code that is causing the problem. Maybe you are attempting to share the same Caret for multiple text components. Or maybe you are using a custom Caret that is not implemented correctly.

  • Caret always visible in JTextField

    The default caret is only visible if the JTextField is editable.
    I would like to have a caret in a JTextField that is visible even if the JTextField is not editable. How can I achieve this?
    Thank you.

    try textfield.setCaret(Caret c)This means to set the caret on every JTextField in the application!!!
    There should be a generic solution.
    Javadoc on JTextField
    public void setCaret(Caret c)
    says:
    Sets the caret to be used. By default this will be set by the UI that gets installed. This can be changed to a custom caret if desired. Setting the caret results in a PropertyChange event ("caret") being fired.
    How can I change the caret of the UI that gets installed?
    Thank you.

  • Extending DefaultCaret... and it won't blink!!!

    Ok so I'm making a class to extend DefaultCaret, its a custom caret to look a bit different... I've got it all working except the blinking!
    As you can see by the code below I have made calls to the 'setBlinkRate(..' function but for some reason it still won't blink!
    Anyone know what I'm doing wrong?
    the only thing i'm not sure about is the 'damage()' function call that i implemented, i suspect this may be the cause but I'm not sure...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    import javax.swing.text.*;
    public class NewCaret extends DefaultCaret {
        /** Creates a new instance of NewCaret */
        public NewCaret () {
            setBlinkRate(500);
        }//end constructor
         * When the component containing this caret gains focus this is called.
         * Here a caretlistener is added this repaints the component when the caret
         * moves and text is deleted.
        public void focusGained(FocusEvent e) {
            super.focusGained(e);
            this.getComponent().addCaretListener(new CaretListener() {
                public void caretUpdate(CaretEvent e) {
                    getComponent().repaint();
        }//end focusGained
         * When the component containing this caret loses focus this is called.
         * Here the container is repainted to removed old artifacts, and the
         * caret listners are removed as they are not needed anymore.
        public void focusLost(FocusEvent e) {
            super.focusLost(e);
            getComponent().repaint();
            CaretListener listeners[] = this.getComponent().getCaretListeners();
            for (int i = 0; i < listeners.length; i++) {
                this.getComponent().removeCaretListener(listeners);
    }//end focusLost
    * Overriding this method to display the custom cursor
    public void paint(Graphics g) {
    if (isVisible()) {
    // Determine where to draw the cursor
    JTextComponent c = getComponent();
    TextUI ui = c.getUI();
    Rectangle r = null;
    int dot = getDot();
    int mark = getMark();
    Color selectCol = javax.swing.UIManager.getLookAndFeel().getDefaults().getColor("TextField.selectionBackground");
    Font f = getComponent().getFont();
    FontMetrics currentFontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(f);
    int height = currentFontMetrics.getAscent();
    try {
    r = ui.modelToView(c, dot);
    String s = getComponent().getText().substring(dot);
    g.setColor(getComponent().getBackground());
    g.fillRect(r.x, r.y, currentFontMetrics.stringWidth(s) + 8, height + 4);
    g.setColor(c.getCaretColor());
    //top section
    g.drawLine(r.x + 0, r.y + 0, r.x + 1, r.y + 0);
    g.drawLine(r.x + 1, r.y + 1, r.x + 6, r.y + 1);
    g.drawLine(r.x + 6, r.y + 0, r.x + 7, r.y + 0);
    //middle section
    g.drawLine(r.x + 3, r.y + 2, r.x + 3, r.y + 2 + height - 1);
    g.drawLine(r.x + 4, r.y + 2, r.x + 4, r.y + 2 + height - 1);
    //bottom section
    g.drawLine(r.x + 1, r.y + 2 + height, r.x + 6, r.y + 2 + height);
    g.drawLine(r.x + 0, r.y + 3 + height, r.x + 1, r.y + 3 + height);
    g.drawLine(r.x + 6, r.y + 3 + height, r.x + 7, r.y + 3 + height);
    //color for text
    g.setColor(getComponent().getForeground());
    if (dot < c.getDocument().getLength()) {
    g.drawString(s, r.x + 8, r.y + height);
    if (mark > dot) {
    //selection - so display it.
    String substr = getComponent().getText().substring(dot, mark);
    int len = currentFontMetrics.stringWidth(substr);
    g.setColor(selectCol);
    g.fillRect(r.x + 8, r.y, len, height + 4);
    g.setColor(getComponent().getBackground());
    g.drawString(substr, r.x + 8, r.y + height);
    catch (BadLocationException ex) {
    return;
    }//end paint
    * Overriding this to destroy the current cursor
    public void damage(Rectangle r) {
    if (r != null) {
    getComponent().repaint(r.x, r.y, r.width, r.height);

    I've changed the code around with no success...
    I ended up changing the order of the drawing due to some horrible redraw problems when selecting text from the midde of a string. I've fixed those problems now,
    BUT IT STILL WON' BLINK! :(((
    I've taken your advice as to the damage method and playted with that, still no joy there though.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    import javax.swing.text.*;
    public class NewCaret extends DefaultCaret {
        private int dmgwidth;
        private boolean repainted;
        /** Creates a new instance of NewCaret */
        public NewCaret() {
            setBlinkRate(1000);
            this.dmgwidth = 0;
            this.repainted = false;
        }//end constructor
         * When the component containing this caret gains focus this is called.
         * Here a caretlistener is added this repaints the component when the caret
         * moves and text is deleted.
        public void focusGained(FocusEvent e) {
            super.focusGained(e);
            this.getComponent().addCaretListener(new CaretListener() {
                public void caretUpdate(CaretEvent e) {
                    getComponent().repaint();
        }//end focusGained
         * When the component containing this caret loses focus this is called.
         * Here the container is repainted to removed old artifacts, and the
         * caret listners are removed as they are not needed anymore.
        public void focusLost(FocusEvent e) {
            super.focusLost(e);
            getComponent().repaint();
            CaretListener listeners[] = this.getComponent().getCaretListeners();
            for (int i = 0; i < listeners.length; i++) {
                this.getComponent().removeCaretListener(listeners);
    }//end focusLost
    * Overriding this method to display the custom cursor
    public void paint(Graphics g) {
    if (isVisible()) {                       
    int dot = getDot();
    int mark = getMark();
    // Determine where to draw the cursor
    JTextComponent c = getComponent();
    TextUI ui = c.getUI();
    Rectangle r = null;
    Color selectColBG = javax.swing.UIManager.getLookAndFeel().getDefaults().getColor("TextField.selectionBackground");
    Color selectColFG = javax.swing.UIManager.getLookAndFeel().getDefaults().getColor("TextField.selectionForeground");
    Color colFG = getComponent().getForeground();
    Color colBG = getComponent().getBackground();
    Font f = getComponent().getFont();
    FontMetrics currentFontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(f);
    int height = currentFontMetrics.getAscent();
    String wholetext = getComponent().getText();
    String selString = null;
    String endString = null;
    int selwidth = 0;
    int strwidth = currentFontMetrics.stringWidth(wholetext);
    int filth = currentFontMetrics.stringWidth(wholetext.substring(dot, wholetext.length()));
    if (null != wholetext && wholetext.length() > 0) {
    if (mark > dot) {
    selString = wholetext.substring(dot, mark);
    endString = wholetext.substring(mark);
    selwidth = currentFontMetrics.stringWidth(selString);
    } else {           
    if (dot < wholetext.length()) {
    endString = wholetext.substring(dot);
    int cursorWidth = 8;
    //Here we paint
    try {               
    r = ui.modelToView(c, dot);
    g.setColor(colBG);
    g.fillRect(r.x, r.y, filth, height + 4);
    if (null != selString && selString.length() > 0) {
    g.setColor(selectColBG);
    g.fillRect(r.x + cursorWidth, r.y, selwidth, height + 4);
    g.setColor(selectColFG);
    g.drawString(selString + cursorWidth, r.x + cursorWidth, r.y + height);
    if (null != endString && endString.length() > 0) {
    g.setColor(colFG);
    g.drawString(endString, r.x + cursorWidth + selwidth, r.y + height);
    g.setColor(c.getCaretColor());
    //top section
    g.drawLine(r.x + 0, r.y + 0, r.x + 1, r.y + 0);
    g.drawLine(r.x + 1, r.y + 1, r.x + 6, r.y + 1);
    g.drawLine(r.x + 6, r.y + 0, r.x + 7, r.y + 0);
    //middle section
    g.drawLine(r.x + 3, r.y + 2, r.x + 3, r.y + 2 + height - 1);
    g.drawLine(r.x + 4, r.y + 2, r.x + 4, r.y + 2 + height - 1);
    //bottom section
    g.drawLine(r.x + 1, r.y + 2 + height, r.x + 6, r.y + 2 + height);
    g.drawLine(r.x + 0, r.y + 3 + height, r.x + 1, r.y + 3 + height);
    g.drawLine(r.x + 6, r.y + 3 + height, r.x + 7, r.y + 3 + height);
    this.dmgwidth = strwidth;
    //incrementing width value by width of cursor
    this.dmgwidth += 8;
    catch (BadLocationException ex) {
    return;
    }//end paint
    * Overriding this to destroy the current cursor
    protected synchronized void damage(Rectangle r) {
    if (r != null) {
         int x = r.x;
         int y = r.y;
         int width = dmgwidth;
         int height = r.height;
         getComponent().repaint(x, y, width, height);

  • StylePad demo - scaling it

    Hi, I'm trying to modify the Stylepad demo (located in $JAVA_HOME/demo/jfc/Stylepad) so that it works 100% with a scaled instance of Graphics2D.
    I've seen a bit of discussion around this (scaling/zooming a JTextPane/JTextComponent) - but I have yet to see a solution.
    Just overriding JTextPane's paintComponen() method and serving it a scaled Graphics2D instance opened up a box of problems :) - to which I would appreciate solution suggestions to.
    I've modified StylePad.java's createEditor() method. Here it is:
        protected JTextComponent createEditor() {
               StyleContext sc = new StyleContext();
               final DefaultStyledDocument doc = new DefaultStyledDocument();
                  initDocument(doc, sc);
              final JTextPane p = new JTextPane(doc){
                  public void paintComponent(Graphics g) {
                            Graphics2D g2d = (Graphics2D)g;
                         g2d.scale(0.5,0.5);
                         super.paintComponent(g2d);
                    p.setCaret(new ScaledCaret()); // my custom caret
                    p.addCaretListener(new CaretListener() {
                            public void caretUpdate(CaretEvent e) {
                                p.repaint();
                 MouseInputAdapter mh = new MouseInputAdapter() {
                            public void mousePressed(MouseEvent e) {
                                    p.repaint();
                           public void mouseDragged(MouseEvent e) {
                                    p.repaint();
                    p.addMouseListener(mh);
                    p.addMouseMotionListener(mh);
                    p.setDragEnabled(true);
         /* My own BasicTextPaneUI implementation, commented out for now
            ScaledTextUI sTextUI = new ScaledTextUI();
            p.setUI(sTextUI);
            return p;
        }The first problem I encountered was that the Caret position was all wrong. So, I created my own caret implementation that extends DefaultCaret. Remember that this is just test code to get it working with the scale 0.5,0.5 which I use in StylePad ..
    import javax.swing.text.DefaultCaret;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    public class ScaledCaret extends DefaultCaret {
         * Moves the caret position
         * according to the mouse pointer's current
         * location.  This effectively extends the
         * selection.  By default, this is only done
         * for mouse button 1.
         * @param e the mouse event
         * @see MouseMotionListener#mouseDragged
        public void mouseDragged(MouseEvent e) {
            MouseEvent p = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),(int)Math.round(e.getX()*2), (int)Math.round(e.getY()*2),e.getClickCount(),e.isPopupTrigger());
            super.mouseDragged(p);
         * Tries to set the position of the caret from
         * the coordinates of a mouse event, using viewToModel().
         * @param e the mouse event
        protected void positionCaret(MouseEvent e) {
            MouseEvent p = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),(int)Math.round(e.getX()*2), (int)Math.round(e.getY()*2),e.getClickCount(),e.isPopupTrigger());
            super.positionCaret(p);
    }That fixed the Caret positioning problems - but it still does not blink (once scaled the caret stops blinking).
    The problem I am working with now is the size of the component.
    If you run the StylePad demo with the above code you will experience problems with the painting of the JTextPane .. the ScrollPane obviously thinks its bigger than what it is, and around the JTextPane a lot of "rubbish" is painted.
    My next step was creating a class extending BasicTextPaneUI. I did this, overriding getMaximumSize(), getPeferredSize() and getMinimumSize() to always return a specific dimension. It did not fix the problems I described above..
    Hope someone takes an interest in this problem :)

    Hi again,
    I found out that the scaled painting should be done in the JTextPane's paintComponent method (this will affect all children). Doing them in the view's messed up things ..
    I do however still have problems. Trying to implement your code everything looks pretty messed up.. Here's my EditorKit and ViewFactory if you would be kind enough to take a look at it:
        static class MyEditorKit extends StyledEditorKit implements ViewFactory {
          * Fetches a factory that is suitable for producing
          * views of any models that are produced by this
          * kit.  The default is to have the UI produce the
          * factory, so this method has no implementation.
          * @return the view factory
            public ViewFactory getViewFactory() {
             return this;
             * Creates an uninitialized text storage model (PlainDocument)
             * that is appropriate for this type of editor.
             * @return the model
            public Document createDefaultDocument() {
                return new DefaultStyledDocument();
          * THIS IS COPIED FROM StyledEditorKit
          * Creates a view from the given structural element of a
          * document.
          * @param elem  the piece of the document to build a view of
          * @return the view
          * @see View
          public View create(Element elem) {
             String kind = elem.getName();
             if (kind != null) {
              if (kind.equals(AbstractDocument.ContentElementName)) {
                        return new MyLabelView(elem);
              } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                  return new MyParagraphView(elem);
              } else if (kind.equals(AbstractDocument.SectionElementName)) {
                  return new MyBoxView(elem, View.Y_AXIS);
              } else if (kind.equals(StyleConstants.ComponentElementName)) {
                  return new MyComponentView(elem);
              } else if (kind.equals(StyleConstants.IconElementName)) {
                  return new IconView(elem);
             // default to text display
                return new LabelView(elem);
         }Here's an example of one of the view's (MyParagraphView since that is the one that is used frequently (always?):
            static class MyParagraphView extends javax.swing.text.ParagraphView {
                public MyParagraphView(Element elem) {
                    super(elem);
                    System.out.println("new MyParagraphView()");
                 * Determines the minimum span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getMinimumSpan
                public float getMinimumSpan(int axis) {
                    float f = super.getMinimumSpan(axis);
                    System.out.print("getMinimumSpan() from super ="+f+" .. ");
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    System.out.println("new ="+f);
                    return f;
                 * Determines the maximum span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getMaximumSpan
                public float getMaximumSpan(int axis) {
                    float f = super.getMaximumSpan(axis);
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    return f;
                 * Determines the preferred span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getPreferredSpan
                public float getPreferredSpan(int axis) {
                    float f = super.getPreferredSpan(axis);
                    System.out.print("getPreferredSpan() - from super="+f+"  .. ");
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    System.out.println("new="+f);
                    return f;
                 * Provides a mapping from the document model coordinate space
                 * to the coordinate space of the view mapped to it.  This makes
                 * sure the allocation is valid before calling the superclass.
                 * @param pos the position to convert >= 0
                 * @param a the allocated region to render into
                 * @return the bounding box of the given position
                 * @exception BadLocationException  if the given position does
                 *  not represent a valid location in the associated document
                 * @see View#modelToView
                public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
                    Rectangle r = (Rectangle)super.modelToView(pos, a, b);
                    r.x *= StylePadConstants.X_SCALE_FACTOR;
                    r.y *= StylePadConstants.Y_SCALE_FACTOR;
                    r.width *= StylePadConstants.X_SCALE_FACTOR;
                    r.height *= StylePadConstants.Y_SCALE_FACTOR;
                    return r;
                 * Provides a mapping from the view coordinate space to the logical
                 * coordinate space of the model.
                 * @param x   x coordinate of the view location to convert >= 0
                 * @param y   y coordinate of the view location to convert >= 0
                 * @param a the allocated region to render into
                 * @return the location within the model that best represents the
                 *  given point in the view >= 0
                 * @see View#viewToModel
                public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
                    float newx = (float)(x*StylePadConstants.X_SCALE_FACTOR);
                    float newy = (float)(y*StylePadConstants.Y_SCALE_FACTOR);
                    Rectangle r = a.getBounds();
                    r.x *= StylePadConstants.X_SCALE_FACTOR;
                    r.y *= StylePadConstants.Y_SCALE_FACTOR;
                    r.width *= StylePadConstants.X_SCALE_FACTOR;
                    r.height *= StylePadConstants.Y_SCALE_FACTOR;
                    int i = super.viewToModel(newx, newy, r, bias);
                    return i;
            }What happens is that text elements are displayed on top of other text elements etc.
    All the other views (MyBoxView etc.) contains the same code as the one above. I copied the create() method from StyledEditorKit's ViewFactory.
    StylePadConstants merely contains the x/y scale factor.
    Best regards,
    Bjorn

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

  • In need of customized JTextField

    I need to create a custom textfield, and the formatter won't cut it. I need to have formatting applied real time, with a variable number of characters. The ATM might be a good example, where you enter numbers and the display field fills in from left to right, with the decimal point and dollar sign always being in the correct location, the entry of a decimal point is optional, and comas appear as necessary as the number of digits to the left of the decimal point increases.
    I have similar needs for percentage, and a few other value types. Currently I've extended PlainDocument and have it working, but I'm far from happy with the results, and wasn't able to make it abstract enough to be easily usable for slightly different formats.
    Has anybody seen a component like this floating around? I would hate to recreate what somebody else has already done, particularly of the later effort has resulted in a better solution.
    Thanks,
    -Dave

    does it have to be a textField?Yes - the users are quite adamant and and specific regarding the requirements for this field.
    At first glance, your single replaceAll statement looks much simpler than what I've worked out. I think that some of the extra leg work I'm doing may not be necessary, but I do need to figure out where to insert numbers (in case of entry mid field), where deletions occur, where to place the character after updates, etc.
    I'm posted what I've come up with below. I'm not happy with it - am still looking for the right solution, which I must have glossed right over.
    import java.awt.GridLayout;
    import java.awt.Toolkit;
    import java.text.NumberFormat;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.PlainDocument;
    public class TestTextField {
         public static void main(String[] args) {
              JTextField myTextField = new JTextField();
              myTextField.setHorizontalAlignment(JTextField.RIGHT);
              myTextField.setDocument(new UpperCaseDocument(myTextField));
              JFrame frame = new JFrame();
              frame.getContentPane().setLayout(new GridLayout(3, 1));
              frame.getContentPane().add(myTextField);
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setVisible(true);
    class UpperCaseDocument extends PlainDocument{
         StringBuffer contents;
         JTextField tf;
         public UpperCaseDocument(JTextField tf) {
              this.tf = tf;
              contents = new StringBuffer();
              contents.append("000");
              try {
                   super.insertString(0, NumberFormat.getCurrencyInstance().format(0),
                             null);
              } catch (BadLocationException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void insertString(int offs, String str, AttributeSet a)
                   throws BadLocationException {
              if (str == null) {
                   return;
              boolean allNumbers = isNumeric(str);
              if (allNumbers) {
                   int offset = calcOffset(offs);
                   contents.insert(offset, str);
                   padContents();
                   set(a);
                   int caret = calcCaret(offset + str.length());
                   System.out.println("C: " + caret);
                   tf.setCaretPosition(caret);
              } else {
                   Toolkit.getDefaultToolkit().beep();
         public void remove(int offs, int len) throws BadLocationException {
              super.remove(offs, len);
              String s = getText(0, getLength());
              s = replace(s, "$", "", -1);
              s = replace(s, ",", "", -1);
              s = replace(s, ".", "", -1);
              contents.replace(0, contents.length(), s);
              set(null);
              padContents();
              tf.setCaretPosition(offs);
         private void set(AttributeSet a) {
              try {
                   String s1 = contents.substring(0, contents.length() - 2);
                   String s2 = contents.substring(contents.length() - 2);
                   String amount = s1 + "." + s2;
                   double d = Double.parseDouble(amount);
                   String curr = NumberFormat.getCurrencyInstance().format(d);
                   super.remove(0, getLength());
                   super.insertString(0, curr, a);
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public static String replace(String text, String repl, String with, int max) {
              if (text == null || with == null || max == 0) {
                   return text;
              StringBuffer buf = new StringBuffer(text.length());
              int start = 0, end = 0;
              while ((end = text.indexOf(repl, start)) != -1) {
                   buf.append(text.substring(start, end)).append(with);
                   start = end + repl.length();
                   if (--max == 0) {
                        break;
              buf.append(text.substring(start));
              return buf.toString();
         private int calcOffset(int offset) {
              // Take 1 off the top to accomodate for dollar sign
              if (offset > 0) {
                   offset--;
              int numCommas = (contents.length() - 2) / 3;
              if (numCommas > 0 && (contents.length() - 2) % 3 == 0) {
                   numCommas--;
              int prefix = (contents.length() - 2) % 3;
              if (prefix == 0) {
                   prefix = 3;
              int commaShift = 0;
              for (int i = numCommas; i > 0; i--) {
                   if (offset > prefix) {
                        commaShift++;
                        prefix += 4;
                   } else {
                        break;
              offset -= commaShift;
              int secret = contents.length() + 1 - 2;
              if (offset > secret) {
                   offset--;
              return offset;
         private int calcCaret(int offset) {
              if (offset > contents.length()) {
                   System.out.println("oops");
                   return getLength();
              // Take 1 off the top to accomodate for dollar sign
              if (offset > 0) {
                   offset++;
              int numCommas = (contents.length() - 2) / 3;
              if (numCommas > 0 && (contents.length() - 2) % 3 == 0) {
                   numCommas--;
              int prefix = (contents.length() - 2) % 3;
              if (prefix == 0) {
                   prefix = 3;
              int commaShift = 0;
              for (int i = numCommas; i > 0; i--) {
                   if (offset > prefix) {
                        commaShift++;
                        prefix += 3;
                   } else {
                        break;
              offset += commaShift;
              int secret = getLength() - 2;
              if (offset > secret) {
                   offset++;
              return offset;
         private void padContents() {
              if (contents.length() < 3) {
                   int pading = 3 - contents.length();
                   for (int i = 0; i < pading; i++) {
                        contents.insert(0, "0");
              } else {
                   int excess = contents.length() - 3;
                   for (int i = 0; i < excess; i++) {
                        if (contents.charAt(0) == '0') {
                             contents.deleteCharAt(0);
                        } else {
                             break;
         public static boolean isNumeric(String str) {
              if (str == null) {
                   return false;
              int sz = str.length();
              for (int i = 0; i < sz; i++) {
                   if (Character.isDigit(str.charAt(i)) == false) {
                        return false;
              return true;
    }

  • JTable & custom cell editor

    Hello everyone,
    what is the correct way of writing a custom cell editor for a JTable? I followed the example in the Java tutorial ([How to use tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editor]), but the result is a bit weird. The code I have is the following:
        private class NumericCellEditor extends AbstractCellEditor implements TableCellEditor {
            NumericFTField field = new NumericFTField(threeDecimalsFormat, 3, null, 1);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int col) {
                field.setValue(value);
                return field;
            public Object getCellEditorValue() {
                return field.getValue();
            @Override
            public boolean stopCellEditing() {
                if (((NumericFTField)field).verifyDouble()) {
                    field.setBorder(new EmptyBorder(0, 0, 0, 0));
                    fireEditingStopped();
                    return true;
                } else {
                    field.setBorder(BorderFactory.createLineBorder(Color.red));
                    return false;
        }where the NumericFTField is a class derived from JFormattedTextField that only allows digits, decimal separator, minus and 'E' to be inserted, and it monitors clipboard operations. verifyDouble() is a method of the NumericFTField class that verifies whether the current input can be parsed to a double and whether it satisfies everything it should. This is then used in
    ((TableColumn)jTblSpecs.getColumnModel().getColumn(1)).setCellEditor(new NumericCellEditor());The NumericFTField class works great, I use it also in place of a JTextFields, so I'd say there is nothing wrong with it.
    After I click in a cell (single click), it behaves a little different that the default cell editor: the cell is not highlighted, but it immediately jumps to the editing state (why???). I, indeed, can insert the allowed characters only. When I click in a cell, do some editing and press Enter, the cell's content gets validated. If it is invalid, stopCellEditing() method does its magic; if it is valid, the caret disappears and everything SEEMS okay. However, if I started typing at this point, the cell reverts to the editing state, but now I am able to enter any character I want. It truly looks like the cell editor is now some other component, not the original NumericFTField one. What is going on here?
    It would be great is someone could provide a short schematic source of a custom cell editor class that would work exactly as the JTable's default one except it would only permit digits and so on. It doesn't have to be anything fancy, just a "skeleton" of the class with comments like "input verification here" etc.
    I am sorry for any lack of clarity, but I am still a Java newbie.
    Any help would be much appreciated.
    Best regards,
    vt

    Hi,
    I am also facing the same problem. In addition to what you have specified, my requirement is to be able to select multiple rows for deletion. But, the very first row selected using mouse is not visible as selected though its selected. The other rows are visible as selected.
    If you can use any JDK version, start using JDK1.6. You will not be facing this problem. There were so many changes done for swings from JDK 1.4 to 1.6. But, I have to strictly use JDK1.4, but could not find any workaround for this problem.
    It would be great if anyone can help me out in this issue to get workaround for this problem.

  • ParagraphView and disappearing caret

    Hi!
    I am currently working on a EditorKit to make a custom editor. I extended AbstractDocument and created a custom Element structure that is not based on the abstract elements provided by AbstractDocument. Currently I have three type of elements: Chapter, Paragraph and Text. The Chapter is the root of the element structure and there is only one Chapter element in a document. The chapter contains Paragraphs, and Paragraphs contain text elements. Text elements except the last ones in a Paragraph do not contain endlines. So basically a Paragraph is a line of text with different styled chunks that are stored in the Text elements.
    My viewfactory basically does this:
              if (elem instanceof TextElement) {
                   return new LabelView(elem);
              if (elem instanceof ParagraphElement) {
                   return new ParagraphView(elem);
              if (elem instanceof ChapterElement) {
                   return new BoxView(elem, View.Y_AXIS);
    The problem is that when I want to move around with my caret it disappears when I reach the end of the line instead of appearing at the beginning of the next line. On top of that, it throws the following exception:
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
         at javax.swing.text.CompositeView.getView(CompositeView.java:143)
         at javax.swing.text.Utilities.getNextVisualPositionFrom(Utilities.java:985)
         at javax.swing.text.CompositeView.getNextEastWestVisualPositionFrom(CompositeView.java:732)
         at javax.swing.text.CompositeView.getNextVisualPositionFrom(CompositeView.java:454)
         at javax.swing.text.Utilities.getNextVisualPositionFrom(Utilities.java:987)
         at javax.swing.text.CompositeView.getNextEastWestVisualPositionFrom(CompositeView.java:732)
         at javax.swing.text.CompositeView.getNextVisualPositionFrom(CompositeView.java:454)
         at javax.swing.plaf.basic.BasicTextUI$RootView.getNextVisualPositionFrom(BasicTextUI.java:1568)
         at javax.swing.plaf.basic.BasicTextUI.getNextVisualPositionFrom(BasicTextUI.java:1115)
         at javax.swing.text.DefaultEditorKit$NextVisualPositionAction.actionPerformed(DefaultEditorKit.java:1666)
         at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1636)
         at javax.swing.JComponent.processKeyBinding(JComponent.java:2849)
         at javax.swing.JComponent.processKeyBindings(JComponent.java:2884)
         at javax.swing.JComponent.processKeyEvent(JComponent.java:2812)
         at java.awt.Component.processEvent(Component.java:5911)
         at java.awt.Container.processEvent(Container.java:2023)
         at java.awt.Component.dispatchEventImpl(Component.java:4501)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
         at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:704)
         at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:969)
         at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:841)
         at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:668)
         at java.awt.Component.dispatchEventImpl(Component.java:4373)
         at java.awt.Container.dispatchEventImpl(Container.java:2081)
         at java.awt.Window.dispatchEventImpl(Window.java:2458)
         at java.awt.Component.dispatchEvent(Component.java:4331)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Originally I had Paragraphs as the leaf elements containing the text (no Text elements), and I used the ParagraphView without LabelViews. The exact same was the problem.
    Do you have an idea what goes wrong?

    I didn't extend SUN classes because I expected them to work "out of the box". I use javax.swing.text.ParagraphView directly. It is not abstract so I expected it to work without overriding anything. In my ViewFactory I simply instantiate it:
    if (elem instanceof TextElement) {
      return new LabelView(elem);
    if (elem instanceof ParagraphElement) {
      return new ParagraphView(elem);
    if (elem instanceof ChapterElement) {
      return new BoxView(elem, View.Y_AXIS);
    }I do not have custom View classes, I use the ones that are provided in the package javax.swing.text. I only have a custom Document class derived from AbstractDocument, and custom Elements that are directly implementing the Element interface.
    I am trying to achieve to have a custom document model that is a bit more structured than DefaultStyledDocument.
    Currently my document model is very simple. It has a single chapter element as root which has paragraphs and the paragraphs contain text chunks (so text inside paragraphs could have different styles and semantics).
    Is ParagraphView expecting a specific Document model and will not work with other Document models? If so, then how could I display the paragraphs of my document model (ParagraphElements) so they look like paragraphs (line wrapping, indents etc.)?

  • My custom keyBoard problem

    Hi all,
    I want to develope a custom keyboard worked as MS screen keyboard.
    It will used for machine who have not hard keyboard but own a screen toucher.
    I add a MouseListener to every button of the keyboard, and transfer Robot.keypressed(VK_*) in the mousepressed method.
    The problem is it seems that can only work for the component(JTextField, for example) on the app.
    I mean it can work for any thing who will be edited.
    How can I input text as MS screen keyboard: you press the caret in anywhere you will input, then move your mouse to the keyboard press the key you like.
    thanks

    The problem is you can't input your "A,B,C" to something like notepad, word, or vi(Linux), etc.aha, I see what you're trying to do now.
    OK, the code below is not a hack, it's just plain crap, but a bit of fun anyway.
    open notepad, or word, run the program and have it so both windows are showing
    i.e. word is not maximized etc.
    click into notepad/word to give it focus (cursor blinking away), then click A B or C
    like I said before, the code is just plain crap.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      JFrame f;
      Robot robot;
      KeyboardButton[] keys = new KeyboardButton[3];
      public void buildGUI()
        try{robot = new Robot();}catch(Exception e){}
        JPanel keyboardPanel = new JPanel(new GridLayout(1,3));
        for(int x = 0; x < keys.length; x++)
          keys[x] = new KeyboardButton(""+(char)(x+65));
          keyboardPanel.add(keys[x]);
        f = new JFrame();
        f.setFocusable(false);
        f.getContentPane().add(keyboardPanel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      class KeyboardButton extends JButton
        public KeyboardButton(final String letter)
          super(letter);
          setPreferredSize(new Dimension(50,50));
          addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ae){
              if(robot != null)
                java.awt.datatransfer.StringSelection ss = new java.awt.datatransfer.StringSelection(letter);
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
                f.setVisible(false);
                robot.delay(150);//<--------------may need to increase, depending on pc speed
                robot.keyPress(KeyEvent.VK_CONTROL);
                robot.keyPress(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_V);
                robot.keyRelease(KeyEvent.VK_CONTROL);
                f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • JTextPane and caret

    Hi,
    does anyone know if I can get an intention of moving caret before it actually moves? If I add caret listener, I get the event but the caret has been already moved, so it does not satisfy me.
    Regards

    camickr wrote:
    What is your problem and what is your requirement. If we know this maybe we can suggest an alternative solution.Exactly. There's no direct support for what you want to do, but there could very well be an alternative solution.
    Otherwise I would suggest that you need to write a custom Action for the arrow keys to replace the existing Action.True, but changing the actions for the arrow keys won't handle mouse input (i.e. if the user uses the mouse to make a selection).
    Off the top, I'd say you could subclass DefaultCaret, and override setDot() and moveDot() so they fire a special event you create and define. In order for that to work though, you'd have to do some testing and make sure that one of those two methods is the only way the caret ever changes location (i.e., there isn't some internal, private method in DefaultCaret that bypasses setDot() and moveDot()).

  • Custom purchase requsitionto vendor open and cleared payment report

    dear all i develop report but i cant ableto show in that open amount and cleared amount of vender in that report so please see this report and feedback me for logic to show open and clear amount of vendor purchase orderwise or vendorwise
    report zpo_purchase_history no standard page heading message-id 00.
    TABLES : bsik, bsak, lfa1, lfb1, skb1, t001, bapifvdexp_vzzbepp.
    type-pools:slis,ICON.
    types :begin of ty_po,
            banfn type eban-banfn,
            "Purchase Requisition Number
            bnfpo type eban-bnfpo,
            "Item Number of Purchase Requisition
            ekgrp type eban-ekgrp,                 "Purchasing Group
            badat type eban-badat,
            "Requisition (Request) Date
            menge type eban-menge,
            KNTTP TYPE EBAN-KNTTP,
             PSTYP type eban-PSTYP,
            "Purchase Requisition Quantity
            meins type eban-meins,
            "Purchase Requisition Unit of Measure
            lifnr type ekko-lifnr,                 "Vendor Account Number
            bedat type ekko-bedat,                 "Purchasing Document Date
            ebeln type ekpo-ebeln,
            "Purchasing Document Number
            ebelp type ekpo-ebelp,
            "Item Number of Purchasing Document
            matkl type ekpo-matkl,                 "Material Group
            mtart type ekpo-mtart,                 "Material Type
            matnr type ekpo-matnr,                 "Material Number
            txz01 type ekpo-txz01,                 "Short Text
            menge1 type ekpo-menge,                "Purchase Order Quantity
            meins1 type ekpo-meins,
            "Purchase Order Unit of Measure
            balqty type ekpo-menge,                "Balance Quantity
            netpr type ekpo-netpr,
            "Net Price in Purchasing Document
            peinh type ekpo-peinh,                 "Price Unit
            mblnr type mseg-mblnr,
            "Number of Material Document
            zeile type mseg-zeile,                 "Item in Material Document
            menge2 type mseg-menge,                "GR Quantity
            meins2 type mseg-meins,                "GR Unit of Measure
            werks type mseg-werks,                 "Plant
            charg type mseg-charg,                 "Batch
            belnr type rbkp-belnr,
            "Document Number of an Invoice Document
            bldat type ekbe-bldat,                 "Document Date in Document
            belnr_b type rbkp-belnr,
            SHKZG type ekbe-SHKZG ,                "Debit/Credit Indicator
            DMBTR type   bsik-dmbtr,                "Amount in Local Currency
            DMBTR_C type   bsAk-dmbtr,                "Amount in Local Currency
            thick(10) type c,                      "Thickness
            width(10) type c,                      "Width
            length(10) type c,                     "Length
            grade(10) type c,                        "Grade
            BELNR_d type bseg-belnr,
            xblnr type bkpf-xblnr,
            awkey  type bkpf-awkey,
            RMWWR type rbkp-RMWWR,
            WMWST1 type rbkp-WMWST1,
            end of ty_po.
    types :begin of ty_ekko,
            ebeln type ekko-ebeln,
            lifnr type ekko-lifnr,
            bedat type ekko-bedat,
            end of ty_ekko.
    types:begin of ty_ekpo,
            ebeln type ekpo-ebeln,
            ebelp type ekpo-ebelp,
            matnr type ekpo-matnr,
            txz01 type ekpo-txz01,
            menge type ekpo-menge,
            meins type ekpo-meins,
            netpr type ekpo-netpr,
            peinh type ekpo-peinh,
            banfn type ekpo-banfn,
            bnfpo type ekpo-bnfpo,
            mtart type ekpo-mtart,
            end of ty_ekpo.
    types :begin of ty_eban,
            banfn type eban-banfn,
            bnfpo type eban-bnfpo,
            matnr type eban-matnr,
            menge type eban-menge,
            meins type eban-meins,
            end of ty_eban.
    types : begin of ty_ekbe,
             ebeln type ekbe-ebeln,
             ebelp type ekbe-ebelp,
             belnr type ekbe-belnr,
             bldat type ekbe-bldat,
             gjahr type ekbe-gjahr,
             buzei type ekbe-buzei,
             matnr type ekbe-matnr,
             DMBTR type ekbe-dmbtr,
             shkzg type ekbe-shkzg,
             end of ty_ekbe.
    types : begin of ty_mseg,
             mblnr type mseg-mblnr,
             mjahr type mseg-mjahr,
             zeile type mseg-zeile,
             menge type mseg-menge,
             meins type mseg-meins,
             ebeln type mseg-ebeln,
             ebelp type mseg-ebelp,
             matnr type mseg-matnr,
             werks type mseg-werks,
             charg type mseg-charg,
             end of ty_mseg.
    types : begin of ty_rbkp,
             belnr type rbkp-belnr,
             gjahr type rbkp-gjahr,
             bldat type rbkp-bldat,
             lifnr type rbkp-lifnr,
             ZUONR type rbkp-ZUONR,
             RMWWR type rbkp-RMWWR,
             WMWST1 type rbkp-WMWST1,
             end of ty_rbkp.
    types : begin of ty_bseg,
             bukrs type bseg-bukrs,
             belnr type bseg-belnr,
             gjahr type bseg-gjahr,
             buzei type bseg-buzei,
             valut type bseg-valut,
             wrbtr type bseg-wrbtr ,
             augbl type bseg-augbl,
             matnr type bseg-matnr,
             lifnr type bseg-lifnr,
             ebeln type bseg-ebeln,
             end of ty_bseg.
    types : begin of ty_rseg,
             belnr type rseg-belnr,
             gjahr type rseg-gjahr,
             ebeln type rseg-ebeln,
             ebelp type rseg-ebelp,
             matnr type rseg-matnr,
             bukrs type rseg-bukrs,
             end of ty_rseg.
    types : begin of ty_bsik,
             belnr type bsik-belnr,
              buzei type bsik-buzei,
             DMBTR type bsik-DMBTR,
             budat type bsik-budat,
             shkzg type bsik-shkzg,
             ebeln type bsik-ebeln,
             lifnr type bsik-lifnr,
             end of ty_bsik.
    types : begin of ty_bsak,
             belnr type bsak-belnr,
       lifnr type bsak-lifnr,
        ebeln type bsak-ebeln,
             DMBTR_C type bsak-DMBTR,
    ZUONR type bsak-ZUONR,
             end of ty_bsak.
    types: begin of ty_bkpf,
             BELNR type bkpf-belnr,
             xblnr type bkpf-xblnr,
             awkey  type bkpf-awkey,
           end of ty_bkpf.
    data: it_po type standard table of ty_po,
           it_ekko type standard table of ty_ekko,
           it_ekpo type standard table of ty_ekpo,
           it_eban type standard table of ty_eban,
           it_ekbe type standard table of ty_ekbe,
           it_mseg type standard table of ty_mseg,
           it_rbkp type standard table of ty_rbkp,
           it_rseg type standard table of ty_rseg,
           it_bseg type standard table of ty_bseg,
           it_bsik type STANDARD TABLE OF ty_bsik with header line,
           it_bsak type STANDARD TABLE OF ty_bsak,
           it_bkpf type standard table of ty_bkpf,
           wa_po type ty_po,
           wa_ekko type ty_ekko,
           wa_ekpo type ty_ekpo,
           wa_eban type ty_eban,
           wa_mseg type ty_mseg,
           wa_rbkp type ty_rbkp,
           wa_rseg type ty_rseg,
           wa_bseg type ty_bseg,
           wa_ekbe type ty_ekbe,
           wa_bsik type ty_bsik,
           wa_bsak type ty_bsak,
           wa_bkpf type ty_bkpf.
    data: it_fcat type slis_t_fieldcat_alv,
           it_lshead type slis_t_listheader,
           it_sort type slis_t_sortinfo_alv,
           wa_fcat type slis_fieldcat_alv,
           wa_lshead type slis_listheader,
           wa_layout type slis_layout_alv,
           wa_sort type slis_sortinfo_alv.
    data :it_cl_data like table of clobjdat,
           wa_cl_data like clobjdat.
    data: values(10) type n.
    data: value1(4) type N.
    data: c_matkl type ekpo-matkl,
           c_matnr type ekpo-matnr,
           c_ekgrp type eban-ekgrp,
           c_badat type eban-badat,
           c_index type sy-tabix,
           c_grmenge type mseg-erfmg,
           c_low(10) type c,
           c_high(10) type c,
           c_date type string,
           c_bukrs type ekko-bukrs,
           c_WERKS type eban-WERKS.
    data: gd_date(10).
    DATA: V_EVENTS TYPE SLIS_T_EVENT,
           WA_EVENT TYPE SLIS_ALV_EVENT.
    *********Selection screen variables*********
    selection-screen:begin of block b1 with frame title text-001.
    select-options: s_bukrs for c_bukrs DEFAULT  'bmp1',
                     s_WERKS for c_WERKS,
                     s_matnr for c_matnr DEFAULT 'rm-01',
                     s_matkl for c_matkl ,
                     s_badat for c_badat ,"obligatory,
                     s_ekgrp for c_ekgrp.
    parameters: ch_bal as checkbox.
    selection-screen:end of block b1.
    *initialization.
    * PERFORM EVENT_CALL.
    *  PERFORM POPULATE_EVENT.
    start-of-selection.
         PERFORM EVENT_CALL.
       PERFORM POPULATE_EVENT.
       perform getdata.
       perform setdata.
       perform fieldcat.
       perform display.
    *&      Form  GETDATA
    form getdata .
       select a~BANFN
              a~bnfpo
              a~ekgrp
              a~badat
              a~KNTTP
              a~PSTYP
              b~ebeln
              b~ebelp
              b~matkl
              b~matnr
              b~bukrs
              into corresponding fields of table it_po
              from eban as a inner join ekpo as b
              on a~banfn = b~banfn and
                 a~bnfpo = b~bnfpo AND
                 A~KNTTP = B~KNTTP and
                 a~PSTYP = b~PSTYP
              where  a~badat in s_badat and
                     a~ekgrp in s_ekgrp and
                     a~WERKS in s_WERKS and
                     b~matnr in s_matnr and
                     b~matkl in s_matkl and
                     b~bukrs in s_bukrs and
                     b~loekz <> 'L' and
                     a~loekz <> 'X'.
       if it_po[] is not initial.
         select ebeln
                ebelp
                matnr
                txz01
                menge
                meins
                netpr
                peinh
                banfn
                bnfpo
                mtart
                from ekpo into table it_ekpo
                for all entries in it_po
                where ebeln = it_po-ebeln and
                      ebelp = it_po-ebelp and
                      loekz <> 'L'.
         select banfn
                bnfpo
                matnr
                menge
                meins
                from eban into table it_eban
                for all entries in it_po
                where banfn = it_po-banfn and
                      bnfpo = it_po-bnfpo and
                      loekz <> 'X'.
         if it_ekpo[] is not initial.
           select ebeln
                  lifnr
                  bedat
                  from ekko into table it_ekko
                  for all entries in it_ekpo
                  where ebeln = it_ekpo-ebeln.
           select ebeln
                  ebelp
                  belnr
                  bldat
                  gjahr
                  buzei
                  matnr
                  DMBTR
                  shkzg
                  from ekbe into table it_ekbe
                  for all entries in it_ekpo
                  where ebeln = it_ekpo-ebeln and
                        ebelp = it_ekpo-ebelp .
    *if it_ekbe-shkzg = 'H'.
    **ekbe-dmbtr = ekbe-dmbtr * -1.
    **ekbe-menge = ekbe-menge * -1.
    *endif.
    * select belnr
    *             gjahr
    *             ebeln
    *             ebelp
    *     from bseg into table it_bseg
    *             for all entries in it_ekpo
    *             where ebeln = it_ekpo-ebeln and
    *                   ebelp = it_ekpo-ebelp.
           select belnr
                  gjahr
                  ebeln
                  ebelp
                  matnr
                  bukrs
                  from rseg into table it_rseg
                  for all entries in it_ekpo
                  where ebeln = it_ekpo-ebeln and
                        ebelp = it_ekpo-ebelp.
         endif.
         if it_ekbe[] is not initial.
           select mblnr
                  mjahr
                  zeile
                  menge
                  meins
                  ebeln
                  ebelp
                  matnr
                  werks
                  charg
                  from mseg into table it_mseg
                  for all entries in it_ekbe
                  where mblnr = it_ekbe-belnr and
                        mjahr = it_ekbe-gjahr and
                        zeile = it_ekbe-buzei and
                        bwart = '101'.
         endif.
         if it_rseg[] is not initial.
           select belnr
                  gjahr
                  bldat
                  lifnr
                  ZUONR
                  RMWWR
                  WMWST1
                  from rbkp into table it_rbkp
                  for all entries in it_rseg
                  where belnr = it_rseg-belnr.
         endif.
    *if it_rseg[] is not initial.
    *      SELECT bukrs
    *              belnr
    *              gjahr
    *              buzei
    *              valut
    *              wrbtr
    *              augbl
    *              matnr
    *              lifnr
    *              ebeln
    *        INTO TABLE it_bseg
    *          FROM bseg
    *          FOR ALL ENTRIES IN it_rseg
    *          WHERE bukrs = it_rseg-bukrs and ebeln = it_rseg-ebeln and mwskz = ''.
    *endif.
    *loop at it_BKPF into wa_BKPF.
    *  values = wa_rbkp-belnr.
    *  value1 = wa_rbkp-gjahr.
       data: aekey_1 type string .
    *CONCATENATE values value1 into aekey_1.
    *  if it_BSEG[] is not initial.
    *MESSAGE aekey_1 type 'I'.
           SELECT single belnr xblnr awkey into wa_bkpf
             from bkpf
             where awkey = aekey_1.
    SELECT SINGLe belnr
    buzei
    dmbtr
    budat
       shkzg
       ebeln
       lifnr
       FROM bsik
    INTO CORRESPONDING FIELDS OF  wa_bsik
    *FOR ALL ENTRIES IN it_bseg
    WHERE
        bukrs in s_bukrs and
        lifnr = wa_rbkp-lifnr
    and
    *AND gjahr = it_bseg-gjahr
    * AND
        belnr = wa_bkpf-belnr.
    insert wa_bsik into table it_bsik.
    CLEAR wa_bsik.
    CLEAR it_bsik.
    *endloop.
    * and ebeln = it_bseg-ebeln .
    *    select BELNR
    **           SHKZG
    **           DMBTR
    *           from bkpf into table it_bkpf
    *            for ALL ENTRIES IN it_rbkp
    *            where belnr = it_rbkp-belnr.
    *        ENDif.
    IF IT_bseg[] IS NOT INITIAL.
           select belnr
             LIFNR
             ebeln
                  DMBTR
              ZUONR
                  from bsik into table it_bsik
                  for all entries in it_bseg
                  where belnr = it_bseg-belnr.
           select belnr
             LIFNR
             ebeln
                  DMBTR
              ZUONR
                  from bsak into table it_bsak
                  for all entries in it_bseg
                  where belnr = it_bseg-belnr.
    ENDIF.
       else.
         message s002.
         leave list-processing.
       endif.
    endform.                    " GETDATA
    *&      Form  SETDATA
    form setdata .
       clear wa_po.
       loop at it_po into wa_po.
         c_index = sy-tabix.
    ********Calculate PR Quantity**********
         clear wa_eban.
         read table it_eban into wa_eban
                    with key banfn = wa_po-banfn
                             bnfpo = wa_po-bnfpo.
         if sy-subrc eq 0.
           move:wa_eban-menge to wa_po-menge,
                wa_eban-meins to wa_po-meins.
         endif.
    ********Calculate PO Quantity**********
         clear wa_ekpo.
         read table it_ekpo into wa_ekpo
                    with key banfn = wa_po-banfn
                             bnfpo = wa_po-bnfpo .
         if sy-subrc eq 0.
           move:wa_ekpo-txz01 to wa_po-txz01,
                wa_ekpo-netpr to wa_po-netpr,
                wa_ekpo-peinh to wa_po-peinh,
                wa_ekpo-mtart to wa_po-mtart,
                wa_ekpo-menge to wa_po-menge1,
                wa_ekpo-meins to wa_po-meins1.
         endif.
    ********Calculate Balance Quantity******
         clear wa_mseg.
         loop at it_mseg into wa_mseg
                where ebeln = wa_po-ebeln and
                      ebelp = wa_po-ebelp.
           c_grmenge = c_grmenge + wa_mseg-menge.
         endloop.
         move:wa_mseg-mblnr to wa_po-mblnr,
              c_grmenge to wa_po-menge2,
              wa_mseg-meins to wa_po-meins2,
              wa_mseg-werks to wa_po-werks,
              wa_mseg-charg to wa_po-charg.
         wa_po-balqty = wa_eban-menge - c_grmenge.
         clear : wa_rseg,wa_rbkp.
         read table it_rseg into wa_rseg with key
                        ebeln = wa_mseg-ebeln
                        ebelp = wa_mseg-ebelp.
         read table it_rbkp into wa_rbkp
                    with key belnr = wa_rseg-belnr
                             gjahr = wa_rseg-gjahr.
         if sy-subrc eq 0.
           move : wa_rbkp-belnr to wa_po-belnr,
                  wa_rbkp-bldat to wa_po-bldat,
                  wa_rbkp-RMWWR to wa_po-RMWWR,
                  WA_RBKP-WMWST1 TO WA_PO-WMWST1.
         endif.
           read table it_bseg into wa_bseg with key
                         ebeln = wa_rseg-ebeln
                         bukrs = wa_rseg-bukrs.
           if sy-subrc eq 0.
             move wa_bseg-belnr to wa_po-belnr_d.
           endif.
    *    read table it_bkpf into wa_bkpf
    *    with key belnr = wa_ekbe-belnr.
    *    read table it_bseg into wa_bseg
    *    with key belnr = wa_bkpf-belnr.
    CLEAR wa_bsik.
    clear it_bsik.
         read table it_bsik into wa_bsik
         with key belnr = wa_bkpf-belnr.
    *    if wa_bsik-shkzg = 'H'.
    *     wa_bsik-DMBTR = wa_bsik-DMBTR * 1.
    *     endif.
           if sy-subrc eq 0.
             move : wa_bsik-belnr to wa_po-belnr,
                     wa_bsik-DMBTR to wa_po-DMBTR.
            endif.
    *    clear wa_bsik.
    *    read table it_bsik into wa_bsik
    *               with key  belnr = wa_bseg-belnr.
    *    if sy-subrc eq 0.
    *        move : wa_bsik-DMBTR to wa_po-DMBTR.
    *    endif.
    *clear wa_bsak.
    *    read table it_bsak into wa_bsak
    *               with key  belnr = wa_bseg-belnr.
    *    if sy-subrc eq 0.
    *        move : wa_bsak-DMBTR_C to wa_po-DMBTR_C.
    *    endif.
    *clear : wa_rbkp.
    *loop at it_bsik into wa_bsik.
    *read table it_bsik into wa_bsik with key belnr = wa_rbkp-belnr.
    *if sy-subrc eq 0.
    *  move : wa_bsik-DMBTR to wa_po-DMBTR.
    *    endif.
    *endloop.
    *********Assign Vendor,PO Date*********
         clear wa_ekko.
         read table it_ekko into wa_ekko
                    with key ebeln = wa_po-ebeln.
         if sy-subrc eq 0.
           move:wa_ekko-lifnr to wa_po-lifnr,
                wa_ekko-bedat to wa_po-bedat.
         endif.
    *clear wa_ekko.
    *read table it_ekko into wa_ekko
    *with key lifnr = wa_po-lifnr.
    *if sy-subrc eq 0.
    *  move: wa_bsik-DMBTR to wa_po-DMBTR.
    *  endif.
    *    call function 'ZSD_BATCH_CLASSIFICATION_DATA'
    *      exporting
    **        ch_charg                   = wa_po-charg
    *        ch_matnr                   = wa_po-matnr
    *        ch_werks                   = wa_po-werks
    *      tables
    *        cl_data                    = it_cl_data
    **       I_SEL_CHARACTERISTIC       =
         loop at it_cl_data into wa_cl_data.
           if wa_cl_data-ausp1 ne '?'.
             if wa_cl_data-atnam eq 'THICKNESS'.
               move wa_cl_data-ausp1 to wa_po-thick.
             elseif wa_cl_data-atnam eq 'LENGTH'.
               move wa_cl_data-ausp1 to wa_po-length.
             elseif wa_cl_data-atnam eq 'WIDTH'.
               move wa_cl_data-ausp1 to wa_po-width.
             elseif wa_cl_data-atnam eq 'GRADE'.
               move wa_cl_data-ausp1 to wa_po-grade.
             endif.
           endif.
         endloop.
         modify it_po from wa_po index c_index.
         clear :c_grmenge,wa_po,wa_ekpo,wa_mseg,c_index.
       endloop.
    endform.                    " SETDATA
    *&      Form  FIELDCAT
    *       text
    *  -->  p1        text
    *  <--  p2        text
    form fieldcat .
       perform buildfields using '1' 'BANFN'  'IT_PO' 'PR Number' '' ''.
    *  perform buildfields using '2' 'BNFPO'  'IT_PO' 'PR Item Number' '' ''.
       perform  buildfields using '2' 'KNTTP' 'IT_PO' 'A/c Assignment Cat' '' ''.
       perform  buildfields using '2' 'PSTYP' 'IT_PO' 'Item Cat' '' ''.
       perform buildfields using '3' 'EKGRP'  'IT_PO' 'Purchase Group' '' ''.
       perform buildfields using '4' 'BADAT'  'IT_PO' 'Request Date' '' ''.
       perform buildfields using '5' 'MENGE'  'IT_PO' 'PR Quantity'  'X' ''.
       perform buildfields using '6' 'MEINS'  'IT_PO' 'PR Unit' '' ''.
       perform buildfields using '7' 'LIFNR'  'IT_PO' 'Vendor Number' '' ''.
       perform buildfields using '8' 'EBELN'  'IT_PO' 'Purchasing Doc No' '' ''  .
       perform buildfields using '9' 'BEDAT'  'IT_PO' 'PO Date' '' ''.
       perform buildfields using '10' 'MTART' 'IT_PO' 'Material Type' '' ''.
       perform buildfields using '11' 'MATKL' 'IT_PO' 'Material Group' '' ''.
       perform buildfields using '12' 'MATNR' 'IT_PO' 'Material Number' '' ''.
       perform buildfields using '13' 'TXZ01' 'IT_PO' 'Material Desc' '' ''.
       perform buildfields using '18' 'MENGE1' 'IT_PO' 'PO Quantity' 'X' ''.
       perform buildfields using '19' 'MEINS' 'IT_PO' 'PO Unit' '' ''.
       perform buildfields using '20' 'NETPR' 'IT_PO' 'Net Price' '' ''.
       perform buildfields using '21' 'PEINH' 'IT_PO' 'Price Unit' '' ''.
       perform buildfields using '22' 'MBLNR' 'IT_PO' 'GR Number' '' ''.
       perform buildfields using '23' 'MENGE2' 'IT_PO' 'GR Quantity' 'X' ''.
       perform buildfields using '24' 'MEINS2' 'IT_PO' 'GR Unit' '' ''.
       perform buildfields using '25' 'BELNR' 'IT_PO' 'Invoice doc. number' '' ''.
       perform buildfields using '26' 'BLDAT' 'IT_PO' 'Invoice Date' '' ''.
    *  perform buildfields using '26' 'BELNR_D' 'IT_POP' 'A/C Doc. No.' '' ''.
    *  perform buildfields using '26' 'AUGBL' 'IT_PO' 'Clearing Doc No.' '' ''.
       perform buildfields using '26' 'DMBTR' 'IT_PO' 'OPEN AMOUNT' '' ''.
      perform buildfields using '26' 'DMBTR' 'IT_PO' 'clear AMOUNT' '' ''.
    *  perform buildfields using '26' 'DMBTR_C' 'IT_PO' 'Clear balance' '' ''.
       if ch_bal = 'X'.
         perform buildfields using '27' 'BALQTY' 'IT_PO' 'Balance Quantity'
         'X' ''.
       endif.
       perform buildfields using '26' 'WMWST1' 'IT_PO' 'TOTAL TAX ADDED' 'X' ''.
       perform buildfields using '26' 'RMWWR' 'IT_PO' 'TOTAL AMOUNT IN INVOICE' 'X' ''.
    endform.                    " FIELDCAT
    *&      Form  BUILDFIELDS
    *       text
    *      -->P_0449   text
    *      -->P_0450   text
    *      -->P_0451   text
    *      -->P_0452   text
    form buildfields  using    value(p_col_pos) like sy-cucol
                                value(p_fldname) type slis_fieldname
                                value(p_tabname) type slis_tabname
                                value(p_reptext) like dd03p-reptext
                                value(p_do_sum) type char1
                                value(hotspot) type char1.
       wa_fcat-col_pos = p_col_pos.
       wa_fcat-fieldname = p_fldname.
       wa_fcat-tabname = p_tabname.
       wa_fcat-reptext_ddic = p_reptext.
       wa_fcat-do_sum = p_do_sum.
       wa_fcat-hotspot = hotspot.
       append wa_fcat to it_fcat.
       clear wa_fcat.
    endform.                    " BUILDFIELDS
    *&      Form  DISPLAY
    form display .
       clear wa_layout.
       wa_layout-zebra = 'X'.
       wa_layout-colwidth_optimize = 'X'.
    * wa_layout-box_fieldname     = 'SEL'.
    * wa_layout-edit = 'X'.
       perform build_sort using 'BANFN' '1' 'X'.
       call function 'REUSE_ALV_GRID_DISPLAY'
        exporting
    *   I_INTERFACE_CHECK                 = ' '
    *   I_BYPASSING_BUFFER                = ' '
    *   I_BUFFER_ACTIVE                   = ' '
          i_callback_program               = sy-cprog
    *   I_CALLBACK_PF_STATUS_SET          = ' '
        I_CALLBACK_USER_COMMAND           = 'USER_COMMAND '
          i_callback_top_of_page           = 'TOP_OF_PAGE'
    *   I_CALLBACK_HTML_TOP_OF_PAGE       = ' '
    *   I_CALLBACK_HTML_END_OF_LIST       = ' '
    *   I_STRUCTURE_NAME                  =
        i_background_id                   = 'ALV_BACKGROUND'
    *   I_GRID_TITLE                      =
    *   I_GRID_SETTINGS                   =
          is_layout                        = wa_layout
          it_fieldcat                      = it_fcat
    *   IT_EXCLUDING                      =
    *   IT_SPECIAL_GROUPS                 =
         it_sort                           = it_sort
    *   IT_FILTER                         =
    *   IS_SEL_HIDE                       =
    *   I_DEFAULT                         = 'X'
        I_SAVE                            = 'A'
    *   IS_VARIANT                        =
    *   IT_EVENTS                         =
    *   IT_EVENT_EXIT                     =
    *   IS_PRINT                          =
    *   IS_REPREP_ID                      =
    *   I_SCREEN_START_COLUMN             = 0
    *   I_SCREEN_START_LINE               = 0
    *   I_SCREEN_END_COLUMN               = 0
    *   I_SCREEN_END_LINE                 = 0
    *   I_HTML_HEIGHT_TOP                 = 0
    *   I_HTML_HEIGHT_END                 = 0
    *   IT_ALV_GRAPHICS                   =
    *   IT_HYPERLINK                      =
    *   IT_ADD_FIELDCAT                   =
    *   IT_EXCEPT_QINFO                   =
    *   IR_SALV_FULLSCREEN_ADAPTER        =
    * IMPORTING
    *   E_EXIT_CAUSED_BY_CALLER           =
    *   ES_EXIT_CAUSED_BY_USER            =
         tables
           t_outtab                          = it_po[]
      exceptions
        program_error                     = 1
        others                            = 2
       if sy-subrc <> 0.
         message id sy-msgid type sy-msgty number sy-msgno
                 with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
       endif.
    endform.                    " DISPLAY
    *&      Form  top_of_page
    *       text
    form top_of_page.                                           "#EC *
    **********Create report header*********
       refresh it_lshead.
       clear wa_lshead.
    **********To display date in header*********
    *  write: s_badat-low to c_low dd/mm/yyyy,s_badat-high to c_high
    *  dd/mm/yyyy.
    *  if s_badat-high is initial.
    *    concatenate 'Dated on' c_low into c_date separated by space.
    *  else.
    *    concatenate 'Dated between' c_low 'and' c_high into c_date separated
    *    by space.
    *  endif.
       wa_lshead-typ = 'H'.
       wa_lshead-info = 'PR To Payment History'.
    *  'Pending Indents History -

    We had a requirement to retrieve "aging of receiveables" by customer. Basically, it goes thru each record and depending on the due date places the amounts in the following buckets (example). 0-30 day Overdue, 31-60 days Overdue, 61-90 days overdue, 30+ days overdue, 60+ days overdue) etc all the way to 6+ years overdue.
    There are also cooresponding buckets for coming due analysis. For example, what is: 0-30 days coming due, 31-60 days coming due, 30+ days coming due, etc...
    To do this, first I needed to be able be able to produce an open items statement at any given time in the past. Now, this seems impossible because of how the items go from open to cleared all the time. And an item that was open one month ago, may not be open anymore.
    What I did was first remove any selections on item status. Then compare the posting date with teh key date in the past, if the posting date is less than or equal to the key date, keep the record.
    Then compare the clearing date with the key date. First, keep all that are #. (This keeps all records still open from that posting date/key date)
    Then, add another check for all items that were cleared after the key date (GT Key Date). This gives you the open items on that date.
    Hope that makes sense. Let me know if you want clarification.
    /smw

  • Error in creation of custom PD infotype

    Hi,
    I have a task of creating a custom PD infotype(p9xxx). I created HRI9xxx structure with all the custom fields and when I try to create the infotype using tcode PPCI(selected 'field infotype' option and create button in the 'infotype' block was pressed), it gives an error message that p9xxx-begda is not in ABAP dictionary and then it gives me list of screens, module pools and tables created. This custom infotype entry does not exist in T777I. I have tried regenerating it and same problem persists. If anyone knows the solution, please do let me know.
    Thanks in advance

    Solved.

Maybe you are looking for

  • Performance issue in procedure

    Hi All i have a performance issue with below procedure it is taking 10-15 hrs .custom table has 2 lacks record . PROCEDURE update_summary_dollar_amounts( p_errbuf OUT VARCHAR2 ,p_retcode OUT NUMBER) IS v_customer_id NUMBER := NULL; pymt_count NUMBER

  • What's wrong, my MBP works fine!

    After 30 years or so on a PC I moved to a Mac. I'm running Lion on a 2011 MBP. I upgraded to Lion with no trouble. My battery lasts long enough; 6-7 hours depending on what I do. I just upgraded to 10.7.3 and was back at work in about 25 minutes. Wha

  • Tell iPhone to NOT sleep when connected to dock?

    I can't seem to find any setting where I can accomplish this. Am I missing something?

  • DUPLICATE CONTACTS IN ADDRESS BOOK ON iPHONE

    I have duplicate contacts for every name in my address book on my iPhone. This morning, I opened my address book in my AppleBook and erased all duplicates. I synced my iPhone again, and still have duplicate addresses. Can anyone explain the problem a

  • Adobe LiveCycle Designer ES2 email button issue...  :(

    I have created a form with an submit button with is supposed to go to an email address. I have used this EXACT process in a prior form and had no issues. I am using a regular button and then have a script in MouseUp*. The following script will not op