Co-ordinate problem

ok i am trying to make a simple paint program and i have got stuck when trying to display the coordinates the mouse is pointing to.
i have a mouseMotionListener in one class which gets the point of the mouse when it enters or moves inside the canvas, like so:
public void mouseEntered(MouseEvent e)
p = e.getPoint();
public void mouseMoved(MouseEvent e)
p = e.getPoint();
}p is a point which i somehow want to pass into another class to be displayed outside of the canvas. But p is staying at (0,0) (what it was initialized as).
does anyone know what could be causing this?
i need a fresh brain and a cup of tea!

yup i already put
System.out.println("entered");
and likewise for moved and they worked fine
i dont really understand the second part of what you said there,
this is the code that recieves the point (the method called updateCo):
public class coBox extends JPanel
public static int x, y;
public String coord = "(" + x + "," + y + ")";
public coBox()
x = 0;
y = 0;
public void updateCo(Point p)
x = p.x;
y = p.y;
public void paintComponent(Graphics g)
g.drawString(coord, 30, 20);
}

Similar Messages

  • Textures - a simple problem

    Hi J3D gurus. Maybe you could help me with this problem which is really bugging me.
    Here is some code I have written to load a texture.
            TextureLoader textureLoad = null;
            TextureAttributes textureAttrib = new TextureAttributes();
            textureAttrib.setTextureBlendColor(0.0f,0.0f,0.0f,0.0f);
            textureAttrib.setTextureMode(TextureAttributes.BLEND);
            try {
              textureLoad = new TextureLoader
                (new URL(codeBase + "/test.gif"),this.canvas);
            catch (Exception e) {
              e.printStackTrace();
            ImageComponent2D image = textureLoad.getImage();
            System.out.println("Image width=" + image.getWidth());
            System.out.println("Image height=" + image.getHeight());
            Texture2D tex2D = new Texture2D
              (Texture.BASE_LEVEL, Texture.RGB, 128, 128);
            tex2D.setImage(0,image);
            a.setTexture(tex2D);Now when I apply the Appearance to my Shape3D object, the entire shape is textured with just the bottom left pixel from my 128*128 pixel image.
    I have been told to use an array of floats to set the texture coordinates. This following code, I copied from some example which would seem to be applying the texture to a tringle maybe (WHAT DOES THIS ARRAY DO EXACTLY)?
            float[] coords = {0.0f, 0.0f,
                                1.0f, 0.0f,
                                0.0f, 1.0f,
            GeometryArray geometry = (GeometryArray)shape.getGeometry();
            geometry.setTextureCoordinates(0, 0, coords);
            shape.setGeometry(geometry);My Shape3D is a circle clock face and my texture is a square with the width equal to my clock-face diameter.
    Anyway, when I run this, I get an error;
    java.lang.IllegalStateException: GeometryArray: cannot directly access data in BY_REFERENCE mode
         at javax.media.j3d.GeometryArrayRetained.setTextureCoordinates(GeometryArrayRetained.java:4588)
         at javax.media.j3d.GeometryArray.setTextureCoordinates(GeometryArray.java:2173)How do I map this simple texture onto my circle????
    Any help would be very appreciated.
    TOM

    This is definitely a texture co-ordinates problem.
    What is happening with the code here:        float[] coords = {0.0f, 0.0f,
                                1.0f, 0.0f,
                                0.0f, 1.0f,
                                };Is that you are initializing a pair of co-ordinates on the image for each point on the first face of your shape.
    This set of co-ordinates would be correct if you have a triangle that covers the top left corner of a square. If you had a whole square you would need a fourth texture co-ordinate pair at 1.0f, 1.0f after the second element. It does sound, however, like you're using a by-reference geometryArray, which means (I think- not used these myself) you will need to create the array of co-ordinates in an array belonging to the object and then hand a reference that array to your GeometryArray. Alternatively you could create it and then copy the information from your shape afterwards, which should mean it carries it's own co-ordinates.
    I'm on slightly sketchy ground myself here, so none of this is gospel, but I think that is roughly correct.

  • Problem: mapping mouse co-ordinates to a list of nodes in a graph.

    Hi.
    I have an undirected graph containing many nodes, some represent squares/tiles and some represent rooms in a board-game called Cluedo.
    Each node has an ID: -
    Rooms are called by the room name. -> Kitchen/Lounge
    Squares are called by the concatenated x/y position. -> A1/A2/K20
    I have created an algorithm to find the shortest path between two nodes in the graph.
    The problem I'm faced with is finding a way to map co-ordinates on the image file to these IDs. I have seen an implementation of a similar idea with an invisible image acting as a "colour-mask", so when the click hits the graphical map a function works out the colour of that pixel on the "colour-mask" and then uses a look-up table to find out which ID that is associated to.
    The problem with the above is that a Cluedo board has about 22x22 tiles and several rooms (each room would occupy several tiles in an undefined shape.)
    I've provided two example map files:
    http://www.dcs.qmul.ac.uk/~ade1/map.gif
    http://www.dcs.qmul.ac.uk/~ade1/map2.gif
    Does anyone have a suggestion of how I could solve this problem using what's available to me with Java?
    I'd appreciate any suggestions,
    Alexander Ellis

    Create a two-dimensional array that maps from grid coordinates to node/room objects.
    NodeOrRoom[][] grid = new NodeOrRoom[22][22];
    grid[0][0] = kitchen;
    grid[1][0] = kitchen;
    nodeLookup(int pixelTop, int pixelLeft) {
      return grid[pixelTop / gridCellHeight][pixelLeft / gridCellWidth];
    }Matthew

  • Learning Co-ordinate System - Problem

    Hi
    I created a sample project to epxlain my problem.
    There are two canvases in the main application. outerspace canvas and innerspace canvas.
    innerspace canvas has a visual component "mainBox"
    and there is also a visual component in outerspace canvas named "overBox"
    now i want user to map the x-xis and y-xis of overBox to mainBox, so when user will click re-arrange, overbox will completely cover the mainBox.
    This is actually a problem of different co-oridatane systems and i dont know how to map them into one.
    Here is the code.
    Application File
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*">
         <mx:Script>
              <![CDATA[
                        private function arrange(event:MouseEvent):void{
                             var point:Point = mainBox.localToGlobal(new Point());
                             overBox.x = point.x;
                             overBox.y = point.y;
              ]]>
         </mx:Script>
         <mx:Canvas width="80%" height="80%" horizontalCenter="0" verticalCenter="0" id="outerSpace" backgroundColor="#A9A9A9">
              <mx:Canvas width="80%" height="80%" horizontalCenter="0" verticalCenter="0" id="innerSpace" backgroundColor="#8DB5FF">
                   <ns1:Node horizontalCenter="0" verticalCenter="0" width="100" height="100" id="mainBox">
                   </ns1:Node>
              </mx:Canvas>
              <ns1:Node x="21" y="10" id="overBox" width="100" height="100" backgroundColor="#FFA352">
              </ns1:Node>
         </mx:Canvas>
         <mx:Button label="Re-Arrange" click="arrange(event)" left="10" top="10"/>
    </mx:Application>
    Project is also attached.
    Thanks

    Just see below. But it won't work if you resize the view, as one is centered
    private
    function arrange(event:MouseEvent):void
    // Get mainbox coord in local system - i.e. relative to innerSpace
    var p1:Point = new Point(mainBox.x,mainBox.y); 
    // Convert it to global coord from innerSpace
    var p2:Point = innerSpace.localToGlobal(p1); 
    // Convert it to local coord - relative to outerSpace
    var p3:Point = outerSpace.globalToLocal(p2); 
    overBox.x=p3.x;
    overBox.y=p3.y;

  • Problem with JPanel after rotation

    Hi,
    I am developing a graphics editor like mspaint. I have JPanel as my drawing canvas. now the problem is when I rotate the canvas, co-ordinates on the canvas are also getting rotate with it. for example if top-left corner is (0,0) initially then after rotating it 90 degree top-right corner becomes (0,0) and same for all the points on the canvas.
    the code i m using for rotation is
    contentPanel = new JPanel(){
    @Override
    protected void paintComponent(Graphics g) {                       
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    Rectangle rect=g2.getClipBounds();
    if(rotation!=0){
    double angle = rotation * Math.PI/2;
    g2.rotate(angle,getWidth()/2,getHeight()/2);
    rect=g2.getClipBounds();
    setPreferredSize(new Dimension(rect.width,rect.height));
    super.paintComponent(g);
    revalidate();
    };

    Whats your question?
    If you rotate it, of course the points will rotate, they have to.

  • Co-ordinates in Hong Kong Seems To Be All Wrong On...

    Anyone using nokia map on E90.. need verification help..
    Google Map and Google Earth 22.308600, 114.170520 shows junction of Kansu Street and Temple Street (男人街)。
    Google Map and Google Earth 22.305450, 114.169760 shows junction of Jordan Road and Temple Street (男人街)。
    Google Map and Google Earth 22.319510, 114.170540 shows junction of Argyle Street and Tung Choi Street (女人街)。
    Google Map and Google Earth 22.315570, 114.171330 shows junction of Dundas Street and Tung Choi Street (女人街)。
    But the same co-ordinate on my Nokia Map E90 shows elsewhere for all the location above.
    Thank you.

    Peter...I hope you are still a moderator...you may be my last hope to help me - Toshiba do the right thing.
    I too have a C55 Satelitte laptop...acutally I purchased it for my 10 year old son. It is one month out of warranty. Last night for the first time, I used his toshiba laptop because I left mine at work. I notice his laptop had this same issue. I spent an hour reading on your forum and trying all the suggestions including the elaborate unplug, remove drivers etc in a particular order and it did not resolve the issue. Obviously this is a defect in this model. My son does not know enough about laptops to even recognize that it is an issue. I have had toshiba laptops for over a decade. I have never had this kind of an issue so I wouldnt even know to look if it was an issue initially.
    It wasnt until last night when I had to use his laptop that I identified this as an issue. No problem, I thought, I'll call tech support and they will do the right thing. No go. I escalated 3 levels and they held their line saying that batteries are consumable and only rated for one year. I have a seven year old toshiba that I use at work that doesnt hold a charge that long but still works!!! This does not work at all - 0%...obviously a defect that unfortuantely my son doesnt have the skill set to have recognized.
    Please Peter, if you are there...can you please see what you can do to have a new battery sent. They are 100.00 which is insulting to pay since it is clearly a defect for this model. Tech support even said as much.
    Any assistance would be greatly appreciated. I have purchased Toshiba laptops for my workplace for over a decade. I am shocked that they are unwilling to do the right thing.
    Thanks in advance.
    Cheryl

  • Calculating co-ordinate distances between specific atoms

    Hi,
    Below is some code to calculate distances between all pairs of atoms. However, i need to make it slightly more specific by only calculating the distance between certain pairs of atoms
    input
    ATOM 5 CA PHE 1 113.142 75.993 130.862
    ATOM 119 CA LEU 7 113.101 72.808 140.110
    ATOM 138 CA ASP 8 109.508 74.207 140.047
    ATOM 150 CA LYS 9 108.132 70.857 141.312
    ATOM 172 CA LEU 10 110.758 70.962 144.119
    e.g distance between all pairs for atoms 5, 119, 150 and 172 (say), last three columns are x,y and z co-ordinates
    code it self
    import java.util.*;
    import java.io.*;
    public class Distance {
    public static void main(String[] args) {
    System.out.println("***Campbells PDB Distance Calculator***" + "\n");
    new Distance();
    System.out.println("\nResults printed to file DistanceCalculations" + "\n");
    System.out.println("\nDue to nature of code, if rerun results will be appended to the end of previous run.");
    public Distance() {
    Vector atomArray = new Vector();
    String line;
    try{
    System.out.println("Enter PDB file:" + "\n");
    BufferedReader inputReader =new BufferedReader (new InputStreamReader(System.in));
    String fileName = inputReader.readLine();
    if ( fileName !=null) {
    BufferedReader inputDistance = new BufferedReader (new FileReader (fileName));
    while (( line = inputDistance.readLine()) !=null && !line.equals(""))
    Atom atom = new Atom(line);
    atomArray.addElement(atom);
    for (int j=0; j<atomArray.size(); j++) {
    for (int k=j+1; k<atomArray.size(); k++) {
    Atom a = (Atom) atomArray.elementAt(j);
    Atom b = (Atom) atomArray.elementAt(k);
    Atom.printDistance (a,b);
    } //if
    } //try
    catch (IOException e) {
    System.out.println("Input file problem");
    } catch (Exception ex) {
    System.out.println (ex);
    class Atom {
    public double x, y, z;
    public String name;
    public Atom(String s) throws IllegalArgumentException {
    try {
    StringTokenizer t = new StringTokenizer (s, " ");
    t.nextToken();
    this.name = t.nextToken();
    for (int j=0; j<3; j++) t.nextToken();
    this.x = new Double(t.nextToken()).doubleValue();
    this.y = new Double(t.nextToken()).doubleValue();
    this.z = new Double(t.nextToken()).doubleValue();
    catch (Exception ex) {
    throw new IllegalArgumentException ("Problem!!!! :-(");
    public String toString() {
    return "atom : " + name + "(x=" + x + " y=" + y + " z=" + z + ")";
    public double distanceFrom (Atom other) {
    return calculateDistance (x, y, z, other.x, other.y, other.z);
    public static double calculateDistance (double x1, double y1, double z1, double x2, double y2, double z2) {
    return Math.sqrt(Math.sqrt(Math.pow(Math.abs(x1-x2),2)+Math.pow(Math.abs(y1-y2),2))+Math.pow(Math.abs(z1-z2),2));
    public static void printDistance (Atom a, Atom b) {
    try{
    FileWriter fw = new FileWriter("DistanceCalculations", true);
    PrintWriter pw = new PrintWriter (fw, true);
    if
    (a.distanceFrom(b) <9){
    pw.println("Distance between " + a.toString() + " and " + b.toString() + " is " + a.distanceFrom(b));
    pw.flush();
    pw.close();
    } // if??
    } //try loop
    catch(IOException e) {
    System.out.println("System error");
    }

    ok, essentially
    want to calculate distance between to ranges. Say
    range 1 is the first three, range 2 the rest. THen
    calculate distance between all possible pairs between
    these two rangesYes - and no doubt that any number of people here could write it for you. But that's not what the forum is about. So what, exactly, is preventing you from doing it?
    Sylvia.

  • PageItem Co-ordinate w.r.t. Spread Co-ordinate System

    Hi All,<br /><br />I am trying to get coordinates of text frame with respect to spread co-ordinate system.<br />I have used following code for this:<br /><br />InterfacePtr<IGeometry> frameGeometry(textFrame, IID_IGEOMETRY);<br />PMRect frmRect = frameGeometry->GetPathBoundingBox();<br />::InnerToParent(textFrame, &frmRect);<br /><br />Here textFrame is the ITextFrame pointer of which I want to get coordiantes w.r.t. Spread. The problem is dimensions in frmRect doesnot change even after transformation using InnerToParent().<br /><br />Can anyone suggest me in this regard, where I am wrong?<br /><br />- Pete

    Hi Pete,
    I think your problem is that the parent of kMultiColumnItemBoss or kFrameItemBoss (the only bosses that could store the ITextFrame interface you start from) is kSplineItemBoss and not kSpreadBoss. With your call to TransformUtils::InnerToParent you are likely getting the coords in the spline item's coordinate space and not in the spread's one. The SDK documentation specifies that "The parent coordinate space is the first ancestor boss object on IHierarchy that has an IGeometry interface".
    HTH,
    Emanuele.

  • Problem in creating small box in sap script

    Hi,
    I am working on a sap script in which iwant to create a small on the right hand side of the footer of the script and also want to display the data in that box.
    plzzz provide me guidelines how to solve this problem.

    u can use the BOX command.
    The BOX command draws a box as per the specifications. The x , y co-ordinates are for the upper left corner with reference to the values in the position command. The Position command is used to set  x,y coordinates with respect to the start position.
    plz chk this link:
    how to display Lines and Boxes in SAP Script

  • Centering JFrame on desktop problem

    I have this code which centers JFrame on the desktop and which works fine only outside the constructor of the JFrame class. How can I make sure that the JFrame window is centered on the desktop when it opens?
    GraphicsConfiguration gc = this.getGraphicsConfiguration();
    Rectangle bounds = gc.getBounds();
    int x = (int) ( bounds.getWidth() - this.getWidth() ) /2 ;
    int y = (int) ( bounds.getHeight() - this.getHeight() ) /2;
    this.setLocation( x, y );
    The problem is that at "constructor time" the width and height are 0 (in this.getWidth and this.getHeight methods of JFrame).
    any alternative to make it work?
    thanks

    I order to center the JFrame you can always get the screen size then simply set it's bounds e.g.
    java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
    Dimension scrSize = tk.getScreenSize();
    Then depending on it's size determine the size you want the JFrame, and calculate the x, y co-ordinates. Making the size a fraction of the screen size, is easy to center e.g.
    youJFrame.setBounds((int)(scrSize.getWidth()-(scrSize.getWidth()*.75)), (int)(scrSize.getHeight()-((int)scrSize.getHeight()*.75)),
    (int)(scrSize.getWidth()*0.5), (int)(scrSize.getHeight()*0.5));

  • Latitude and longitude co-ordinates not appearing correctly

    I am trying to allocate a 'place' to a photograph by inputting the latitude and longitude. The place is 'The Needles" at the extreme western point of the Isle of Wight, the co-ordinates being 50.3973N and 01.3552W. However, when I enter these co-ordinates in the format as indicated in the 'help' section of iphoto (i.e. 50.3973, 01.3552), the place comes up somewhere off the coast of France in the English Channel! Can anyone please advise me if I am not entering the numbers correctly or is there a problem with iphoto?

    When I show extended photo info on a photo that is correctly positioned it displays as
    GPS Latitude l.llllll˚ N
    GPS longitude n.nnnnn˚ W
    Have you tried with a space between the digits and the N or W?
    Also you might try experimenting with adding a minus sign to one or the other of the fields although that does not sound correct off the top of my head
    If you have a photo that is correctly located there you can use HoudahGeo - http://www.houdah.com/houdahGeo/ - to locate the rest of the photos from the correct photo's location - this is a very useful function to take lots of photos with a non GPS camera and take one with your iPhone and use its location for the others
    LN

  • RTF Template formatting problem

    Hi,
    I am designing a report layout using MS Word.
    The report format is like this
    Employee: EmpID                           Date of Joining: DOJ
    Employee Name: Ename                      Department     : DeptThe problem is that when i generate pdf preview, when the size of EmpId or Ename increases DOj and Dept shifts to further right
    eg
    Employee: 1                           Date of Joining: 12-Oct-2000
    Employee Name: Scott                  Department    : Accounting
    Employee: 123                                     Date of Joining: 12-Oct-2000
    Employee Name: John Smith                             Department    : SalesIs there any way that i can fix the prompts/labels from shifting depending upon the size of the data?
    I am using fields option to insert fields insert --> Fields
    Thanks and Regards
    AT

    Exactly,
    Your understanding of Free format report is different,
    to align to the output you need, you have to use the microsoft word options available,
    if you dont want that,
    you got to create xsl template , which is going to some declarative syntax, where you got to give the exact positions and coordinates of each field, which will be difficlut
    so by putting this table from word ,your work of giving the declarative co-ordinates is highly reduced for each field.

  • 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();

  • Please Help : Big problem with applets

    Hi,
    I have a big problem which I have not been able to figure out. The applet I have enclosed works fine on some computers but not on others .
    I am running :
    java version "1.3.1_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_02-b02)
    Java HotSpot(TM) Client VM (build 1.3.1_02-b02, mixed mode)
    The applet runs perfectly Ok at university but not on other computers.
    The objective of the applet is to display 3 shapes on the screen once. On the university computer it works, however at home and work the 3 shapes are continuously displayed on the screen ( like they are in some infinite loop). I have been struggling with this for days any help would be greatly appreciated.
    It would help me if some of you could run this applet and let me know if the shapes are displayed once or if the shapes are continuously updated on the screen ( assuming that the applet window is not resized covered over etc. )
    =========================================
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /*<html><applet code = "stage1.class" height = "600" width="810"></applet></html>*/
    public class stage1 extends JApplet{
    JPanel extraPanel = new JPanel();
    public void init()
    Container c = getContentPane();
    extraPanel.setBackground (Color.white);
    extraPanel.setLayout (new FlowLayout());
    c.add(extraPanel);
    public void paint (Graphics g)
    //super.paint( g ); // call superclass's paint method
    // populate the two dimensional array - store the coordinates for the circle and square shapes
    int circle[][] = { {100,100,200,200}, // display circle in the left hand side of the screen
    {350,100,200,200}, // display circle in the middle of the screen
    {600,100,200,200} }; // display circle in the right hand side of the screen
    int rect[][] = { {100,100,200,200}, // display square in the left hand side of the screen
    {350,100,200,200}, // display square in the middle of the screen
    {600,100,200,200} }; // display square in the right hand side of the screen
    // populate the two dimensional array - store the coordinates for the polygon shapes
    int polyX[][] = { {150,250,300,250,150,100 }, // display polygon in the left hand side of the screen
    {400,500,550,500,400,350 }, // display polygon in the middle of the screen
    {650,750,800,750,650,600} }; // display polygon in the right hand side of the screen
    int polyY[] = { 100,100,200,300,300,200    }; // the "Y" co-ordinates wont change for all three polygons
    int xCoordinates[] = new int[ 6 ];
    int pickAShape
    , pickAColour
    , polygonCount = 0
    , circleCount = 0
    , squareCount = 0
    , redCount = 0
    , greenCount = 0
    , blueCount = 0
    , yellowCount = 0 ;
    for ( int position = 0;position < 3;position++ )
    pickAShape = 1 + ( int )( Math.random() * 3 );
    pickAColour = 10 + ( int )( Math.random() * 4 );
    switch ( pickAShape )
    case 1: // draw a circle
    switch ( pickAColour )
    case 10:
    g.setColor( Color.red );
    redCount++;
    break;
    case 11:
    g.setColor( Color.green );
    greenCount++;
    break;
    case 12:
    g.setColor( Color.blue );
    blueCount++;
    break;
    case 13:
    g.setColor( Color.yellow );
    yellowCount++;
    break;
    g.fillOval( circle[position][0],circle[position][1],circle[position][2],circle[position][3] );
    circleCount++;
    break;
    case 2: // draw a rectangle
    switch ( pickAColour )
    case 10:
    g.setColor( Color.red );
    redCount++;
    break;
    case 11:
    g.setColor( Color.green );
    greenCount++;
    break;
    case 12:
    g.setColor( Color.blue );
    blueCount++;
    break;
    case 13:
    g.setColor( Color.yellow );
    yellowCount++;
    break;
    g.fillRect(rect[position][0],rect[position][1],rect[position][2],rect[position][3] );
    squareCount++;
    break;
    case 3: // draw a polygon
    switch ( pickAColour )
    case 10:
    g.setColor( Color.red );
    redCount++;
    break;
    case 11:
    g.setColor( Color.green );
    greenCount++;
    break;
    case 12:
    g.setColor( Color.blue );
    blueCount++;
    break;
    case 13:
    g.setColor( Color.yellow );
    yellowCount++;
    break;
    xCoordinates[0]=polyX[position][0];
    xCoordinates[1]=polyX[position][1];
    xCoordinates[2]=polyX[position][2];
    xCoordinates[3]=polyX[position][3];
    xCoordinates[4]=polyX[position][4];
    xCoordinates[5]=polyX[position][5];
    Polygon polygonInstance = new Polygon ( xCoordinates, polyY, 6 );
    g.fillPolygon( polygonInstance );
    polygonCount++;
    break;
    // display the results
    setFont(new Font("Serif",Font.BOLD,24));
    g.setColor(Color.black);
    if ((circleCount ==3 || squareCount ==3 || polygonCount==3) && (redCount ==3 || greenCount ==3 || blueCount==3 || yellowCount ==3))
    g.drawString( "YOU WIN !!!!" ,380,400 );
    else
    g.drawString( "YOU LOSE !!!!",380,400 );
    } // end method paint
    } // end class stage4
    =========================================
    Regards and thanks

    O.K. You will not believe this, but the problem will be solved if you change the following line from:
        setFont(new Font("Serif",Font.BOLD,24));to:
        g.setFont(new Font("Serif",Font.BOLD,24));Now, since I am also learning JAVA, the way I went about solving was to create your applet from scratch, using cut and paste, and running it piece by piece till I ran into the flashing display. Took me a while. I am enclosing my version of the program for your comments.
    import java.awt.*;
    import java.applet.*;
    public class Slotto extends Applet {
        int circle[][] = { {100,100,200,200}, // circle in the left hand side of the screen
                           {350,100,200,200}, // circle in the middle of the screen
                           {600,100,200,200} }; // circle in the right hand side of the screen
        int rect[][] = { {100,100,200,200}, // square in the left hand side of the screen
                         {350,100,200,200}, // square in the middle of the screen
                         {600,100,200,200} }; // square in the right hand side of the screen
        int polyX[][] = { {150,250,300,250,150,100 }, // polygon in the left hand side of the screen
                          {400,500,550,500,400,350 }, // polygon in the middle of the screen
                          {650,750,800,750,650,600} }; // polygon in the right hand side of the screen
        int polyY[] = { 100,100,200,300,300,200 }; // the "Y" co-ordinates wont change for all three polygons
        int xCoordinates[] = new int[ 6 ];
        int pickAShape
        , pickAColour
        , polygonCount = 0
        , circleCount = 0
        , squareCount = 0
        , redCount = 0
        , greenCount = 0
        , blueCount = 0
        , yellowCount = 0
        , position ;
        public void paint(Graphics g) {
            for (position = 0; position < 3; position++) {
                chooseColor(g);
                drawTheShape(g);
            declareResults(g);
        public void chooseColor(Graphics g) {
            pickAColour = 10 + ( int )( Math.random() * 4 );
            switch ( pickAColour )
                case 10:
                    g.setColor( Color.red );
                    redCount++;
                    break;
                case 11:
                    g.setColor( Color.green );
                    greenCount++;
                    break;
                case 12:
                    g.setColor( Color.blue );
                    blueCount++;
                    break;
                case 13:
                    g.setColor( Color.yellow );
                    yellowCount++;
                    break;
        public void drawTheShape(Graphics g) {
            pickAShape = 1 + ( int )( Math.random() * 3 );
            switch ( pickAShape )
                case 1: // draw a Circle
                    g.fillOval( circle[position][0],
                                circle[position][1],
                                circle[position][2],
                                circle[position][3] );
                    circleCount++;
                    break;
                case 2: // draw a Square
                    g.fillRect(rect[position][0],
                               rect[position][1],
                               rect[position][2],
                               rect[position][3] );
                    squareCount++;
                    break;
                case 3: // draw a Polygon
                    xCoordinates[0]=polyX[position][0];
                    xCoordinates[1]=polyX[position][1];
                    xCoordinates[2]=polyX[position][2];
                    xCoordinates[3]=polyX[position][3];
                    xCoordinates[4]=polyX[position][4];
                    xCoordinates[5]=polyX[position][5];
                    Polygon polygonInstance = new Polygon ( xCoordinates,
                                                            polyY, 6 );
                    g.fillPolygon( polygonInstance );
                    polygonCount++;
                    break;
        public void declareResults(Graphics g) {
            g.setFont(new Font("Serif",Font.BOLD,24));
            g.setColor(Color.black);
            if ((circleCount ==3 || squareCount ==3 || polygonCount==3)
             && (redCount ==3 || greenCount ==3 || blueCount==3 || yellowCount ==3))
                g.drawString( "YOU WIN !!!!" ,380,400 );
            else
                g.drawString( "YOU LOSE !!!!",380,400 );
    }Regards.

  • Y-intercept calculation problem: "A2:A7" isn't a valid reference

    This is actually a problem I have with many calculations in Numbers but I will use the following as an example:
    I am trying to calculate the y-intercept and slope for a set of data. Table 1 contains the raw data with each data point in triplicate. In Table 2, column 1 is the ordinate value and column 2 is the abscissa value, which is the average of the triplicates. I would like to place the calculation for the y-intercept in column 3 and the slope in column 4, but always get the error, "A2:A7" isn't a valid reference" for a result. Instead, I have to have a third table for just the y-int and slope. Why isn't A2:A7 a valid reference?

    No, I didn't; I only had a 5 rows but I made it 7 rows - so it was a 4 column x 7 row table - and then the formulas worked. The odd thing is that there was still only data in the first 5 rows and, after I set up the formulas, I reduced the table back to 4x7 and the formulas remained unchanged. Thanks for the help.

Maybe you are looking for

  • When I try and add a video from my iPhone it fails to load with a generic error. How do I fix this?

    I have been trying unsuccessfully to get a video from my iPhone to load.  It plays just fine on windows media player, but every one I try and add on Adobe gives me the same "Add media failure.  The importer reported a generic error."  what do I do to

  • Pdf black background

    I am importing some PDF files into Aperture. This works as expected except the background is black, meaning that any text appears as a black block. Here's an example of what happens: There is a big block of text on the left side of the page. Is there

  • Activity report in REM for each document posting

    Dear All, Please help me with , how to get the Activity report for each & every for  MFBF document posted. BR, Subbu.

  • Should I buy a new battery from a third party vendor?

    Hello, I am totally new to this portion of support and to the world of laptops so please bear with me for a moment. I don't think I need a new battery yet but I did some research on-line and the general consensus seems to be that Apple and batteries

  • ERROR-1079 Error in item post calculation computation

    hi, We are getting this error when the user is clicking on a "Submit" button. Below the error there is an Oracle -20000 (ORA-01422) error is getting displayed. In order to debug the issue i need to understand a way of knowing the underlying database