Problem drawing an arrow

i am facing serious problems drawing an arrow which has to be moved round the screen.
does anybody have any idea or reference websites that would solve my problem
i have to rotate the arrow to the mouse pointer to wherever it is dragged.
hope u will get with this nick
hussain52

A more descriptive backgound to the problem may help people come up with a solution for you.
From what you've said it sound like you need to use a canvas and paint the arrow on it. Then use a mouse listener to listen for mouse clicks on the arrow and re-draw the arrow appropriatly.
Does this sound like it might work?
If so, try the code below...
It only paints a line, but it might get you thinking in the right direction?
Additions to get it to do what you want are...
1. Draw an arrow head at the end of the line.
2. Listen for mouse clicks within a certain radius of the end of the line.
3. Redraw the line using the original start point and the new end.
However, if I've completely missunderstood then it's all a complete waste of time.... but I've enjoyed it.
Adios amigo.
/*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* Class declaration
* @author Ollie Lord
* @version %I%, %G%
public class ArrowCanvas extends Canvas implements MouseListener {
private int startX;
private int startY;
private int endX;
private int endY;
* Constructor declaration
* @see
public ArrowCanvas() {
          setSize(new Dimension(200, 200));
          addMouseListener(this);
public void paint(Graphics g) {
          g.setColor(Color.black);
          g.drawLine(startX, startY, endX, endY);
* Invoked when the mouse has been clicked on a component.
public void mouseClicked(MouseEvent e) {
* Invoked when the mouse enters a component.
public void mouseEntered(MouseEvent e) {
* Invoked when the mouse exits a component.
public void mouseExited(MouseEvent e) {
* Invoked when a mouse button has been pressed on a component.
public void mousePressed(MouseEvent e) {
          System.out.println("Pressed");
          startX=e.getX();
          startY=e.getY();
* Invoked when a mouse button has been released on a component.
public void mouseReleased(MouseEvent e) {
          System.out.println("Released");
          endX=e.getX();
          endY=e.getY();
          repaint();
* Method declaration
* @param args
* @see
public static void main(String[] args) {
JFrame frame = new JFrame("Arrow");
frame.getContentPane().add(new ArrowCanvas());
frame.pack();
frame.show();
/*--- formatting done in "Ollies Java Convention" style on 07-04-2001 ---*/

Similar Messages

  • How to draw an arrow  ?

    hi.
    i want to create an application which permet to create graphs.
    to create edges i use :
    var arc = Path {
    strokeWidth: bind width
    elements: [
    MoveTo {
    x: bind debutX
    y: bind debutY
    QuadCurveTo {
    x: bind finX
    y: bind finY
    controlX: bind pointX
    controlY: bind pointY
    and i wan't to draw an arrow on this arc so i add a Polygon
    var triangle = Polygon {
    points: bind [pointX - 10,pointY - 10,pointX,pointY,pointX + 10,pointY - 10]
    fill: Color.AQUA
    strokeWidth: 5
    you can see that i use the same pointX and pointY .....this is what i obtain
    http://www.servimg.com/image_preview.php?i=65&u=11565828][img]http://i86.servimg.com/u/f86/11/56/58/28/fleche10.jpg
    the arrow is not on the arc !!
    thanks
    Edited by: ksergses on Apr 20, 2009 5:31 AM

    >
    Indeed, on Bézier curves, control points are outside of the curve, in general.
    Note that I see the triangle pointing precisely on the curve on the given screenshot... It depends on what you call arrow tip! ;-)no it's not the right tip pointing on the curve.....in general the arrow is far from the curve
    Back to your problem, either you compute the middle point with the Bézier formulasthat's what i am thinking about...but even if i do that ...the problem that the curves position can change ..and it's form also...and calculating the middle point is not the solution in this case .......
    i am searching for a tool that bind two objects ( arrow and curve) and after that we can manipulate them like one element ( like flash) !
    I am disappointed that JavaFX does not provide a tool to draw arrows easily.
    thanks
    Edited by: ksergses on Apr 21, 2009 5:03 AM

  • Drawing an arrow on a photo

    Is it possible to draw an arrow on a photo using iPhoto? I have a picture I want to e-mail to someone, and to draw their attention to one detail. The arrow doesn't have to look great -- it could be the equivalent of taking a Sharpie to a printed-out photo.

    Sara
    No, it's not possible using iPhoto. You can use other editors to do this such as Photoshop Elements or Seashore. There's a new editor called ACORN. It has a trial period so you could see if it meets your needs in the long term by using it in the short term. It will allow you to draw on the pic.
    You can set Acorn or Photoshop or any image editor as an external editor in iPhoto. (Preferences -> General -> Edit Photo: Choose from the Drop Down Menu.) This way, when you double click a pic to edit in iPhoto it will open automatically in the editor, and when you save it it's sent back to iPhoto automatically.
    Regards
    TD

  • Drawing an arrow between two rectangle shapes

    i am trying to draw an arrow between two rectangle shapes. the arrow will start from the center of one rectangle and end with the arrow tip at the edge of the other rectangle. i actually draw the arrow first, and draw the rectangles last so the effect of where the arrow starts will seem to come from the edge and not the center.
    i have code using some trigonmetry that works for squares, but as soon as the shape becomes a rectangle (i.e. width and height are not the same), the drawing breaks.
    can i detect where a line intersects with a shape through clipping and use that point location to draw my arrow head? if so, how?

    Here's one way to do this using the rule of similar triangles.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Pointers extends JPanel {
        Rectangle r1 = new Rectangle(40,60,100,150);
        Rectangle r2 = new Rectangle(200,250,175,100);
        int barb = 20;
        double phi = Math.toRadians(20);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            g2.draw(r1);
            g2.draw(r2);
            g2.setPaint(Color.red);
            g2.draw(getPath());
        private GeneralPath getPath() {
            double x1 = r1.getCenterX();
            double y1 = r1.getCenterY();
            double x2 = r2.getCenterX();
            double y2 = r2.getCenterY();
            double theta = Math.atan2(y2 - y1, x2 - x1);
            Point2D.Double p1 = getPoint(theta, r1);
            Point2D.Double p2 = getPoint(theta+Math.PI, r2);
            GeneralPath path = new GeneralPath(new Line2D.Float(p1, p2));
            // Add an arrow head at p2.
            double x = p2.x + barb*Math.cos(theta+Math.PI-phi);
            double y = p2.y + barb*Math.sin(theta+Math.PI-phi);
            path.moveTo((float)x, (float)y);
            path.lineTo((float)p2.x, (float)p2.y);
            x = p2.x + barb*Math.cos(theta+Math.PI+phi);
            y = p2.y + barb*Math.sin(theta+Math.PI+phi);
            path.lineTo((float)x, (float)y);
            return path;
        private Point2D.Double getPoint(double theta, Rectangle r) {
            double cx = r.getCenterX();
            double cy = r.getCenterY();
            double w = r.width/2;
            double h = r.height/2;
            double d = Point2D.distance(cx, cy, cx+w, cy+h);
            double x = cx + d*Math.cos(theta);
            double y = cy + d*Math.sin(theta);
            Point2D.Double p = new Point2D.Double();
            int outcode = r.outcode(x, y);
            switch(outcode) {
                case Rectangle.OUT_TOP:
                    p.x = cx - h*((x-cx)/(y-cy));
                    p.y = cy - h;
                    break;
                case Rectangle.OUT_LEFT:
                    p.x = cx - w;
                    p.y = cy - w*((y-cy)/(x-cx));
                    break;
                case Rectangle.OUT_BOTTOM:
                    p.x = cx + h*((x-cx)/(y-cy));
                    p.y = cy + h;
                    break;
                case Rectangle.OUT_RIGHT:
                    p.x = cx + w;
                    p.y = cy + w*((y-cy)/(x-cx));
                    break;
                default:
                    System.out.println("Non-cardinal outcode: " + outcode);
            return p;
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new Pointers());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • How to draw an arrow in Java2D ?

    Hi ,
    Can anybody tell me how can I draw an arrow in Java2D ? The main issue here is to draw the 2 small arrow lines at the appropriate angle at one end of the line
    Thanks
    Ratheesh

    import java.awt.*;
    import java.awt.geom.*;
    public abstract class Transformers
    extends Component {
    Shape mAxes, mShape;
    int mLength = 54, mArrowLength = 4, mTickSize = 4;
    public Transformers() {
    mAxes = createAxes();
    mShape = createShape();
    protected Shape createAxes() {
    GeneralPath path = new GeneralPath();
    // Axes.
    path.moveTo(-mLength, 0);
    path.lineTo(mLength, 0);
    path.moveTo(0, -mLength);
    path.lineTo(0, mLength);
    // Arrows.
    path.moveTo(mLength - mArrowLength, -mArrowLength);
    path.lineTo(mLength, 0);
    path.lineTo(mLength - mArrowLength, mArrowLength);
    path.moveTo(-mArrowLength, mLength - mArrowLength);
    path.lineTo(0, mLength);
    path.lineTo(mArrowLength, mLength - mArrowLength);
    // Half-centimeter tick marks
    float cm = 72 / 2.54f;
    float lengthCentimeter = mLength / cm;
    for (float i = 0.5f; i < lengthCentimeter; i += 1.0f) {
    float tick = i * cm;
    path.moveTo( tick, -mTickSize / 2);
    path.lineTo( tick, mTickSize / 2);
    path.moveTo(-tick, -mTickSize / 2);
    path.lineTo(-tick, mTickSize / 2);
    path.moveTo(-mTickSize / 2, tick);
    path.lineTo( mTickSize / 2, tick);
    path.moveTo(-mTickSize / 2, -tick);
    path.lineTo( mTickSize / 2, -tick);
    // Full-centimeter tick marks
    for (float i = 1.0f; i < lengthCentimeter; i += 1.0f) {
    float tick = i * cm;
    path.moveTo( tick, -mTickSize);
    path.lineTo( tick, mTickSize);
    path.moveTo(-tick, -mTickSize);
    path.lineTo(-tick, mTickSize);
    path.moveTo(-mTickSize, tick);
    path.lineTo( mTickSize, tick);
    path.moveTo(-mTickSize, -tick);
    path.lineTo( mTickSize, -tick);
    return path;
    protected Shape createShape() {
    float cm = 72 / 2.54f;
    return new Rectangle2D.Float(cm, cm, 2 * cm, cm);
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    // Use antialiasing.
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    // Move the origin to 75, 75.
    AffineTransform at = AffineTransform.getTranslateInstance(75, 75);
    g2.transform(at);
    // Draw the shapes in their original locations.
    g2.setPaint(Color.black);
    g2.draw(mAxes);
    g2.draw(mShape);
    // Transform the Graphics2D.
    g2.transform(getTransform());
    // Draw the shapes in their new locations, but dashed.
    Stroke stroke = new BasicStroke(1,
    BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
    new float[] { 3, 1 }, 0);
    g2.setStroke(stroke);
    g2.draw(mAxes);
    g2.draw(mShape);
    public abstract AffineTransform getTransform();
    public Frame getFrame() {
    ApplicationFrame f = new ApplicationFrame("...more than meets the eye");
    f.setLayout(new BorderLayout());
    f.add(this, BorderLayout.CENTER);
    f.setSize(350,200);
    f.center();
    return f;
    }

  • Problems drawing image

    Im sorry for even askign this but i'm having problems drawing an image, no idea why its not working!!! I know that my Image object actually is the image because i can get it to display on a button, but i need to get it to display in the JPanel through the paintComponent() method, for some reason it wont do it. Thanks for the help.
    Here's my code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class StatWindow extends JDialog{
        private StatPanel panel;
        public StatWindow(JFrame parent) {
            this(parent, null);
        public StatWindow(JFrame parent, String data){
            super(parent, "Stat", false);
            getContentPane().setLayout(null);
            panel = new StatPanel();
            getContentPane().add(panel);
            panel.setBounds(0, 0, 220, 220);
            setSize(300, 300);
            setVisible(true);
        class StatPanel extends JPanel{
            private Image diagram1;
            private Image diagram2;
            private Image diagram3;
            private Image diagram4;
            private Image diagram5;
            private Image diagram6;
            private Image diagram7;
            private Image diagram8;
            private Image diagram9;
            private Image diagram10;
            private Image diagram11;
            private Image diagram12;
            private Image diagram13;
            private Image diagram14;
            private Image diagram15;
            private Image diagram16;
            private Image diagram17;
            private Image diagram18;
            private Image diagram19;
            private Image diagram20;
            private Image diagram21;
            private Image diagram22;
            private Image diagram23;
            private Image diagram24;
            private Image diagram25;
            private Image diagram26;
            private Image diagram27;
            public StatPanel(){
                super();
                Image diagram1 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_01.jpg"));
                Image diagram2 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_02.jpg"));
                Image diagram3 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_03.gif"));
                Image diagram4 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_04.jpg"));
                Image diagram5 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_05.jpg"));
                Image diagram6 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_06.jpg"));
                Image diagram7 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_07.gif"));
                Image diagram8 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_08.jpg"));
                Image diagram9 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_09.jpg"));
                Image diagram10 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_10.jpg"));
                Image diagram11 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_11.gif"));
                Image diagram12 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_12.jpg"));
                Image diagram13 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_13.jpg"));
                Image diagram14 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_14.gif"));
                Image diagram15 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_15.gif"));
                Image diagram16 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_16.jpg"));
                Image diagram17 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_17.jpg"));
                Image diagram18 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_18.gif"));
                Image diagram19 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_19.jpg"));
                Image diagram20 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_20.jpg"));
                Image diagram21 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_21.jpg"));
                Image diagram22 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_22.gif"));
                Image diagram23 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_23.jpg"));
                Image diagram24 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_24.gif"));
                Image diagram25 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_25.jpg"));
                Image diagram26 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_26.jpg"));
                Image diagram27 = getToolkit().getImage(getClass().getResource("xpbn/media/stat/Diagram_27.jpg"));
                addMouseMotionListener(new MouseMotionHandler());
                addMouseListener(new MouseHandler());
                JButton b = new JButton(new ImageIcon(diagram1));
                getContentPane().add(b);
                b.setBounds(0, 0, 40, 40);
            class MouseMotionHandler extends MouseMotionAdapter{
                public void mouseMoved(MouseEvent e){
            class MouseHandler extends MouseAdapter{
                public void mousePressed(MouseEvent e){
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g.create();
                g2d.drawImage(diagram1, 0, 0, this);
                g2d.dispose();
    }

    you have these declarations
    private Image diagram1;
    private Image diagram2;
    and in your constructor you have these
    Image diagram1 = getToolkit().getImage...
    Image diagram2 = getToolkit().getImage...
    the inclusion of the 'type' Image makes them local to the constructor

  • Problem with up-arrow on a long command line

    I often use the "terminal" window to open up a connection (via ssh) to linux and unix boxes.
    While I'm logged into the remote computer and I try to edit a previous command, I notice that my
    display gets all fouled up if the command that I'm trying edit is very long. I'm unable to do the
    usual unix tricks of up-arrowing to the command and then backspacing through it to perform my edits. Often my only recourse is to retype the entire command which is a pain and prone to error.
    I'm using bash as my Mac shell and tcsh on the remote machines.
    Has anybody experienced this? Any hints?

    It's a visual-only problem with Terminal.app.
    Other than the cosmetic effect, you will find that the editing works as you expect - you might just have to be psychic with regards to telling how far to backspace and where/when to make your edits.
    The problem has been there for a long time. You might have better luck setting the terminal to a different emulation (Terminal -> Preferences -> Declare terminal as:) to see if one of the other emulations work for you, or use a different terminal application such as iTerm

  • 3d problem - drawing order

    Okay, I'm working on 3D stuff and everything is going fine, etc. But I've got one problem: I don't know how to determine the drawing order of all the faces, so know faces behave like they shouldn't, because they get drawn at the wrong order, and get drawn while they actually shouldn't be. I'm NOT using Java3D.
    Currently, I'm using the painter's algorithm (get the distance of the face to the center, and determine the order that way), but it's not working properly, as expected. I read BSP-trees are the best way to determine the order of the drawings, but I can't find any decent BSP-tutorial (for 3D) nor any code I can use.
    My question: Does anyone knows a decent, detailed 3D-BSP-Tutorial, or any code I can use/examine or could anyone explain it here or tell me an other (easier) method. It should be a fast method, because I'm using this for a game I'm creating.
    Please help,
    Matt.

    Matt, could you be a little more specific? Like what is exactly your polygon drawing problem? Some of the polygons are inside out, or all of them? Or they render in very wrong locations etc?

  • Problem in Orange Arrow Link

    Dear All,
    I have a typical problem which I am facing it for the first time.
    I have created a report which shows transactions listing of the branches in the system i.e Sales Order, Delivery, Invoice etc. Each transaction heads are a sub report i.e Invoice is a subreport, Order is a subreport and so on. I have included the link button also so that the users can go into the transactions when they preview the report. Now the link button is working for all the documents except for the Invoices where it throws the message "You are not permitted to perform this transaction". Now there is no authorization involved in the database. Everyone has a full authorization.Even I myself as a manager(super user) cannot open the transaction from the link arrow. If i go manually to Invoice, I am able to open the document. Now the same report when I open up in another database i.e OEC one it is working.
    Please can anyone let me know where I am missing something or where I am going wrong.
    FYI, the report has a selection of Branches, From Date and To Date and i am using SAP 8.8 Pl 10.
    Regards,
    Gary

    Hi Gary,
    Refer This Link,
    Transaction link in CR report
    Thanks,
    Srujal Patel

  • Problem drawing a graph in Java2D

    I am trying to draw a graph using Java2D, onto a JPanel. I works sort of ok, but i have 2 problems;
    1. I don't know how to get it "linked" to the paint() method, so everytime someone resizez the window/window looses focus, the drawing is removed.
    2. The graphing becomes unacurate when passing more than 25-30 values, I think the problem might be the "hvorPaAkse" (whereOnAksis) or the "okY" (increaseY) value, that for some rasen appear to add too much, so that the error gradually increases for every loop in the for(), or something like that.
    I know reading the code and understanding the problem itselv is a challenge, but I if there's anybody out there who can help, I would be thankful for any help!
    CODE:
    //The draw axis method
    public void tegnAkser(JComponent comp, int antX, int antY, int okX, int okY) {
    Graphics g = comp.getGraphics();
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(akseStrek);
    g2.draw(new Line2D.Double(origo.x, origo.y, origo.x, comp.getHeight()-((antY*okY)+(comp.getHeight()/yOffset))));
    g2.draw(new Line2D.Double(origo.x, origo.y, origo.x+(antX*okX), origo.y));
    int hvorPaAkse = origo.x;
    System.out.println(comp.getHeight()/antY);
    int gangeverdi = 1;
    if(comp.getHeight()/antY < 16) {
    gangeverdi = 5;
    for(int i=0; i<antX; i++) {
    g2.draw(new Line2D.Double(hvorPaAkse, origo.y - 2, hvorPaAkse,
    origo.y + 2));
    g2.drawString("" + i, hvorPaAkse, origo.y + 15);
    hvorPaAkse += okX;
    hvorPaAkse = origo.y;
    for(int i=0; i<antY; i++) {
    if(i%gangeverdi == 0) {
    g2.draw(new Line2D.Double(origo.x - 2, hvorPaAkse, origo.x + 2,
    hvorPaAkse));
    g2.drawString("" + i, origo.x - 15, hvorPaAkse);
    hvorPaAkse -= okY;
    //the drawGraf method
    public void tegnGraf(int[] verdier, JComponent comp) {
    Graphics g = comp.getGraphics();
    Graphics2D g2 = (Graphics2D) g;
    int xLengde = comp.getWidth();
    int yLengde = comp.getHeight();
    origo = new Punkt(xLengde - 9 * (xLengde / xOffset),
    yLengde - (yLengde / yOffset));
    int ant = verdier.length;
    int maxVerdi = 0;
    for (int i = 0; i < verdier.length; i++) {
    if (verdier[i] > maxVerdi)
    maxVerdi = verdier;
    tegnAkser(comp, ant+1, maxVerdi+1, (xLengde - (xLengde / xOffset)) / ant,
    ( (yLengde / yOffset) - yLengde) * -1 / maxVerdi);
    g2.setColor(Color.BLUE);
    g2.setStroke(grafStrek);
    ArrayList punkter = new ArrayList();
    for (int i = 0; i < verdier.length; i++) {
    g2.drawString("x", origo.x-2 + (i * (xLengde - (xLengde / xOffset)) / ant),
    origo.y +3 -
    (verdier[i] * ( (yLengde / yOffset) - yLengde) * -1 /
    maxVerdi));
    punkter.add(new Point2D.Double(origo.x +
    (i * (xLengde - (xLengde / xOffset)) / ant),
    origo.y -
    (verdier[i] *
    ( (yLengde / yOffset) - yLengde) * -1 /
    maxVerdi)
    //g2.draw(new Line2D.Double(origo.x,origo.y,origo.x+1,origo.y+1));
    for(int i=1; i<punkter.size(); i++) {
    Point2D.Double forrige = (Point2D.Double)punkter.get(i-1);
    Point2D.Double denne = (Point2D.Double)punkter.get(i);
    Line2D.Double linje = new Line2D.Double(forrige,denne);
    g2.draw(linje);
    Thanks
    CJ

    I couldn't do much with the code that you posted. It looks like you are plotting integers. Maybe you can use this.
    /* Plots plus/minus int values for ordinate for
    * evenly-distributed, positive int values on abcissa
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class PlottingIntegers
        public static void main(String[] args)
            int[] data = {
                100, 220, 12, 65, 47, 175, 190, 18
            IntegerPlotter plotter = new IntegerPlotter();
            for(int i = 0; i < 8; i++)
                plotter.plot(data);
    JFrame f = new JFrame("Plotting Integers");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(plotter);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    class IntegerPlotter extends JPanel
    final int PAD = 25;
    List dataList;
    public IntegerPlotter()
    dataList = new ArrayList();
    setBackground(Color.white);
    setPreferredSize(new Dimension(400,300));
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int width = getWidth();
    int height = getHeight();
    int xStep = (width - 2*PAD)/(dataList.size() - 1);
    int x = PAD;
    int y;
    // scale data
    int max = ((Integer)Collections.max(dataList)).intValue();
    int min = ((Integer)Collections.min(dataList)).intValue();
    int vertSpace = height - 2*PAD;
    int yOffset = height - PAD;
    int yDataOffset = (min >= 0 ? min : max > 0 ? 0 : max);
    double scale = (double)vertSpace/(max - min);
    int yOrigin = yOffset + (int)(min > 0 ? 0 : max > 0 ? scale*min : - vertSpace);
    // draw ordinate
    g2.draw(new Line2D.Float(PAD, PAD, PAD, yOffset));
    // draw abcissa
    g2.draw(new Line2D.Float(PAD, yOrigin, width - PAD, yOrigin));
    // label ordinate limits
    g2.drawString(String.valueOf(max), 10, PAD - 10);
    g2.drawString(String.valueOf(min), 10, yOffset + PAD/2);
    g2.setStroke(new BasicStroke(4f));
    g2.setPaint(Color.red);
    for(int i = 0; i < dataList.size(); i++)
    y = yOrigin -
    (int)(scale * (((Integer)dataList.get(i)).intValue() - yDataOffset));
    g2.draw(new Line2D.Float(x, y, x, y));
    x += xStep;
    protected void plot(int input)
    dataList.add(new Integer(input));
    repaint();

  • Problems drawing images form another class

    Ok as the title says I'm having trouble drawing images from a different class. I have a class that represents a plane and it has a draw' method that draws its .gif image.
    public void draw (Graphics g)
    g.drawImage(planepic , xPos, yPos, null)
    then in my main class in the paint method i have
    plane.draw(g);
    I think my problem is the null for my image observer. I tried using null as my image observer and i got a error saying i can't make a static reference to a non static method.
    I've done some research because i never really understood static but i still don't quite get it.
    Also when I use this as my image observer i get a error in my plane object.
    I also just tried passing and making a object for my main class and i still got the static error.
    Any help is appreciated and thanks in advance

    Ok as the title says I'm having trouble drawing
    images from a different class. I have a class that
    represents a plane and it has a draw' method that
    draws its .gif image.
    public void draw (Graphics g)
    g.drawImage(planepic , xPos, yPos, null)
    in my main class in the paint method i have
    plane.draw(g);
    I think my problem is the null for my image observer.
    I tried using null as my image observer and i got a
    error saying i can't make a static reference to a non
    static method. Use a minimal implementation of the ImageObserver to be sure.
    public class Plane implements ImageObserver
    public boolean imageUpdate(
    Image img,int infoFlags,int x,int y,int width,int height)
       switch(infoFlags)
          case ALLBITS:
                    return false;
          case SOMEBITS:
                    return true;
          default:
                return true;
    I've done some research because i never really
    understood static but i still don't quite get it.
    Also when I use this as my image observer i get a
    error in my plane object.
    I also just tried passing and making a object for my
    main class and i still got the static error.
    Any help is appreciated and thanks in advanceWhen you call draw(g) from your other class you hand it a Graphics context that you instantiated somewhere else ie: in another class. Without a more complete example it is really impossible to determine your issue for sure,
    but if I was to guess I would say you need to make sure that the Graphics context handed to the draw(Graphics) method was instantiated from a Component that was already visible. ie: Do a f
    Frame.createImage() from your parent frame after iyou have already called setVisible(true); In other words I suspect you are making and Image from some other Component that is not yet visible. That however is a guess so if not the issue post the rest of the code or at least a minimal implementation that demonstrates this.
    About static:
    static means the class/variable is the same throughout ALL classes of that type and if changed in one instance it will change and thus be the same for all instances.
    You CAN call static by referencing the base class Object without having to instantiate.
    ie:given
    public class SomeClass
    static String name;
    static String getName
       if(name == null)
          name = "DefaultName";
       return name;
    }Thus you could call..
      String name = SomeClass.getName();As opposed to
    SomeClass myClass = new SomeClass();
          myClass.getName();This can get you in trouble if you try to make a method that is static
    that then tries to reference non static variables.
    ie:
    public class SomeClass
    int x;
    static String name;
    SomeClass()
       x=0;
    static String getName
       if(name == null)
          name = "DefaultName";
       x++;
       return name;
    }In this case SomeClass.getName(); will throw and exception because it is trying to access[b] x  from a static context .
    Hope that clears that up for you; if not post a more complete example.
    Good Luck!
    (T)

  • Problem drawing tiled image

    I have a tiled buffred image. I have implemented caching and tiling myself i.e. the complete image (that can be as big as 100+MB) is tiled into 512x512 tiles and i am keeping them in a cache implemented as hashmap. The cache size is adjusted based on the available memory.
    My logic is that when the user scrolls the image i figure out the tiles that needed to be shown to the user and then see if i can find it in the cache, in case of a cache miss i create the tile in memory (using createCompatibleImage()). Once the tile is created i stuff it in my cache. After making sure the required tiles are available i then simply use drawImage(tile,x,y,null) to draw the tiles inside the paintComponent() method. My problem is that the tiles get drawn erratically i.e. if the viewport requires six tiles to be drawn then every so often few of the tiles do not get drawn. I have made sure that the my program does call drawImage() six times once for each tile - but it seems that despite drawImage call the actual drawing has a mind of its own.
    I do not suspect my tile creation or cachig code since when someof the tiles are not shown properly all i have to do is to move mouse over the undrawn area and the tiles appear immediately.
    My code is spread all over so it is difficult to produce all the relevant code in here, so i will give some code snippet:
    // Code for creating a new tile
    public createTile()
    GraphicsConfiguration gc = Utility.getDefaultConfiguration();
    BufferedImage overlayImage = gc.createCompatibleImage(width, height);
    int ii = 0;
    int jj = 0;
         for (int i= 0; i<width; i++){                
              for (int j=0; j<height; j++){
                   int rgb = ....;//the rgb is calculated based on some specific logic.
                   overlayImage.setRGB(ii,jj,rgb);
                   jj++;
              ii++;
              jj = 0;
    // After creating the image I then resize the image to handle zoom in/zoom out
    // using nearest neighbor interpolation. I don't suspect the resize code so
    // have not reporduce it here.
         return (resizeImage(overlayImage,newWidth,newHeight)).
    ====================================================
    // Extract of some of my paint code is given below.
    //I am not calling super.paintComponent() because i am redrawing the
    // whole screen with my tiled image.
      public void paintComponent(Graphics g)
           Graphics2D g2d = (Graphics2D)g;
         Tile[]tiles = getChosenTiles();
                   for (int i=0; i<tiles.length; i++){
                        g2d.drawImage(tiles.getImage(), tiles[i].x, tiles[i].y, null);

    Since nobody replied to the post - i had no option but to dig into the problem myself. Good thing is that I managed to find the solution.
    As it turned out my logic was as below:
    Step 1: find out the tiles that need to be shown on the viewport.
    Step 2: obtain these tiles from the cache
    Step 2a: If tiles not found in cache then create the tiles in memory.
    Step 3: for (int i=0;i<tiles.length; i++) {             
                    g2d.drawImage(tiles.getImage(), null, tiles[i].x, tiles[i].y);
    The problem was that for some reason the Java graphics drawing could not keep up with the for loop. What i did was to move the drawing logic inside Step 2. i.e. I would get a tile and then draw it immediately after getting it. In other words the logic was changed to
    Step 1: find out the tiles that need to be shown on the viewport
    Step 2:
                 for (int i=0;i<tiles.length; i++) {
                     BufferedImage image = tiles.getImage();
    if (image == null) {
    image = createTileImage(tiles[i]);
    tiles[i].setImage(image);
    g2d.drawImage(tiles[i].getImage(), null, tiles[i].x, tiles[i].y);
    This solved my problem.
    -km

  • Using a keyListener to draw with arrow keys

    Hi!
    I am trying to create an interactive game where the user can
    draw a line using the arrow keys (similar to an etch-a-sketch). I
    have a start point acting on keyListeners that will move around the
    screen using the arrow keys, but I can't seem to figure out how to
    get the listeners to draw a line. Here is the correct code that
    moves the start point:
    information_txt.text = "USE YOUR ARROW KEYS TO DRAW";
    var speed:Number = 4;
    start_mc.onEnterFrame = function() {
    if (Key.isDown(Key.RIGHT)) {
    this._x = this._x+speed;
    } else if (Key.isDown(Key.LEFT)) {
    this._x = this._x-speed;
    if (Key.isDown(Key.UP)) {
    this._y = this._y-speed;
    } else if (Key.isDown(Key.DOWN)) {
    this._y = this._y+speed;
    How can I modify Action Script to get the keyListeners to
    draw on the arrow keys?
    Any help would be MUCH appreciated!!!
    Thanks!

    Thanks for your reply! That's awesome. you were right, my
    script is in AS 2.0... I guess I posted to the wrong section. But I
    could easily switch to AS 3.0. I am really just interested in
    drawing with the arrow keys and using that action script to draw
    onto my own stage/ image. I have tried messing with the script, but
    can't seem to get the "drawing" portions of the script to work.
    Any suggestions??
    Thanks again for the help!!!

  • Low memory problem drawing a route with MKAnnotationView

    Hi!
    I'm drawing a route like it's done in http://spitzkoff.com/craig/?p=81 but i'm not loading de coordinates from a file, i get the coordinates from GPS with CLLocationManager.
    The problem is that my app crash with low memory in the device. I guess it's the way i'm drawing the route.
    In - (MKAnnotationView *)mapViewMKMapView *)_mapView viewForAnnotationid <MKAnnotation>)annotation i can use dequeueReusableAnnotationViewWithIdentifier: like i do for the PinAnnotation?
    And if doesn't exist i can make initWithAnnotation:annotation reuseIdentifier: ?
    Should this solve my problem?
    Does AnnotationView's consume much memory?
    Thanks!And sorry for my bad english

    Hi!
    I'm drawing a route like it's done in http://spitzkoff.com/craig/?p=81 but i'm not loading de coordinates from a file, i get the coordinates from GPS with CLLocationManager.
    The problem is that my app crash with low memory in the device. I guess it's the way i'm drawing the route.
    In - (MKAnnotationView *)mapViewMKMapView *)_mapView viewForAnnotationid <MKAnnotation>)annotation i can use dequeueReusableAnnotationViewWithIdentifier: like i do for the PinAnnotation?
    And if doesn't exist i can make initWithAnnotation:annotation reuseIdentifier: ?
    Should this solve my problem?
    Does AnnotationView's consume much memory?
    Thanks!And sorry for my bad english

  • Really weird problem drawing lines..

    I have an application that during each frame draws a couple of Graphic2D lines. The program has worked great, and still does, except for when it runs on a new computer of mine. I just put togther a AMD XP 2000 with a Radeon 8500 (just in case this matters) and for some reason when I run my application, the lines drawn do not show up. I am positive they are being drawn, just not displaying, and yet the lines are drawn properly on my two other computers with the same exact java sdk package (1.4.0). Any ideas?!?!?

    Thanks if you took a ponder to my question, but it appeared to only be a Radeon driver problem, as the newest drivers weren't functioning properly for me..

Maybe you are looking for

  • Applet doesn´t load in java 7 with next-generation plug-in marked

    I have developed an applet with netbeans 7.1.2 which worked fine until I updated from jvm6 to jvm7. The applet does not load properly unless I uncheck from the configuration of the jvm the checbox plug-in next-generation. Anyone know why in java 6 wo

  • Course of action? Parsing 1000+ PDF forms into XML.

    Hello - I am looking to automate the parsing of hundreds of PDF Forms into XML and then do some basic validation. The preferred method would be to drop all of the PDF's into a folder, run a script, and then the PDF's would go to their corresponding d

  • Regarding VA01/VA02/VA03 - Adding a new field column to the Overview table

    Hi, Apologies if this is not the right forum, but I have a request to add an extra column into the main overview screen in VA01/VA02/VA03. The field I want to add is available from the Sales Header Data > Purchase Order Data tab (Ship-to party > Your

  • Software update for iPad 1

    Will there be any updates for the iPad 1? My last update was 5.1.1 I have noticed tat some apps are crashing.

  • CMYK v RGB and iPhoto

    After upgrading I was doing my normal photoshop work. Things were fine. Then I rebooted my computer and many of my images turned grey, washed out, looked like a raw image. They are all jpgs but the color setting was CMYK. Talked to support and the sa