Search Results

Search found 258 results on 11 pages for 'drawimage'.

Page 6/11 | < Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • Flickering when repainting a JPanel inside a JScrollPAne

    - by pR0Ps
    I'm having a problem with repainting a JPanel inside a JScrollPane. Basically, I'm just trying to 'wrap' my existing EditPanel (it originally extended JPanel) into a JScrollPane. It seems that the JPanel updates too often (mass flickering). How would I stop this from happening? I tried using the setIgnoreRepaint() but it didn't seem to do anything. Will this current implementation work or would I need to create another inner class to fine-tune the JPanel I'm using to display graphics? Skeleton code: public class MyProgram extends JFrame{ public MyProgram(){ super(); add(new EditPanel()); pack(); } private class EditPanel extends JScrollPane{ private JPanel graphicsPanel; public EditPanel(){ graphicsPanel = new JPanel(); } public void paintComponent(Graphics g){ graphicsPanel.revalidate(); //update the scrollpane to current panel size repaint(); Graphics g2 = graphicsPanel.getGraphics(); g2.drawImage(imageToDraw, 0, 0, null); } } }

    Read the article

  • java code for capture the image by webcam

    - by Navneet
    I am using windows7 64 bit operating system. The source code is for capturing the image by webcam: import javax.swing.*; import javax.swing.event.*; import java.io.*; import javax.media.*; import javax.media.format.*; import javax.media.util.*; import javax.media.control.*; import javax.media.protocol.*; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import com.sun.image.codec.jpeg.*; public class SwingCapture extends Panel implements ActionListener { public static Player player = null; public CaptureDeviceInfo di = null; public MediaLocator ml = null; public JButton capture = null; public Buffer buf = null; public Image img = null; public VideoFormat vf = null; public BufferToImage btoi = null; public ImagePanel imgpanel = null; public SwingCapture() { setLayout(new BorderLayout()); setSize(320,550); imgpanel = new ImagePanel(); capture = new JButton("Capture"); capture.addActionListener(this); String str1 = "vfw:Logitech USB Video Camera:0"; String str2 = "vfw:Microsoft WDM Image Capture (Win32):0"; di = CaptureDeviceManager.getDevice(str2); ml = di.getLocator(); try { player = Manager.createRealizedPlayer(ml); player.start(); Component comp; if ((comp = player.getVisualComponent()) != null) { add(comp,BorderLayout.NORTH); } add(capture,BorderLayout.CENTER); add(imgpanel,BorderLayout.SOUTH); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Frame f = new Frame("SwingCapture"); SwingCapture cf = new SwingCapture(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { playerclose(); System.exit(0);}}); f.add("Center",cf); f.pack(); f.setSize(new Dimension(320,550)); f.setVisible(true); } public static void playerclose() { player.close(); player.deallocate(); } public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); if (c == capture) { // Grab a frame FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); buf = fgc.grabFrame(); // Convert it to an image btoi = new BufferToImage((VideoFormat)buf.getFormat()); img = btoi.createImage(buf); // show the image imgpanel.setImage(img); // save image saveJPG(img,"c:\\test.jpg"); } } class ImagePanel extends Panel { public Image myimg = null; public ImagePanel() { setLayout(null); setSize(320,240); } public void setImage(Image img) { this.myimg = img; repaint(); } public void paint(Graphics g) { if (myimg != null) { g.drawImage(myimg, 0, 0, this); } } } public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f,false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } } } This code is sucessfully compiled. On running the code, the following runtime error occurs: Exception in thread "VFW Request Thread" java.lang.UnsatisfiedLinkError:JMFSecurityManager: java.lang.UnsatisfiedLinkError:no jmvfw in java.library.path at com.sun.media.JMFSecurityManager.loadLibrary(JMFSecurityManager.java:206) at com.sun.media.protocol.vfw.VFWCapture.<clinit><VFWCapture.java:19> at com.sun.media.protocol.vfw.VFWSourceStream.doConnect(VFWSourceStream.java:241) at com.sun.media.protocol.vfw.VFWSourceStream.run(VFWSourceStream.java:763) at java.cdlang.Thread.run(Thread.java:619) Please send me solution of this problem/

    Read the article

  • VB.NET custom user control graphics rotation

    - by AtharvaI
    Hi, this is my first question on here. I'm trying to build a dial control as a custom user control in VB.NET. I'm using VS2008. so far I have managed to rotate image using graphics.rotatetransform . however, this rotate everything. Now I have a Bitmap for the dial which should stay stable and another Bitmap for the needle which I need to rotate. so far i've tried this: Dim gL As Graphics = Graphics.FromImage(bmpLongNeedle) gL.TranslateTransform(bmpLongNeedle.Width / 2, bmpLongNeedle.Height * 0.74) gL.RotateTransform(angleLongNeedle) gL.TranslateTransform(-bmpLongNeedle.Width / 2, -bmpLongNeedle.Height * 0.74) gL.DrawImage(bmpLongNeedle, 0, 0) As I understand it, the image of the needle should be rotated at angle "angleLongNeedle" although i'm placing the rotated image at 0,0. However, the result is that the Needle doesn't get drawn on the control. any pointers as to where I might be going wrong or something else I should be doing? Thanks in advance

    Read the article

  • C#: Creating an editable object inside a PictureBox

    - by ET
    My goal is to let the user click on a specific location on a map to add a Placemark, and then edit the placemark by click its icon (change its name, move it around, etc). I am using a PictureBox to show the map, and by registering the MouseDoubleClick event I am drawing an Image on the map with GDI+ DrawImage() method. The problem is that after the placemark's Image was drawn, it does not editable: the user cant click the icon and move it around, change its name etc. Is there any other design pattern I can follow? maybe using other controls... ?

    Read the article

  • Controlling the visibility of a Bitmap in .NET

    - by ET
    Hi everyone, I am trying to create this simple application in c#: when the user double clicks on specific location in the form, a little circle will be drawn. By one click, if the current location is marked by a circle - the circle will be removed. I am trying to do this by simply register the MouseDoubleClick and MouseClick events, and to draw the circle from a .bmp file the following way: private void MouseDoubleClick (object sender, MouseEventArgs e) { Graphics g = this.CreateGraphics(); Bitmap myImage = (Bitmap)Bitmap.FromFile("Circle.bmp"); g.DrawImage(myImage, e.X, e.Y); } My problem is that I dont know how to make the circle unvisible when the user clicks its location: I know how to check if the selected location contains a circle (by managing a list of all the locations containig circles...), but I dont know how exactly to delete it. Another question: should I call the method this.CreateGraphics() everytime the user double-clicks a location, as I wrote in my code snippet, or should I call it once on initialization?

    Read the article

  • Adding fields to a proxied class in Clojure

    - by mikera
    I'm using "proxy" to extend various Swing classes in a Clojure GUI application, generally with code that looks something like: (def ^JPanel mypanel (proxy [JPanel] [] (paintComponent [#^Graphics g] (.drawImage g background-image 0 0 nil)))) This works well but I can't figure out how to add additional fields to the newly extended class, for example making the background-image a field that could be subsequently updated. This would be pretty easy and common practice in Java. Is there a good way to do this in Clojure? Or is there another preferred method to achieve the same effect?

    Read the article

  • where should this check logic go?

    - by Benny
    I have a function that draw a string on graphics: private void DrawSmallImage(Graphics g) { if (this.SmallImage == null) return; var smallPicHeight = this.Height / 5; var x = this.ClientSize.Width - smallPicHeight; var y = this.ClientSize.Height - smallPicHeight; g.DrawImage(this.SmallImage, x, y, smallPicHeight, smallPicHeight); } the check if (this.SmallImage == null) return; should be in the function DrawSmallImage or should be in the caller? which is better?

    Read the article

  • Controling the visibility of a Bitmap in .NET

    - by ET
    Hi everyone, I am trying to create this simple application in c#: when the user double clicks on specific location in the form, a little circle will be drawn. By one click, if the current location is marked by a circle - the circle will be removed. I am trying to do this by simply register the MouseDoubleClick and MouseClick events, and to draw the circle from a .bmp file the following way: private void MouseDoubleClick (object sender, MouseEventArgs e) { Graphics g = this.CreateGraphics(); Bitmap myImage = (Bitmap)Bitmap.FromFile("Circle.bmp"); g.DrawImage(myImage, e.X, e.Y); } My problem is that I dont know how to make the circle unvisible when the user clicks its location: I know how to check if the selected location contains a circle (by managing a list of all the locations containig circles...), but I dont know how exactly to delete it. Another question: should I call the method this.CreateGraphics() everytime the user double-clicks a location, as I wrote in my code snippet, or should I call it once on initialization?

    Read the article

  • How to read binary column in database into image on asp.net page?

    - by marko
    I want to read from database where I've stored a image in binary field and display a image. while (reader.Read()) { byte[] imgarr = (byte[])reader["file"]; Stream s = new MemoryStream(imgarr); System.Drawing.Image image = System.Drawing.Image.FromStream(s); Graphics g = Graphics.FromImage(image); g.DrawImage(image, new Point(400, 10)); image.Save(Response.OutputStream, ImageFormat.Jpeg); g.Dispose(); image.Dispose(); } con.Close(); This piece of code doesn't work: System.Drawing.Image image = System.Drawing.Image.FromStream(s); What am I doing wrong?

    Read the article

  • Java : VolatileImage slower than BufferedImage.

    - by Norswap
    I'm making a game in java and in used BufferedImages to render content to the screen. I had performance issues on low end machines where the game is supposed to run, so I switched to VolatileImage which are normally faster. Except they actually slow the whole thing down. The images are created with GraphicsConfiguration.createCompatibleVolatileImage(...) and are drawn to the screen with Graphics.drawImage(...) (follow link to see which one specifically). They are drawn upon a Canvas using double buffering. Does someone has an idea of what is going wrong here ?

    Read the article

  • Problem using GDI+ with multiple threads (VB.NET)

    - by Joe B
    I think it would be best if I just copy and pasted the code (it's very trivial). Private Sub Main() Handles MyBase.Shown timer.Interval = 10 timer.Enabled = True End Sub Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint e.Graphics.DrawImage(image, 0, 0) End Sub Private Sub tick() Handles timer.Elapsed Using g = Graphics.FromImage(image) g.Clear(Color.Transparent) g.DrawLine(Pens.Red, 0 + i, 0 + i, Me.Width - i, Me.Height - i) End Using Me.Invalidate() End Sub An exception, "The object is currently in use elsewhere", is raised during the tick event. Could someone tell me why this happens and how to solve it? Thanks.

    Read the article

  • Resizing gives me to heavy image

    - by phenevo
    Hi, I'm resizing jpeg 1200x900 ,556kb by method: public static Image ResizeImage(Image imgToResize, int height) //height=400 { int destWidth; int destHeight; int sourceWidth = imgToResize.Width; int sourceHeight = imgToResize.Height; float nPercent = 0; float nPercentH = 0; nPercentH = ((float)height / (float)sourceHeight); nPercent = nPercentH; destWidth = (int)(sourceWidth * nPercent); destHeight = height; Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgToResize, 0, 0, destWidth, destHeight); g.Dispose(); return b; } gives me 555kb 533x400 jpeg. Why this photo is so heavy. For photo jpeg 2111kb 2156x1571 I get 556kb 533x400 jpeg Why in first case is so terrible !

    Read the article

  • Reading a file over a network path

    - by Sin5k4
    I have this weird issue,when I use > File FileToRead = new File("\\\\MYSERVER\\MYFOLDER\\MYFOLDER\\MYPICTURE.JPG"); to read a file over a network,all I get is a null pointer exception.Normally a local path works with this,but when on a network path,I just couldn't manage to get it to work.Any ideas? PS:oh and my network connection seems to work,no issues when accessing data in windows explorer... More of the code: File FileToRead = new File("file://DOKSERVICE/Somefolder/ProductImage/01001.JPG"); // File FileToRead = new File("c:\\dog.jpg"); local test BufferedImage image = ImageIO.read(FileToRead); BufferedImage resizedimage = new BufferedImage(260, 260,BufferedImage.TYPE_INT_RGB ); Graphics2D g = resizedimage.createGraphics(); g.drawImage(image, 0, 0, 260, 260, null); g.dispose(); picture.setIcon(new ImageIcon(image));

    Read the article

  • problem getting a form image background

    - by Deumber
    I'm creating a datagridview transparent //I got the parent background image Bitmap parentBackGround = new Bitmap(this.Parent.BackgroundImage); //Set the area i want to create equal to the size of my grid Rectangle rect = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height); //And draw in the entire grid the area of the background image that is cover with my grid, making a "transparent" effect. graphics.DrawImage(parentBackGround.Clone(rect, PixelFormat.Format32bppRgb), gridBounds); When the backgroundimage of the grid's parent is show in an normal layout all work ok, but if the layout is stretch, center or any other, the transparency effent gone, have you any idea to fix it?

    Read the article

  • Drawing Image onto Canvas Stretches Image?

    - by Fred Finkle
    I have this code (stolen from the web): function readIt() { var reader = new FileReader(); reader.onload = (function(e) { var img = new Image(); img.src = e.target.result; var c = document.getElementById("canvas"); var ctx = c.getContext("2d"); ctx.drawImage(img, 0, 0); } ); reader.readAsDataURL(document.getElementById('userImage').files[0]); } Which works up to a point. The canvas's width and height are set to the size of the image, but only the top left of the image appears - It appears to be stretched so it fits all the space allocated to the canvas (enough to display the whole image - 615px x 615px). If I add an <img> element sized the same size as the canvas and point the src to the image in the file system it appears perfect. I'm using Chrome, but it appears the same in Firefox. Thanks in advance.

    Read the article

  • How do i generate thumbnail image for use with img tag ? Java web application.

    - by Nitesh Panchal
    Hello, I am using the below given code, but it is not working properly. Can anybody tell me how do i generate thumbnail of the image? because i am creating a photo album and i want only thumbnail images to be downloaded at first, not the entire 400-500 kb images. File objFile = new File(strImageFullPath); File targetFile = new File(strImageFullPathWithoutExt + "_small" + strFileExtension); Image image = ImageIO.read(objFile); final int WIDTH = 150; final int HEIGHT = 150; Image thumbnailImage = image.getScaledInstance(WIDTH, HEIGHT, Image.SCALE_DEFAULT); BufferedImage objThumbnailBufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics gfx = objThumbnailBufferedImage.getGraphics(); gfx.drawImage(image, 0, 0, null); gfx.dispose(); ImageIO.write(objThumbnailBufferedImage, strFileExtension.substring(1), targetFile); Just assume that few variables like strImageFullPath,strImageFullPathWithoutExt etc they exist. Thanks in advance :)

    Read the article

  • How to change the opacity (alpha, transparency) of an element in a canvas element after it has been

    - by Joe Lencioni
    Using the HTML5 <canvas> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity once it as been drawn. Here's the code I have so far: var canvas = document.getElementById('myCanvas'); if (canvas.getContext) { var c = canvas.getContext('2d'); c.globalAlpha = 0; var img = new Image(); img.onload = function() { c.drawImage(img, 0, 0); } img.src = 'image.jpg'; } Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity? Thanks!

    Read the article

  • how to compress a PNG image using Java

    - by 116213060698242344024
    Hi I would like to know if there is any way in Java to reduce the size of an image (use any kind of compression) that was loaded as a BufferedImage and is going to be saved as an PNG. Maybe some sort of png imagewriteparam? I didnt find anything helpful so im stuck. heres a sample how the image is loaded and saved public static BufferedImage load(String imageUrl) { Image image = new ImageIcon(imageUrl).getImage(); bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2D = bufferedImage.createGraphics(); g2D.drawImage(image, 0, 0, null); return bufferedImage; } public static void storeImageAsPng(BufferedImage image, String imageUrl) throws IOException { ImageIO.write(image, "png", new File(imageUrl)); }

    Read the article

  • Speed of interpolation algorithms, C# and C++ working together.

    - by Kaminari
    Hello. I need fast implementation of popular interpolation algorithms. I figured it out that C# in such simple algorithms will be much slower than C++ so i think of writing some native code and using it in my C# GUI. First of all i run some tests and few operations on 1024x1024x3 matrix took 32ms in C# and 4ms in C++ and that's what i basicly need. Interpolation however is not a good word because i need them only for downscaling. But the question is: Will it be faster than C# methods in Drawing2D Image outputImage = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); Graphics grPhoto = Graphics.FromImage(outputImage); grPhoto.InterpolationMode = InterpolationMode.*; //all of them grPhoto.DrawImage(bmp, new Rectangle(0, 0, destWidth, destHeight), Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); Some of these method run in 20ms and some in 80. Is there a way to do it faster?

    Read the article

  • Google Chrome hardware acceleration making game run slow

    - by powerc9000
    So I have been working on a game in HTML5 canvas and noticed that the games lags and performs much slower when hardware acceleration is turned on in Google Chrome then when it is turned off. You can try for yourself here From doing some profiling I see that the problem lies in drawImage. More specifically drawing one canvas onto another. I do a lot of this. Hardware Acceleration on. Hardware Acceleration off. Is there something fundamental I am missing with one canvas to another? Why would the difference be that profound?

    Read the article

  • Slow Firefox Javascript Canvas Performance?

    - by jujumbura
    As a followup from a previous post, I have been trying to track down some slowdown I am having when drawing a scene using Javascript and the canvas element. I decided to narrow down my focus to a REALLY barebones animation that only clears the canvas and draws a single image, once per-frame. This of course runs silky smooth in Chrome, but it still stutters in Firefox. I added a simple FPS calculator, and indeed it appears that my page is typically getting an FPS in the 50's when running Firefox. This doesn't seem right to me, I must be doing something wrong here. Can anybody see anything I might be doing that is causing this drop in FPS? <!DOCTYPE HTML> <html> <head> </head> <body bgcolor=silver> <canvas id="myCanvas" width="600" height="400"></canvas> <img id="myHexagon" src="Images/Hexagon.png" style="display: none;"> <script> window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); var animX = 0; var frameCounter = 0; var fps = 0; var time = new Date(); function animate() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); animX += 1; if (animX == canvas.width) { animX = 0; } var image = document.getElementById("myHexagon"); context.drawImage(image, animX, 128); context.lineWidth=1; context.fillStyle="#000000"; context.lineStyle="#ffffff"; context.font="18px sans-serif"; context.fillText("fps: " + fps, 20, 20); ++frameCounter; var currentTime = new Date(); var elapsedTimeMS = currentTime - time; if (elapsedTimeMS >= 1000) { fps = frameCounter; frameCounter = 0; time = currentTime; } // request new frame requestAnimFrame(function() { animate(); }); } window.onload = function() { animate(); }; </script> </body> </html>

    Read the article

  • Drawing isometric map in canvas / javascript

    - by Dave
    I have a problem with my map design for my tiles. I set player position which is meant to be the middle tile that the canvas is looking at. How ever the calculation to put them in x:y pixel location is completely messed up for me and i don't know how to fix it. This is what i tried: var offset_x = 0; //used for scrolling on x var offset_y = 0; //used for scrolling on y var prev_mousex = 0; //for movePos function var prev_mousey = 0; //for movePos function function movePos(e){ if (prev_mousex === 0 && prev_mousey === 0) { prev_mousex = e.pageX; prev_mousey = e.pageY; } offset_x = offset_x + (e.pageX - prev_mousex); offset_y = offset_y + (e.pageY - prev_mousey); prev_mousex = e.pageX; prev_mousey = e.pageY; run = true; } player_posx = 5; player_posy = 55; ct = 19; for (i = (player_posx-ct); i < (player_posx+ct); i++){ //horizontal for (j=(player_posy-ct); j < (player_posy+ct); j++){ // vertical //img[0] is 64by64 but the graphic is 64by32 the rest is alpha space var x = (i-j)*(img[0].height/2) + (canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); var abposx = x - offset_x; var abposy = y - offset_y; ctx.drawImage(img[0],abposx,abposy); } } Now based on these numbers the first render-able tile is I = 0 & J = 36. As numbers in the negative are not in the array. But for I=0 and J= 36 the position it calculates is : -1120 : 592 Does any one know how to center it to canvas view properly?

    Read the article

  • Issues with shooting in a HTML5 platformer game

    - by fnx
    I'm coding a 2D sidescroller using only JavaScript and HTML5 canvas, and in my game I have two problems with shooting: 1) Player shoots continous stream of bullets. I want that player can shoot only a single bullet even though the shoot-button is being held down. 2) Also, I get an error "Uncaught TypeError: Cannot call method 'draw' of undefined" when all the bullets are removed. My shooting code goes like this: When player shoots, I do game.bullets.push(new Bullet(this, this.scale)); and after that: function Bullet(source, dir) { this.id = "bullet"; this.width = 10; this.height = 3; this.dir = dir; if (this.dir == 1) { this.x = source.x + source.width - 5; this.y = source.y + 16; } if (this.dir == -1) { this.x = source.x; this.y = source.y + 16; } } Bullet.prototype.update = function() { if (this.dir == 1) this.x += 8; if (this.dir == -1) this.x -= 8; for (var i in game.enemies) { checkCollisions(this, game.enemies[i]); } // Check if bullet leaves the viewport if (this.x < game.viewX * 32 || this.x > (game.viewX + game.tilesX) * 32) { removeFromList(game.bullets, this); } } Bullet.prototype.draw = function() { // bullet flipping uses orientation of the player var posX = game.player.scale == 1 ? this.x : (this.x + this.width) * -1; game.ctx.scale(game.player.scale, 1); game.ctx.drawImage(gameData.getGfx("bullet"), posX, this.y); } I handle removing with this function: function removeFromList(list, object) { for (i in list) { if (object == list[i]) { list.splice(i, 1); break; } } } And finally, in the main game loop I have this: for (var i in game.bullets) { game.bullets[i].update(); game.bullets[i].draw(); } I have tried adding if (game.bullets.length > 0) to the main game loop before the above draw&update calls, but I still get the same error.

    Read the article

  • ArrayList of Entites Random Movement

    - by opiop65
    I have an arraylist of entites that I want to move randomly. No matter what I do, they won't move. Here is my female class: import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.util.Random; import javax.swing.ImageIcon; public class Female extends Entity { static int femaleX = 0; static int femaleY = 0; double walkSpeed = .1f; Random rand = new Random(); int random; int dir; Player player; public Female(int posX, int posY) { super(posX, posY); } public void update() { posX += femaleX; posY += femaleY; } public void draw(Graphics2D g2d) { g2d.drawImage(getFemaleImg(), posX, posY, null); if (Player.showBounds == true) { g2d.draw(getBounds()); } } public Image getFemaleImg() { ImageIcon ic = new ImageIcon("res/female.png"); return ic.getImage(); } public Rectangle getBounds() { return new Rectangle(posX, posY, getFemaleImg().getHeight(null), getFemaleImg().getWidth(null)); } public void moveFemale() { random = rand.nextInt(3); System.out.println(random); if (random == 0) { dir = 0; posX -= (int) walkSpeed; } } } And here is how I update the female class in the main class: public void actionPerformed(ActionEvent ae) { player.update(); for(int i = 0; i < females.size(); i++){ Female tempFemale = females.get(i); tempFemale.update(); } repaint(); } If I do something like this(in the female update method): public void update() { posX += femaleX; posY += femaleY; posX -= walkSpeed; } The characters move with no problem. Why is this?

    Read the article

  • Attach my sprite with Box2d

    - by user919496
    I'm coding Javascript(HTML5) with Box2D. And I want to ask how to attach Sprite with Box2D. This is function My sprite: function My_Sprite() { this.m_Image = new Image(); this.m_Position = new Vector2D(0,0); this.m_CurFrame = 0; this.m_ColFrame = 0; this.m_Size = new Vector2D(0,0); this.m_Scale = new Vector2D(0,0); this.m_Rotation = 0; } My_Sprite.prototype.constructor = function (_Image_SRC) { this.m_Image.src = _Image_SRC; } My_Sprite.prototype.constructor = function (_Image_SRC,_Size,_Col) { this.m_Image.src = _Image_SRC; this.m_Size = _Size; this.m_ColFrame = _Col; this.m_Scale = new Vector2D(1, 1); } My_Sprite.prototype.Draw = function (context) { context.drawImage(this.m_Image, this.m_Size.X * (this.m_CurFrame % this.m_ColFrame), this.m_Size.Y * parseInt(this.m_CurFrame / this.m_ColFrame), this.m_Size.X, this.m_Size.Y, this.m_Position.X, this.m_Position.Y, this.m_Size.X * this.m_Scale.X, this.m_Size.Y * this.m_Scale.Y ); } and this is function Object : function Circle(type, angle, size) { // Circle.prototype = new My_Object(); // Circle.prototype.constructor = Circle; // Circle.prototype.parent = My_Object.prototype; this.m_den = 1.0; this.m_fri = 0.5; this.m_res = 0.2; fixDef.density = this.m_den; fixDef.friction = this.m_fri; fixDef.restitution = this.m_res; fixDef.shape = new b2PolygonShape; bodyDef.type = type; bodyDef.angle = angle; bodyDef.userData = m_spriteCircle; fixDef.shape = new b2CircleShape( Radius / SCALE //radius ); this.m_Body = world.CreateBody(bodyDef); this.m_Body.CreateFixture(fixDef); m_spriteCircle = new My_Sprite(); this.Init(); } Circle.prototype.Init = function () { m_spriteCircle.constructor("images/circle.png", new Vector2D(80, 80), 1); m_spriteCircle.m_CurFrame = 0; } Circle.prototype.Draw = function (context) { m_spriteCircle.Draw(context); } and I draw it : var m_Circle = new Circle(); m_Circle.Draw(context);

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11  | Next Page >