Class of an rectangle

hi,
all I´m trying to do is create a class representing a rectangle, so when I create an instance of this class, it would draw a rectangle ...
please help, I know this is a very basic question, but I am a beginner ...
thanks

The method draw(Shape s) is not part of the Graphics class but rather is part of the newer Graphics2D class. Note that Graphics objects returned from the paintComponent method are Graphics2D objects, but to get this functionality, you must first cast the returned Graphics object into a Graphics2D object:
public void paintComponent(Graphics g){
   Graphics2D g2 = (Graphics2D)g;
   g2.draw(new Spalicek(10, 10, 100, 100));
}Having said this, I recommend against creating new objects from within a paint or paintComponent method as these methods must be as fast as possible. Better would be to create the object outside of the paintComponent method but use it from within it:
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class NakresliSpalicek extends JPanel{
  Spalicek myRect = new Spalicek(10, 10, 100, 100);
@Override
public void paintComponent(Graphics g){
   Graphics2D g2 = (Graphics2D)g;
   g2.draw(myRect);
}

Similar Messages

  • How can I hide a property in a derived class

    For Example
    Class Rectangle
    Private dLength, dBreadth as Double
    Sub new(Byval Length as Double, Byval Breadth as Double)
    dlength = length dbreadth = breadth
    end Sub
    Public Readonly Property Length as Double
    return dlength
    end property
    Public Readonly Property Breadth as Double
    return dbreadth
    end property
    Public Property Area as Double
    return dLength * dBreadth
    end Property
    End Class
    Class Square
    Inherits Rectangle
    Sub New(Byval Length as Double)
    Mybase.new(Length, Length)
    end sub
    ' I want to hide the breadth property here.
    ' Only length should be visible.
    end Class
    How can I implement this in VB?

    Hello,
    I agree with Frank, this goes against the concepts of OO. If you really wanted to it can be done yet would highly recommend rethinking your reasoning and design. The following is how it can be done but it should not be done.
    Imports System.ComponentModel
    Class Rectangle
    Private dLength, dBreadth As Double
    Sub New(ByVal Length As Double, ByVal Breadth As Double)
    dLength = Length
    dBreadth = Breadth
    End Sub
    Public ReadOnly Property Length As Double
    Get
    Return dLength
    End Get
    End Property
    <Browsable(False), EditorBrowsable(EditorBrowsableState.Never)> _
    Public ReadOnly Property Breadth As Double
    Get
    Return dBreadth
    End Get
    End Property
    Public ReadOnly Property Area As Double
    Get
    Return dLength * dBreadth
    End Get
    End Property
    End Class
    Class Square
    Inherits Rectangle
    Sub New(ByVal Length As Double)
    MyBase.New(Length, Length)
    End Sub
    ' I want to hide the breadth property here.
    ' Only length should be visible.
    End Class
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • How to register mouselistener for custom class?

    i m trying to create a custom class (extending java.awt.Rectangle)which responds to mouse gestures.
    i m using it as an object on my drawpad which responds to mouse behavior
    like rollover.
    the rollover color change is achieved using canvas' graphics object triggerd by my cutom class
    i m not able to register a mouseevent for the custom class.
    can someone help me in achieving this?
    thanks in advance
    z_idane

    Something like this? Don't think I'd be likely to extend Rectangle, myself, but anyway...
    public class HotSpot extends Rectangle implements MouseMotionListener
        private boolean hover = false;
        // add constructors to taste
        public void mouseMoved(MouseEvent e)
            if (this.hover != (contains(e.getX(), e.getY())
                this.hover = ! this.hover;
                if (this.hover)
                    // "mouse enter" code here
                else
                    // "mouse exit" code here
        public void mouseDragged(MouseEvent e)
    }Obviously you'd need something like this elsewhere,
    myDrawingPad.addMouseMotionListener(new HotSpot(...));

  • XMLEncoding of a custom class

    I'm trying to save game levels as XML code using the XMLEncoder. I've made getters and setters for every attribute and a no-arg constructor, but still some attributes are missing in the XML code. I've spent a LOT of time reading about different XML APIs, without learning anything to help me.
    I've made a TestClass to illustrate the problem:
    public class TestClass {
        private Polygon polygon;
        private Rectangle rectangle;
        public TestClass() {
            polygon = new Polygon();
            rectangle = new Rectangle();
        public Polygon getPolygon() {
            return polygon;
        public void setPolygon(Polygon polygon) {
            this.polygon = polygon;
        public Rectangle getRectangle() {
            return rectangle;
        public void setRectangle(Rectangle rectangle) {
            this.rectangle = rectangle;
    }The code to encode a TestClass object:
    public class XMLProcessor {
        public static void main(String[] args) {
            TestClass tc = new TestClass();
            Polygon p = new Polygon();
            p.addPoint(5, 6);
            p.addPoint(7, 8);
            tc.setPolygon(p);
            Rectangle r = new Rectangle();
            r.setBounds(1, 1, 10, 10);
            tc.setRectangle(r);
            try {
                XMLEncoder e = new XMLEncoder(new FileOutputStream("Test.xml"));
                e.writeObject(tc);
                e.close();
            } catch(Exception e) {
                System.out.println(e);
    }This produces the following XML document:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="xmltest.TestClass">
      <void property="rectangle">
       <object class="java.awt.Rectangle">
        <int>1</int>
        <int>1</int>
        <int>10</int>
        <int>10</int>
       </object>
      </void>
    </object>
    </java>As you can see, the polygon is missing, although it has a set- and get-method. The encoding also works for java.awt.Point, but not for java.awt.Point2D.
    What can I do to fix this?

    Set a PersistenceDelegate?

  • Test rectangle

    need to modify the source code
    can't compile
    nedd to change the method.
    Urgent!
    below is the source code
    * TestRectangle.java
    * Version:
    * $Id:$
    * Revisions:
    * $Log:$
    import javabook.*;
    * A test class for the Rectangle class.
    class TestRectangle {
    * Main method for program.
    * @param args command line arguments (ignored)
    public static void main( String args[] ) {
         MainWindow win; // The main display window
         InputBox input; // User input
         OutputBox output; // Output to user
         double length, width; // length and width of the rectangle
         Rectangle aRectangle; // The rectangle to test
         // Create the main window and display it
         win = new MainWindow( "Lab 3 - TestRectangle program" );
         win.setVisible( true );
         // Create an input box and get the length and width
         input = new InputBox( win );
         length = input.getFloat( "Enter rectangle length:" );
         width = input.getFloat( "Enter rectangle width:" );
         // Create the corresponding rectangle
         aRectangle = new Rectangle( length, width );
         // Create the output window and display the results
         output = new OutputBox( win );
         output.setVisible( true );
         output.printLine( "Testing " + length + " x " + width
                   + " rectangle:" );
         output.skipLine( 1 );
         output.printLine(
    " Perimeter should be = " + ( ( length * 2 ) + ( width * 2 ) ) );
         output.printLine(
    " The perimeter is: " + aRectangle.getPerimeter() );
         output.skipLine( 1 );
         output.printLine( " Area should be = " + length * width );
         output.printLine( " The area is: " + aRectangle.getArea() );
    } // TestRectangle

    Another urgent homework problem!!
    Coudl you atleast post the error message. And which method do you need to change? The only method here is main()

  • Trying to make a square class

    hi i am trying to write a class that creates a square but it has to use to use the rectangle package so far i get an error cannot not find symbol on this line square = new Rectangle(0,0); and i get errors when i return my x and y variables if anyone has any ideas please i need some help thank you
    import java.awt.Rectangle;
    public class square
         private int length;
      private int width;
         public square ()
              square   = new Rectangle(0,0);
         public square (int length, int width)
             square = new Rectangle(0,0,length, width);
             this.length = length;
              this.width = width;
          /*Constructor:*/
        public square(int x, int y, int length, int width)
              square = new Rectangle(x, y, width, length);
                 this.length = length;
             this.width = width;
      public int getLength()
        return length;
      public int getWidth()
        return width;
      public int getX()
           return x;
      public int getY()
           return y;
      public void setBounds()
      return side;
    }

    You realize that by definition a square has equal sides? You don't need a width or a height, you just need a length. My "Square" class would only have a getLength() method and possibly setLength() if you want it to be mutable. If this is intended for use with AWT you could subclass Rectangle and guarantee that all sides are equal. Given your current design it would be trivially easy for me to create a Square that is in fact not a square at all.
    public class Square {
        private Rectangle rect;
        public Square(int x, int y, int length) {
            super();
            rect = new Rectangle(x, y, length, length);
        public Rectangle getRectangle() {
            return rect;
    }Of course, they could easily modify that Rectangle to make it not be a Square anymore. You could change the code to make a defensive copy. Then they could change the Rectangle, but it wouldn't affect you, so your Square would always return a square even if they made the returned Rectangle not a square at some later point. You'd do that like so:
      * Returns a square rectangle.  The returned Rectangle is mutable
      * and as such it could be mutated to no longer be a square.  It is the
      * responsibility of the client to ensure this does not happen.  Each
      * returned Rectangle is unique and mutations in one will not affect
      * the others.
      * @return A Rectangle that is a perfect square.
    public Rectangle getRectangle() {
        return new Rectangle(rect);
    }You could subclass Rectangle, but it's internals are exposed so you couldn't ever guarantee your Square was a square. Alternatively it looks like you could subclass Rectangle2D or RectangularShape and just be sure to override anything that could mutate your Square into something not a square. Also, you could just implement the Shape interface if that suits your purposes.
    Just some things to think about.

  • I am trying to add one rectangle into another container rectangle

    However, only the container shows up. Here is my code:
    Rectangle.java
    /** Rectangle Supplier Class
    * Author: David D. Riley modified by Deborah WHitfield
    * Date: April, 2004
    public class Rectangle extends JComponent {
         private static final long serialVersionUID = 1L;
         /** post: getX() == x and getY() == y
    * and getWidth() == w and getHeight() == h
    * and getBackground() == Color.black
         public Rectangle(int x, int y, int w, int h) {
    super();
              setBounds(x, y, w, h);
    setBackground(Color.black);
    /** post: this method draws a filled Rectangle
    * and the upper left corner is (getX(), getY())
    * and the rectangle's dimensions are getWidth() and getHeight()
    * and the rectangle's color is getBackground()
    public void paint(Graphics g) {
    g.setColor( getBackground() );
    g.fillRect(0, 0, getWidth()-1, getHeight()-1);
    repaint();
    // paintChildren(g);
    digit.java
    import javax.swing.JFrame;
    import java.awt.Color;
    public class digit {
         private Rectangle topLeft, top, topRight, mid, bottomLeft, bottom, bottomRight, container;
         public digit(JFrame window, int x, int y) {
              container = new Rectangle(x, y, 125, 175);
              container.setBackground(Color.white);
              container.setVisible(true);
              topLeft = new Rectangle(0, 0, 50, 50);
              topLeft.setBackground(Color.red);
              container.add(topLeft,0);
              window.add(container,0);
    lastly, Driver.java
    import java.awt.Color;
    import javax.swing.JFrame;
    public class Driver {
         private JFrame window;
         public static void main(String [] args){
              JFrame window = new JFrame ("Window");
              window.setBounds(30, 100, 800, 800);
              window.setVisible(true);
              digit d1 = new digit(window, 50, 50);
              digit d2 = new digit(window, 300, 50);
              digit d3 = new digit(window, 450, 50);
              Rectangle colon1 = new Rectangle(225, 70, 40, 50);
              Rectangle colon2 = new Rectangle(225, 145, 40, 50);
              window.add(colon1);
              window.add(colon2);
              colon1.setBackground(Color.black);
              colon2.setBackground(Color.black);
              window.repaint();
    Any help you can give me is greatly appreciated. Thanks!

    Do me a favor just to humor me. Delete his paint() method override and substitute a paintComponent override that looks like so:
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g.setColor(getBackground());
            g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
            //repaint();
            // paintChildren(g);
        }Let me know what happens.

  • Draw rectangle

    Hi,I want to use mouse to draw a rectangle.But my code doesn't work.Could anyone have a look and make it work please?Heaps of thanks!
    import javax.swing.JInternalFrame;
    import java.awt.Cursor;
    import java.io.File;
    //for inner class
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseEvent;
    import java.awt.Point;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Shape;
    import java.awt.Rectangle;
    import java.awt.Color;
    import java.awt.Container;
    import javax.swing.JFrame;
    * Testing drawing rectangle
    public class TestDraw extends JInternalFrame
    private Container c;
    public TestDraw(String name) {
    super(name,true,true,true,true);
    //Set the window size or call pack...
    setSize(300,300);
    c = this.getContentPane();
    c.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    c.addMouseListener(new MouseMonitor(this));
    setVisible(true);
    }//End of constructor
    public static void main(String[] args)
    TestDraw td = new TestDraw("test");
         TestGUI tg = new TestGUI(td);
    private static class TestGUI extends JFrame
         public TestGUI(JInternalFrame jif)
              setBounds(100,100,400,400);
              Container c = getContentPane();
    c.add(jif);
    setVisible(true);
    /********************MouseMonitor INNER CLASS********************/
         private class MouseMonitor extends MouseAdapter
              private int clickedX,clickedY,releasedX,releasedY;
              private JInternalFrame j;
              public MouseMonitor(JInternalFrame ji)
    this.j = ji;
              public void mouseClicked(MouseEvent event)
              clickedX = event.getX();
              clickedY = event.getY();
              }//End of mouseClicked()
              public void mouseReleased(MouseEvent event)
                   releasedX = event.getX();
                   releasedY = event.getY();
    System.out.println("clickedX="+clickedX);
    System.out.println("clickedY="+clickedY);
    System.out.println("releasedX="+releasedX);
    System.out.println("releasedY="+releasedY);
    Node node = new Node(clickedX,clickedY,releasedX,releasedY);
    node.setColor(Color.RED);
                   j.paintComponent(node);
                   j.repaint();
                   j.validate();
    /********************Node INNER CLASS********************/
    class Node extends Rectangle
    private Color color;
    private int left, top, width, height;
    public Node( int x, int y, int width, int height)
    setBounds(x, y, width, height);
    repaint();
    void setColor(Color color) {
    // Set the color of this shape
    this.color = color;
    public void setBounds(int left, int top, int width, int height) {
    // Set the position and size of this shape.
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
    void draw(Graphics g) {
    g.setColor(color);
    g.fillRect(left,top,width,height);
    g.setColor(Color.black);
    g.drawRect(left,top,width,height);
    /**************************END INNER CLASS**********************/
              public void paint(Graphics g)
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setPaint(Color.red);
                   g2.draw3DRect(clickedX,clickedY,releasedX,releasedY,true);
    }

    Fabulous program!
    I'd like to add more function,but stuck at the right click when the mouse pointing to the node.I want to show the popup menu when user right-clicks at the node,but show error message when he left-click(means he try to draw another node on the top of that node).
    The program seems act properly when mouse is pressed,but error dialog pops and blocks the mouseReleased action.Thanks in advance!
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JMenuItem;
    public class ShapeFrame1 extends JInternalFrame {
         private List<Node> nodes;
         private Node selected;
         private Point start;
         private boolean drawing;
         public static void main(String[] args) {
              ShapeFrame1 sf = new ShapeFrame1("Shape Test");
              JFrame frame = new JFrame("Shape Test");
              frame.setBounds(100,100,640,480);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(sf);
              sf.pack();
              sf.setVisible(true);
              frame.setVisible(true);
         public ShapeFrame1(String title) {
              super(title,true,true,true,true);
              setContentPane(new NodePanel());
              nodes = new ArrayList<Node>();
              getContentPane().addMouseListener(new MouseMonitor());
              getContentPane().addMouseMotionListener(new MouseMonitor());
         protected Node createNode(Point start, Point end) {
              return new Node(start.x, start.y,end.x - start.x, end.y - start.y, Color.BLACK);
         protected Node getNodeAt(Point location) {
              for(Node node : nodes)
                   if(node.contains(location))
                        return node;
              return null;
         class NodePanel extends JPanel {
              public void paintComponent(Graphics g) {
                   for(Node node : nodes)
                        node.paint(g);
                   if(drawing) { // User is currently drawing
                        Graphics2D g2 = (Graphics2D)g;
                        g2.setColor(Color.BLUE);
                        g2.draw(createNode(start, getMousePosition()));
                   else if (start != null){
         class Node extends Rectangle {
              private Color color;
              private String name;
              Node(int x, int y, int width, int height, Color color) {
                   super(x, y, width, height);
                   this.color = color;
              public void paint(Graphics g) {
                   Graphics2D g2 = (Graphics2D)g;
                   if(selected != null && selected.equals(this))
                        g2.setColor(Color.BLUE);
                   else
                        g2.setColor(color);
                   g2.draw(this);
              void setName(String n){
                   this.name = n;
              String getName(){
                   return this.name;
         class MyPopupMenu extends JPopupMenu{
              MyPopupMenu(){
                   createDefaultMenuItem(this);
              private void createDefaultMenuItem(JPopupMenu popup) {
                   JMenuItem item;
                   item = new JMenuItem("cut");
                   popup.add(item);
                   item = new JMenuItem("copy");
                   popup.add(item);
                   item = new JMenuItem("paste");
                   popup.add(item);
                   popup.addSeparator();
                   item = new JMenuItem("Add Node Name");
                   popup.add(item);
         class MouseMonitor extends MouseAdapter implements MouseMotionListener {
              private MyPopupMenu popup = new MyPopupMenu();
              public void mousePressed(MouseEvent evt) {
                   checkPopup(evt);
                   Node node = getNodeAt(evt.getPoint());
                        if (node != null)
                             JOptionPane.showMessageDialog(
                                   new JFrame(),
                              "Node exists.Please choose another location!",
                              "ERROR",
                              JOptionPane.ERROR_MESSAGE);
                        else
                             start = evt.getPoint();
              public void mouseReleased(MouseEvent evt) {
                   checkPopup(evt);
                   if(drawing) {
                        Node node = createNode(start, evt.getPoint());
                        nodes.add(node);
                        setCursor(Cursor.getDefaultCursor());
                        drawing = false;
                   } else {
                        // User isn't drawing, so select a Node if there is one
                        Node node = getNodeAt(evt.getPoint());
                        selected = node;
                   repaint();
              public void mouseMoved(MouseEvent evt) {}
              public void mouseDragged(MouseEvent evt) {
                   drawing = true;
                   setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                   repaint(); // User is currently drawing, so repaint the view
              private void checkPopup(MouseEvent evt){
                   if (evt.isPopupTrigger()){
                        popup.show(evt.getComponent(),evt.getX(),evt.getY());
    }

  • Help me to Edit this program

    Hi All,
    Can anyone kind enought to help me to add the START and STOP button for this "bouncing ball" program that i got from the internet ? Below is the java coding.
    import java.awt.*;
    import java.applet.*;
    class Obstacle
         public Rectangle r;
         Graphics g;
         public Obstacle(int x,int y,int w,int h)
              r=new Rectangle(x,y,w,h);
         public void paint(Graphics gr)
              g=gr;
              g.setColor(Color.lightGray);
              g.draw3DRect(r.x,r.y,r.width,r.height,true);
    class CollideBall
         int width, height;
         public static final int diameter=20;
         //coordinates and value of increment
         double x, y, xinc, yinc, coll_x, coll_y;
         boolean collide;
         Color color;
         Graphics g;
         Rectangle r;
         //the constructor
         public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c)
              width=w;
              height=h;
              this.x=x;
              this.y=y;
              this.xinc=xinc;
              this.yinc=yinc;          
              color=c;          
              r=new Rectangle(150,80,130,90);
         public double getCenterX() {return x+diameter/2;}
         public double getCenterY() {return y+diameter/2;}
         public void alterRect(int x, int y, int w, int h)
              r.move(x,y);
              r.resize(w,h);
         public void move()
              if (collide)
                   double xvect=coll_x-getCenterX();
                   double yvect=coll_y-getCenterY();
                   if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
                        xinc=-xinc;
                   if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
                        yinc=-yinc;
                   collide=false;
              x+=xinc;
         y+=yinc;
              //when the ball bumps against a boundary, it bounces off
         if(x<6 || x>width-diameter)
              xinc=-xinc;
                   x+=xinc;
              if(y<6 || y>height-diameter)
              yinc=-yinc;
                   y+=yinc;
              //cast ball coordinates to integers
              int x=(int)this.x;
              int y=(int)this.y;
              //bounce off the obstacle
              //left border
              if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height)
              xinc=-xinc;
                   x+=xinc;
              //right border
              if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height)
              xinc=-xinc;
                   x+=xinc;
              //upper border
              if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width)
                   yinc=-yinc;
                   y+=yinc;
              //bottom border
              if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width)
                   yinc=-yinc;
                   y+=yinc;
         public void hit(CollideBall b)
              if(!collide)
                   coll_x=b.getCenterX();
                   coll_y=b.getCenterY();
                   collide=true;
         public void paint(Graphics gr)
              g=gr;
              g.setColor(color);
              //the coordinates in fillOval have to be int, so we cast
              //explicitly from double to int
              g.fillOval((int)x,(int)y,diameter,diameter);
              g.setColor(Color.white);
              g.drawArc((int)x,(int)y,diameter,diameter,45,180);
              g.setColor(Color.darkGray);
              g.drawArc((int)x,(int)y,diameter,diameter,225,180);
    public class BouncingBalls extends Applet implements Runnable
         Thread runner;     
         Image Buffer;
    Graphics gBuffer;          
    CollideBall ball[];
         Obstacle o;
    //how many balls?
    static final int MAX=10;
         boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
         boolean shiftNW,shiftSW,shiftNE,shiftSE;
         int xtemp,ytemp,startx,starty;
         int west, north, east, south;
         public void init()
              Buffer=createImage(size().width,size().height);
              gBuffer=Buffer.getGraphics();                         
              ball=new CollideBall[MAX];
              int w=size().width-5;
              int h=size().height-5;          
              //our balls have different start coordinates, increment values
              //(speed, direction) and colors
              ball[0]=new CollideBall(w,h,50,20,1.5,2.0,Color.orange);
    ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
    ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
    ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
    ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
              ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
              ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
              ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
              ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
              ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
              o=new Obstacle(150,80,130,90);
              west=o.r.x;
              north=o.r.y;
              east=o.r.x+o.r.width;
              south=o.r.y+o.r.height;
         public void start()
              if (runner == null)
                   runner = new Thread (this);
                   runner.start();
    public void stop()
              if (runner != null)
         runner.stop();
         runner = null;
         public void run()
              while(true)
                   Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
                   try {runner.sleep(15);}
         catch (Exception e) { }               
                   //move our balls around
                   for(int i=0;i<MAX;i++)
                        ball.move();
                   handleCollision();
                   repaint();     
         boolean collide(CollideBall b1, CollideBall b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //we calculate the distance between the centers two
              //colliding balls (theorem of Pythagoras)
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.diameter)                         
                   return true;          
                   return false;     
         void changeCursor(int x, int y)
              Rectangle r=new Rectangle(o.r.x+1,o.r.y+1,o.r.width-1,o.r.height-1);
              Frame BrowserFrame;
              Component ParentComponent;
              ParentComponent = getParent();
              while ( ParentComponent != null &&
              !(ParentComponent instanceof Frame))           
              ParentComponent = ParentComponent.getParent();          
              BrowserFrame = (Frame) ParentComponent;
              if(shiftNW||shiftSE)
                   BrowserFrame.setCursor(Frame.SE_RESIZE_CURSOR);
              else if(shiftNE||shiftSW)
                   BrowserFrame.setCursor(Frame.SW_RESIZE_CURSOR);
              else if(shiftW)
                   BrowserFrame.setCursor(Frame.W_RESIZE_CURSOR);
              else if(shiftN)
                   BrowserFrame.setCursor(Frame.N_RESIZE_CURSOR);
              else if(shiftE)
                   BrowserFrame.setCursor(Frame.W_RESIZE_CURSOR);
              else if(shiftS)
                   BrowserFrame.setCursor(Frame.N_RESIZE_CURSOR);
              else if(r.inside(x,y))
                   BrowserFrame.setCursor(Frame.MOVE_CURSOR);
              else
                   BrowserFrame.setCursor(Frame.DEFAULT_CURSOR);
         public boolean mouseMove(Event evt,int x,int y)
              //the corner areas of the obstacle
              Rectangle nw,sw,ne,se;
              nw=new Rectangle(o.r.x-2,o.r.y-2,4,4);
              if(nw.inside(x,y))
                   shiftNW=true;
              else shiftNW=false;
              sw=new Rectangle(o.r.x-2,o.r.y+o.r.height-2,4,4);
              if(sw.inside(x,y))
                   shiftSW=true;
              else shiftSW=false;
              ne=new Rectangle(o.r.x+o.r.width-2,o.r.y-2,4,4);
              if(ne.inside(x,y))
                   shiftNE=true;
              else shiftNE=false;
              se=new Rectangle(o.r.x+o.r.width-2,o.r.y+o.r.height-2,4,4);
              if(se.inside(x,y))
                   shiftSE=true;
              else shiftSE=false;          
              if(x>o.r.x-2&&x<o.r.x+2&&y>o.r.y&&y<o.r.y+o.r.height)
                   shiftW=true;
              else shiftW=false;
              if(x>o.r.x+o.r.width-2&&x<o.r.x+o.r.width+2
                   &&y>o.r.y&&y<o.r.y+o.r.height)
                   shiftE=true;
              else shiftE=false;
              if(y<o.r.y+2&&y>o.r.y-2&&x>o.r.x&&x<o.r.x+o.r.width)
                   shiftN=true;
              else shiftN=false;
              if(y>o.r.y+o.r.height-2&&y<o.r.y+o.r.height+2
                   &&x<o.r.x+o.r.width)
                   shiftS=true;
              else shiftS=false;
              changeCursor(x,y);
              return true;
         public boolean mouseDown(Event evt,int x,int y)
              Rectangle r=new Rectangle(o.r.x+2,o.r.y+2,o.r.width-4,o.r.height-4);
              if(r.inside(x,y))
                   drag=true;
                   startx=x;
                   starty=y;
                   xtemp=o.r.x;
                   ytemp=o.r.y;
              else drag=false;
              changeCursor(x,y);
              return true;
         public boolean mouseDrag(Event evt,int x,int y)
              intro=false;
              Rectangle bounds=new Rectangle(5,5,size().width-5,size().height-5);
              int endx, endy;          
              endx=x-startx;
              endy=y-starty;     
              //disable mouse actions past boundaries
              if(x<5)x=5;
              if(y<5)y=5;
              if(x>bounds.width)x=bounds.width;
              if(y>bounds.height)y=bounds.height;
              if(drag)
                   //disallow to move past border
                   int ox=endx+xtemp;
                   int oy=endy+ytemp;
                   if(ox<5)ox=5;
                   if(oy<5)oy=5;
                   if(ox>bounds.width-o.r.width)
                        ox=bounds.width-o.r.width;
                   if(oy>bounds.height-o.r.height)
                        oy=bounds.height-o.r.height;     
                   o.r.move(ox,oy);                    
                   west=o.r.x;
                   north=o.r.y;
                   east=o.r.x+o.r.width;
                   south=o.r.y+o.r.height;                              
              else
                   if(shiftNW){west=x;north=y;}
                   else if(shiftNE){east=x;north=y;}
                   else if(shiftSW){west=x;south=y;}
                   else if(shiftSE){east=x;south=y;}
                   else if(shiftW)west=x;
                   else if(shiftE)east=x;
                   else if(shiftN)north=y;
                   else if(shiftS)south=y;                                                       
                   //disallow resizing below 40*40
                   int MIN=40;
                   if(east-west<MIN)
                        //shiftNW=shiftNE=shiftSW=shiftSE=shiftW=shiftE=false;
                        if(shiftW||shiftNW||shiftSW)
                             west=east-MIN;
                        if(shiftE||shiftNE||shiftSE)
                             east=west+MIN;
                   if(south-north<MIN)
                        //shiftNW=shiftNE=shiftSW=shiftSE=shiftN=shiftS=false;
                        if(shiftN||shiftNW||shiftNE)
                             north=south-MIN;
                        if(shiftS||shiftSE||shiftSW)
                             south=north+MIN;
              //report altering of obstacle to ball objects and obstacle
              for(int i=0;i<MAX;i++)
                   ball[i].alterRect(o.r.x,o.r.y,o.r.width,o.r.height);
              o.r.move(west,north);
              o.r.resize(east-west, south-north);
              changeCursor(x,y);
              return true;
         private void handleCollision()
              //we iterate through all the balls, checking for collision
              for(int i=0;i<MAX;i++)
                   for(int j=0;j<MAX;j++)
                             if(i!=j)
                                  if(collide(ball[i], ball[j]))
                                       ball[i].hit(ball[j]);
                                       ball[j].hit(ball[i]);
         public void update(Graphics g)
              paint(g);
         public void paint(Graphics g)
              gBuffer.setColor(Color.lightGray);
              gBuffer.fillRect(0,0,size().width,size().height);
              gBuffer.draw3DRect(5,5,size().width-10,size().height-10,false);               
              //paint the obstacle rectangle
              o.paint(gBuffer);
              //paint our balls
              for(int i=0;i<MAX;i++)
                        ball[i].paint(gBuffer);     
              if(intro)
                   gBuffer.setColor(Color.red);
                   gBuffer.setFont(new Font("Helvetica", Font.PLAIN, 12));               
                   gBuffer.drawString("You can move and resize the rectangle!",20,30);
                   gBuffer.setFont(new Font("Helvetica", Font.PLAIN, 10));
              g.drawImage (Buffer,0,0, this);                    

    Hello, please use code tags next time you post code. You can do so by adding [code] [/code] round blocks of code. So
    [code]
    class Code {
    private static final String codeHere = "code here";
    [/code]
    will be rendered as
    class Code {
      private static final String codeHere = "code here";
    We will not do your homework for you, we will however help when you are stuck and point you in the right direction. So what have you tried? What happened?
    Don't know how to begin? What makes the ball move?

  • Game of Life display problem

    The Rules of Game of Life
    For a space that is 'populated':
    Each cell with one or no neighbors dies, as if by loneliness.
    Each cell with four or more neighbors dies, as if by overpopulation.
    Each cell with two or three neighbors survives.
    For a space that is 'empty' or 'unpopulated'
    Each cell with three neighbors becomes populated.
    I have three classes: Cell, BoardComponent, and GameViewer
    I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
    How could I fix those problems?
    My Code:
    1. Cell:
    import java.awt.Rectangle;
    public class Cell extends Rectangle{
         public Cell(int x, int y, int side)
              super(x, y, side, side);
    }2. BoardComponent:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    import com.sun.jdi.event.Event;
    public class BoardComponent extends JComponent{
         public BoardComponent()
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        g2.draw(board[i][j]);
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         public void generate()
              int count = 0;
              for(int i = 0; i < ROW-2; i++)
                   for(int j = 0; j < COL-2; j++)
                        for(int m = 0; m < 2; m++)
                             for(int n = 0; n < 2; n++)
                                  if(m!=0 || n !=0)
                                       if(!(board[i+m][j+n].isEmpty()))
                                            count++;
                        if(count == 3 || count < 2 || count > 4)
                             initialize(i*SIDE, j*SIDE);
         private int mouseX, mouseY;
         private boolean mouseclicked = false;
         public static final int ROW = 40;
         public static final int COL = 40;
         private Cell[][] board = new Cell[ROW][COL];
         public static final int SIDE = 14;
    }3. GameViewer:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class GameViewer extends JFrame{
         public static void main(String[] args)
              final BoardComponent game = new BoardComponent();
              class MouseClickListener extends MouseAdapter
                   public void mouseClicked(MouseEvent event)
                        int x = event.getX();
                        int y = event.getY();
                        game.initialize(x, y);
              MouseAdapter listener = new MouseClickListener();
              game.addMouseListener(listener);
              JButton button = new JButton("Start");
             class TimerListener implements ActionListener
                   public void actionPerformed(ActionEvent event)
                        game.generate();
            ActionListener timer = new TimerListener();
            button.setSize(40, 10);
            button.setLocation(250, 500);
            button.addActionListener(timer);
            final int DELAY = 500;
            Timer t = new Timer(DELAY, timer);
            t.start();  
            JFrame window = new JFrame();
            window.setSize(600, 600);
            window.setTitle("Life of Game");
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.add(game);
            window.add(button);
            window.setVisible(true);
    }Thanks a million.

    As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
    public void paintComponent(Graphics g)
       super.paintComponent(g);
    }As for this method:
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         }You really shouldn't be doing any painting outside the paintComponent() method.
    Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense.

  • Need help to draw recangle on video

    Hi guys ,
    Below I have pasted my code . In this code I have defined frame and in that frame stored video run. The other class has defined rectangle in cnvas . My problem is that I want rectangle to be drawn on video player and I havnt been successful.
    So its my reequest to please help me out.
    Thanks a ton in advance........
    public class Map extends JFrame
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[])
    Map mdi = new Map();
    static void Fatal(String s)
    MessageBox mb = new MessageBox("JMF Error", s);
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player = null;
    Player newPlayer = null;
    //JPanel glass = null;
    SelectionArea drawingPanel;
    String filename;
    // code//
    //ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
    // boolean stop=false;
    * METHODS
    public Map()
    super("Java Media Player");
    drawingPanel = new SelectionArea(this);
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
    //add(drawingPanel);
    //drawingPanel.setVisible(true);
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch (Exception e)
    System.err.println("Could not initialize java.awt Metal lnf");
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar()
    ActionListener al = new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String command = ae.getActionCommand();
    if (command.equals("Open"))
    if (fd == null)
    fd = new FileDialog(Map.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("/movies");
    fd.show();
    if (fd.getFile() != null)
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    else if (command.equals("Exit"))
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    * Open a media file.
    public void openFile(String filename)
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null)
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try
    player = Manager.createPlayer(url);
    catch (NoPlayerException e)
    Fatal("Error: " + e);
    catch (MalformedURLException e)
    Fatal("Error:" + e);
    catch (IOException e)
    Fatal("Error:" + e);
    if (player != null)
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    if (player.getVisualComponent() != null)
    getContentPane().add(player.getVisualComponent());
    player.start();
    jmframe.add(drawingPanel);
    drawingPanel.setVisible(true);
    /*validate();
    public void paint(Graphics g)
    drawingPanel.repaint();
    public void update(Graphics g)
    paint(g);
    drawingPanel.repaint();
    class SelectionArea extends Canvas implements ActionListener, MouseListener, MouseMotionListener
    Rectangle currentRect;
    Map controller;
    //for double buffering
    Image image;
    Graphics offscreen;
    public SelectionArea(Map controller)
    super();
    this.controller = controller;
    addMouseListener(this);
    addMouseMotionListener(this);
    public void actionPerformed(ActionEvent ae)
    repaintoffscreen();
    public void repaintoffscreen()
    image = createImage(this.getWidth(), this.getHeight());
    offscreen = image.getGraphics();
    Dimension d = size();
    if(currentRect != null)
    //Rectangle box = new Rectangle();
    //box.getDrawable(currentRect, d);
    Rectangle box = getDrawableRect(currentRect, d);
    //Draw the box outline.
    offscreen.drawRect(box.x, box.y, box.width - 1, box.height - 1);
    repaint();
    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me){ }
    public void mouseClicked(MouseEvent me){}
    public void mouseMoved(MouseEvent me){}
    public void mousePressed(MouseEvent me)
    currentRect = new Rectangle(me.getX(), me.getY(), 0, 0);
    repaintoffscreen();
    public void mouseDragged(MouseEvent me)
    System.out.println("here in dragged()");
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void mouseReleased(MouseEvent me)
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    g.drawImage(image, 0, 0, this);
    Rectangle getDrawableRect(Rectangle originalRect, Dimension drawingArea)
    int x = originalRect.x;
    int y = originalRect.y;
    int width = originalRect.width;
    int height = originalRect.height;
    //Make sure rectangle width and height are positive.
    if (width < 0)
    width = 0 - width;
    x = x - width + 1;
    if (x < 0)
    width += x;
    x = 0;
    if (height < 0)
    height = 0 - height;
    y = y - height + 1;
    if (y < 0)
    height += y;
    y = 0;
    //The rectangle shouldn't extend past the drawing area.
    if ((x + width) > drawingArea.width)
    width = drawingArea.width - x;
    if ((y + height) > drawingArea.height)
    height = drawingArea.height - y;
    return new Rectangle(x, y, width, height);
    }

    Chances of someone reading a gazillion lines of unformatted code: < 1%
    Paste your code (from the source), highlight it and click the CODE button to retain formatting and make it readable.

  • Problem with adding a Node in a Scene from a Node initialization

    Hi all! I am trying to create a custom Button, then I create a class that extends Rectangle, then this class add a Text on the button... but the Text is never shown!
    import javafx.scene.Cursor;
    import javafx.scene.shape.Rectangle;
    import javafx.scene.paint.Color;
    import javafx.scene.paint.LinearGradient;
    import javafx.scene.paint.Stop;
    import javafx.scene.effect.DropShadow;
    import javafx.scene.text.Text;
    import javafx.scene.text.Font;
    import javafx.scene.input.MouseEvent;
    public class Button extends Rectangle {
        public var text: String;
        postinit {
            cursor = Cursor.HAND;
            width = 90;
            height = 25;
            arcWidth = 15;
            arcHeight = 15;
            effect = DropShadow {radius: 6};
            fill = LinearGradient {
                startX: 0.0, startY: 0.0, endX: 0.0, endY: 1.0
                stops: [
                    Stop {offset: 0.0, color: Color.WHITE}
                    Stop {offset: 1.0, color: Color.LIGHTGRAY}
            insert Text {
                x: this.x + 5, y: this.y + 5
                content: text
                font: Font {size: 13}
            } into scene.content;
            onMouseEntered = function(e: MouseEvent): Void {
                fill = LinearGradient {
                    startX: 0.0, startY: 0.0, endX: 0.0, endY: 1.0
                    stops: [
                        Stop {offset: 0.2, color: Color.WHITE}
                        Stop {offset: 1.0, color: Color.LIGHTGRAY}
            onMouseExited = function(e: MouseEvent): Void {
                fill = LinearGradient {
                    startX: 0.0, startY: 0.0, endX: 0.0, endY: 1.0
                    stops: [
                        Stop {offset: 0.0, color: Color.WHITE}
                        Stop {offset: 1.0, color: Color.LIGHTGRAY}
            onMousePressed = function(e: MouseEvent): Void {
                fill = LinearGradient {
                    startX: 0.0, startY: 0.0, endX: 0.0, endY: 1.0
                    stops: [
                        Stop {offset: 0.0, color: Color.LIGHTGRAY}
                        Stop {offset: 1.0, color: Color.WHITE}
            onMouseReleased = function(e: MouseEvent): Void {
                fill = LinearGradient {
                    startX: 0.0, startY: 0.0, endX: 0.0, endY: 1.0
                    stops: [
                        Stop {offset: 0.0, color: Color.WHITE}
                        Stop {offset: 1.0, color: Color.LIGHTGRAY}
    }If I print scene.content from this class, there is no nodes in the scene! If I print content from the scene, the output show only the button, but not the Text...
    Can somebody tell me why this doesn't works?

    Based on your code, do you even need to extend or create a CustomNode? I believe you can accomplish your desired result by adding a stylesheet to your scene and then specify a styleClass for a basic button.
    Here are a few snippets:
    The scene:
    scene: Scene {
                    stylesheets: uiCSS
                    content: [ //your button ]               ]
                }The button:
    Button{ styleClass: "myButton"}The css:
    .myButton:hover{
       -fx-text-fill: linear (0%,0%) to (0%,100%)
            stops (0%, rgb(220, 220, 220)) (25%, rgb(190, 190, 190))(50%, rgb(190, 190, 190))(100%, rgb(220, 220, 220));
    .myButton:pressed{
      -fx-text-fill: linear (0%,0%) to (0%,100%)
            stops (0%, rgb(100, 100, 100)) (25%, rgb(100, 100, 100))(50%, rgb(100, 100, 100))(100%, rgb(100,100, 100));
    }You can modify the look and feel of any JavaFX control in this manner. An important resource to access is the caspian.css which can be found in the JDK library in the javafx-ui-controls.jar under the com.sun.javafx.scene.control.skin.caspian. You can essentially copy and paste any of the controls css into your css file and modify as desired. This allows you to skin your components without having to change any of the behavior which becomes a big hassle.
    Hope this helps.

  • Massive memory hemorrhage; heap size to go from about 64mb, to 1.3gb usage

    **[SOLVED]**
    Note: I posted this on stackoverflow as well, but a solution was not found.
    Here's the problem:
    [1] http://i.stack.imgur.com/sqqtS.png
    As you can see, the memory usage balloons out of control! I've had to add arguments to the JVM to increase the heapsize just to avoid out of memory errors while I figure out what's going on. Not good!
    ##Basic Application Summary (for context)
    This application is (eventually) going to be used for basic on screen CV and template matching type things for automation purposes. I want to achieve as high of a frame rate as possible for watching the screen, and handle all of the processing via a series of separate consumer threads.
    I quickly found out that the stock Robot class is really terrible speed wise, so I opened up the source, took out all of the duplicated effort and wasted overhead, and rebuilt it as my own class called FastRobot.
    ##The Class' Code:
        public class FastRobot {
             private Rectangle screenRect;
             private GraphicsDevice screen;
             private final Toolkit toolkit;
             private final Robot elRoboto;
             private final RobotPeer peer;
             private final Point gdloc;
             private final DirectColorModel screenCapCM;
             private final int[] bandmasks;
             public FastRobot() throws HeadlessException, AWTException {
                  this.screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                  this.screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
                  toolkit = Toolkit.getDefaultToolkit();
                  elRoboto = new Robot();
                  peer = ((ComponentFactory)toolkit).createRobot(elRoboto, screen);
                  gdloc = screen.getDefaultConfiguration().getBounds().getLocation();
                  this.screenRect.translate(gdloc.x, gdloc.y);
                  screenCapCM = new DirectColorModel(24,
                            /* red mask */    0x00FF0000,
                            /* green mask */  0x0000FF00,
                            /* blue mask */   0x000000FF);
                  bandmasks = new int[3];
                  bandmasks[0] = screenCapCM.getRedMask();
                  bandmasks[1] = screenCapCM.getGreenMask();
                  bandmasks[2] = screenCapCM.getBlueMask();
                  Toolkit.getDefaultToolkit().sync();
             public void autoResetGraphicsEnv() {
                  this.screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                  this.screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
             public void manuallySetGraphicsEnv(Rectangle screenRect, GraphicsDevice screen) {
                  this.screenRect = screenRect;
                  this.screen = screen;
             public BufferedImage createBufferedScreenCapture(int pixels[]) throws HeadlessException, AWTException {
        //          BufferedImage image;
                DataBufferInt buffer;
                WritableRaster raster;
                  pixels = peer.getRGBPixels(screenRect);
                  buffer = new DataBufferInt(pixels, pixels.length);
                  raster = Raster.createPackedRaster(buffer, screenRect.width, screenRect.height, screenRect.width, bandmasks, null);
                  return new BufferedImage(screenCapCM, raster, false, null);
             public int[] createArrayScreenCapture() throws HeadlessException, AWTException {
                       return peer.getRGBPixels(screenRect);
             public WritableRaster createRasterScreenCapture(int pixels[]) throws HeadlessException, AWTException {
             //     BufferedImage image;
                 DataBufferInt buffer;
                 WritableRaster raster;
                  pixels = peer.getRGBPixels(screenRect);
                  buffer = new DataBufferInt(pixels, pixels.length);
                  raster = Raster.createPackedRaster(buffer, screenRect.width, screenRect.height, screenRect.width, bandmasks, null);
             //     SunWritableRaster.makeTrackable(buffer);
                  return raster;
        }In essence, all I've changed from the original is moving many of the allocations from function bodies, and set them as attributes of the class so they're not called every time. Doing this actually had a significant affect on frame rate. Even on my severely under powered laptop, it went from ~4 fps with the stock Robot class, to ~30fps with my FastRobot class.
    ##First Test:
    When I started outofmemory errors in my main program, I set up this very simple test to keep an eye on the FastRobot. Note: this is the code which produced the heap profile above.
        public class TestFBot {
             public static void main(String[] args) {
                  try {
                       FastRobot fbot = new FastRobot();
                       double startTime = System.currentTimeMillis();
                       for (int i=0; i < 1000; i++)
                            fbot.createArrayScreenCapture();
                       System.out.println("Time taken: " + (System.currentTimeMillis() - startTime)/1000.);
                  } catch (AWTException e) {
                       e.printStackTrace();
        }##Examined:
    It doesn't do this every time, which is really strange (and frustrating!). In fact, it rarely does it at all with the above code. However, the memory issue becomes easily reproducible if I have multiple for loops back to back.
    #Test 2
        public class TestFBot {
             public static void main(String[] args) {
                  try {
                       FastRobot fbot = new FastRobot();
                       double startTime = System.currentTimeMillis();
                       for (int i=0; i < 1000; i++)
                            fbot.createArrayScreenCapture();
                       System.out.println("Time taken: " + (System.currentTimeMillis() - startTime)/1000.);
                       startTime = System.currentTimeMillis();
                       for (int i=0; i < 500; i++)
                            fbot.createArrayScreenCapture();
                       System.out.println("Time taken: " + (System.currentTimeMillis() - startTime)/1000.);
                       startTime = System.currentTimeMillis();
                       for (int i=0; i < 200; i++)
                            fbot.createArrayScreenCapture();
                       System.out.println("Time taken: " + (System.currentTimeMillis() - startTime)/1000.);
                       startTime = System.currentTimeMillis();
                       for (int i=0; i < 1500; i++)
                            fbot.createArrayScreenCapture();
                       System.out.println("Time taken: " + (System.currentTimeMillis() - startTime)/1000.);
                  } catch (AWTException e) {
                       e.printStackTrace();
        }##Examined
    The out of control heap is now reproducible I'd say about 80% of the time. I've looked all though the profiler, and the thing of most note (I think) is that the garbage collector seemingly stops right as the fourth and final loop begins.
    The output form the above code gave the following times:
    Time taken: 24.282 //Loop1
    Time taken: 11.294 //Loop2
    Time taken: 7.1 //Loop3
    Time taken: 70.739 //Loop4
    Now, if you sum the first three loops, it adds up to 42.676, which suspiciously corresponds to the exact time that the garbage collector stops, and the memory spikes.
    [2] http://i.stack.imgur.com/fSTOs.png
    Now, this is my first rodeo with profiling, not to mention the first time I've ever even thought about garbage collection -- it was always something that just kind of worked magically in the background -- so, I'm unsure what, if anything, I've found out.
    ##Additional Profile Information
    [3] http://i.stack.imgur.com/ENocy.png
    Augusto suggested looking at the memory profile. There are 1500+ `int[]` that are listed as "unreachable, but not yet collected." These are surely the `int[]` arrays that the `peer.getRGBPixels()` creates, but for some reason they're not being destroyed. This additional info, unfortunately, only adds to my confusion, as I'm not sure why the GC wouldn't be collecting them
    ##Profile using small heap argument -Xmx256m:
    At irreputable and Hot Licks suggestion I set the max heap size to something significantly smaller. While this does prevent it from making the 1gb jump in memory usage, it still doesn't explain why the program is ballooning to its max heap size upon entering the 4th iteration.
    [4] http://i.stack.imgur.com/bR3NP.png
    As you can see, the exact issue still exists, it's just been made smaller. ;) The issue with this solution is that the program, for some reason, is still eating through all of the memory it can -- there is also a marked change in fps performance from the first the iterations, which consume very little memory, and the final iteration, which consumes as much memory as it can.
    The question remains why is it ballooning at all?
    ##Results after hitting "Force Garbage Collection" button:
    At jtahlborn's suggestion, I hit the Force Garbage Collection button. It worked beautifully. It goes from 1gb of memory usage, down to the basline of 60mb or so.
    [5] http://i.stack.imgur.com/x4282.png
    So, this seems to be the cure. The question now is, how do I pro grammatically force the GC to do this?
    ##Results after adding local Peer to function's scope:
    At David Waters suggestion, I modified the `createArrayCapture()` function so that it holds a local `Peer` object.
    Unfortunately no change in the memory usage pattern.
    [6] http://i.stack.imgur.com/Ky5vb.png
    Still gets huge on the 3rd or 4th iteration.
    #Memory Pool Analysis:
    ###ScreenShots from the different memory pools
    ##All pools:
    [7] http://i.stack.imgur.com/nXXeo.png
    ##Eden Pool:
    [8] http://i.stack.imgur.com/R4ZHG.png
    ##Old Gen:
    [9] http://i.stack.imgur.com/gmfe2.png
    Just about all of the memory usage seems to fall in this pool.
    Note: PS Survivor Space had (apparently) 0 usage
    ##I'm left with several questions:
    (a) does the Garbage Profiler graph mean what I think it means? Or am I confusing correlation with causation? As I said, I'm in an unknown area with these issues.
    (b) If it is the garbage collector... what do I do about it..? Why is it stopping altogether, and then running at a reduced rate for the remainder of the program?
    (c) How do I fix this?
    Does anyone have any idea what's going on here?
    [1]: http://i.stack.imgur.com/sqqtS.png
    [2]: http://i.stack.imgur.com/fSTOs.png
    [3]: http://i.stack.imgur.com/ENocy.png
    [4]: http://i.stack.imgur.com/bR3NP.png
    [5]: http://i.stack.imgur.com/x4282.png
    [6]: http://i.stack.imgur.com/Ky5vb.png
    [7]: http://i.stack.imgur.com/nXXeo.png
    [8]: http://i.stack.imgur.com/R4ZHG.png
    [9]: http://i.stack.imgur.com/gmfe2.png
    Edited by: 991051 on Feb 28, 2013 11:30 AM
    Edited by: 991051 on Feb 28, 2013 11:35 AM
    Edited by: 991051 on Feb 28, 2013 11:36 AM
    Edited by: 991051 on Mar 1, 2013 9:44 AM

    SO came through.
    Turns out this issue was directly related to the garbage collector. The default one, for whatever reason, would get behind on its collection at points, and thus the memory would balloon out of control, which then, once allocated, became the new normal for the GC to operate at.
    Manually setting the GC to ConcurrentMarkSweep solved this issue completely. After numerous tests, I have been unable to reproduce the memory issue. The garbage collector does an excellent job of keeping on top of these minor collections.

  • Mouse over solution for jdk1.0

    hi all,
    I am interested in making the equivalent of a mouse over solution for a java applet.
    Basically I'll have approximately 100 Rectangle objects representing images on the applet.
    When the person moves the mouse over these 100 rectangle objects, i'll use contains() method to determine if the mouse is over the object in question.
    If true, the image will be changed to represent the mouse over event .
    I thought for a msecond about looping through all the rectangle objects each time the mouse moves. but that seemed impractical since the mouse can move pretty quickly.
    It seemed to me the best option was to extend the Rectangle object and put an event listener on it . so that the Rectangle object can be triggered at the same time or individually as needed in response to the mousemove event .
    Does anyone have any thoughts about that ?
    does anyone know how I would possible implement something like that for java 1.0
    thanks
    stev

    it seems like I have to extend Component some how to get access to enableEvents method.
    Here is my class
    class ListeningRectangle extends Rectangle{
         public ListeningRectangle(int w, int x, int y, int z, Component c){
              super(w,x,y,z);
              c.enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
         public void mouseMoved (MouseEvent me) {
         System.out.println("event has been received by rectangle");
    I am using this class in conjunction with a java applet (targetted to 1.0-1.1 ).
    I'm passing a reference of the applet in to create this ListeningRectangle like this
    new ListeningRectangle(a,b,c,d,this);
    my objective is to have about 100 different rectangle areas defined on the java applet.
    and when the person moves the moves the mouse of the applet rapidly, only the appropriate ListeningRectangle object would respond.
    any ideas on how to get this done ? ?
    The full code is below
    stephen
    ================================
    full source code below
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestEventHandler extends Applet implements Runnable{
         ///variables
         public static Color bgColor = Color.blue.darker();
         private Thread thread;
         public Graphics offGfx;
         private Image offImg;
         private Image basicOffImg;
         public static int xlen;
         public static int ylen;
    public ListeningRectangle lr;
         ///methods
         public void init(){
         xlen = size().width;
         ylen = size().height;
         basicOffImg = createImage(xlen, ylen);
         offImg = basicOffImg;
         offGfx = offImg.getGraphics();
         setBackground(bgColor);
         offGfx.setColor(bgColor);
         offGfx.fillRect(0, 0, xlen, ylen);
         offGfx.setFont(new Font("Arial, Helvetica, Helv", 1, 15));
         FontMetrics fontmetrics = offGfx.getFontMetrics();
         offGfx.setColor(Color.white);
         String s = "pleaseWait";
         offGfx.drawString(s, xlen / 2 - fontmetrics.stringWidth(s) / 2, ylen / 2);
              lr = new ListeningRectangle(20,20,50,50,this);
              offGfx.fillRect(20,20,50,50);
         public void start(){
         if(thread == null)
              thread = new Thread(this);
              thread.start();
         public void run(){
              while(thread != null){
         try
              Thread.sleep(100L);
              catch(InterruptedException _ex) { }
         public void stop()
              if(thread!=null)
         thread = null;
         public void update(Graphics g){ paint(g);}
         public void paint(Graphics g){
         g.drawImage(offImg, 0, 0, null);
    public boolean mouseDrag(Event event, int i, int j)
    if(true)
    return false;//means ripple
    } else
    return true;//means do not ripple for jvm1.0
    public boolean mouseMove(Event event, int i, int j)
    if(true)
    return false;
    } else
    return false;
    class ListeningRectangle extends Rectangle{
         public ListeningRectangle(int w, int x, int y, int z, Applet c){
              super(w,x,y,z);
              c.enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
         public void mouseMoved (MouseEvent me) {
         System.out.println("event has been received by rectangle");
    }//end of class

  • Calling a method on top object?

    Say I have my top level class, App extends JFrame, and I want to call the getlocation method on it within on of its functions. I cant do super().getLocation. So what do I do?

    Here's the code.
    public class App extends javax.swing.JFrame {
        Rectangle _captureArea;   
        public App()  {
            initComponents();
            captureButton.addActionListener(new ActionListener( ) {      
                 public void actionPerformed(ActionEvent ev) {
                    _captureArea = new Rectangle(App.this.getLocationOnScreen().getX()-320, App.this.getLocationOnScreen().getY(), 320, 45);
        } //end of constructor
    }Here is the error:
    init:
    deps-jar:
    Compiling 1 source file to C:\Documents and Settings\James Kovacs\TextTwistPlayer\build\classes
    C:\Documents and Settings\James Kovacs\TextTwistPlayer\src\App.java:39: cannot find symbol
    symbol  : constructor Rectangle(double,double,int,int)
    location: class java.awt.Rectangle
                    _captureArea = new Rectangle(App.this.getLocationOnScreen().getX()-320, App.this.getLocationOnScreen().getY(), 320, 45);
    1 error
    BUILD FAILED (total time: 1 second)Message was edited by:
    jdk2006

Maybe you are looking for