Search Results

Search found 108 results on 5 pages for 'graphics2d'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Lines don't overlap when they should Java Swing

    - by Sven
    I'm drawing lines in a JFrame on a self made gridPanel. Problem is, I draw the lines between 2 points. When I have a line that is between point 1 and point 2 and a line between point 2 and point 3, the lines should connect. This however isn,t the case, there is a small gap in between, no idea why. But it isn't drawing till the end of the specified point. (start point is correct.) Here is the code of the JFrame: public void initialize(){ this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(500, 400)); gridPane = new GridPane(); gridPane.setBackground(Color.WHITE); gridPane.setSize(this.getPreferredSize()); gridPane.setLocation(0, 0); this.add(gridPane,BorderLayout.CENTER); //createSampleLabyrinth(); drawWall(0,5,40,5); //These are the 2 lines that don't connect. drawWall(40,5,80,5); this.pack(); } drawWall calls a method that calls a method in GridPane. The relevant code in gridPane: /** * Draws a wall on this pane. With the starting point being x1, y1 and its end x2,y2. * @param x1 * @param y1 * @param x2 * @param y2 */ public void drawWall(int x1, int y1, int x2, int y2) { Wall wall = new Wall(x1,y1,x2,y2, true); wall.drawGraphic(); wall.setLocation(x1, y1); wall.setSize(10000,10000); this.add(wall, JLayeredPane.DEFAULT_LAYER); this.repaint(); } This method creates a wall and puts it in the Jframe. The relevant code of the wall: public class Wall extends JPanel { private int x1; private int x2; private int y1; private int y2; private boolean black; /** * x1,y1 is the start point of the wall (line) end is x2,y2 * * @param x1 * @param y1 * @param x2 * @param y2 */ public Wall(int x1, int y1, int x2, int y2, boolean black) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; this.black = black; setOpaque(false); } private static final long serialVersionUID = 1L; public void drawGraphic() { repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; if(black){ g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(8)); } else { g2.setColor(Color.YELLOW); g2.setStroke(new BasicStroke(3)); } g2.drawLine(x1, y1, x2, y2); } } So, where am I going wrong? The true/false is to determine if the wall should be black or yellow, nothing to be concerned about.

    Read the article

  • How to properly scroll a 2D tilemap?

    - by Sri Harsha Chilakapati
    Hello and I'm trying to make my own game engine in Java. I have completed all the necessary ones but I can't figure it out with the TileGame class. It just can't scroll. Also there are no exceptions. Here I'm listing the code. TileGame.java @Override public void draw(Graphics2D g) { if (back!=null){ back.render(g); } if (follower!=null){ follower.render(g); follower.draw(g); } for (int i=0; i<actors.size(); i++){ Actor actor = actors.get(i); if (actor!=follower&&getVisibleRect().intersects(actor.getBounds())){ g.drawImage(actor.getAnimation().getFrameImage(), actor.x - OffSetX, actor.y - OffSetY, null); actor.draw(g); } } } /** * This method returns the visible rectangle * @return The visible rectangle */ public Rectangle getVisibleRect(){ return new Rectangle(OffSetX, OffSetY, global.WIDTH, global.HEIGHT); } @Override public void update(){ if (follower!=null){ if (scrollHorizontally){ OffSetX = global.WIDTH/2 - Math.round((float)follower.x) - tileSize; OffSetX = Math.min(OffSetX, 0); OffSetX = Math.max(OffSetX, global.WIDTH - mapWidth); } if (scrollVertically){ OffSetY = global.HEIGHT/2 - Math.round((float)follower.y) - tileSize; OffSetY = Math.min(OffSetY, 0); OffSetY = Math.max(OffSetY, global.HEIGHT - mapHeight); } } for (int i=0; i<actors.size(); i++){ Actor actor1 = actors.get(i); if (getVisibleRect().contains(actor1.x, actor1.y)){ actor1.update(); for (int j=0; j<actors.size(); j++){ Actor actor2 = actors.get(j); if (actor1.isCollidingWith(actor2)){ actor1.collision(actor2); actor2.collision(actor1); } } } } } but the problem is that all the actors are working, but it just won't scroll. Help Please.. Thanks in Advance.

    Read the article

  • How can I resize a set of sprite images?

    - by Tyler J Fisher
    Hey StackExchange GameDev community, I'm attempting to resize series of sprites upon instantiation of the class they're located in. I've attempted to use the following code to resize the images, however my attempts have been unsuccessful. I have been unable to write an implementation that is even compilable, so no error codes yet. wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST); I've heard that Graphics2D is the best option. Any suggestions? I think I'm probably best off loading the images into a Java project, resizing the images then outputting them to a new directory so as not to have to resize each sprite upon class instantiation. What do you think? Photoshopping each individual sprite is out of the question, unless I used a macro. Code: package game; //Import import java.awt.Image; import javax.swing.ImageIcon; public class Mario extends Human { Image wLeft = new ImageIcon("sprites\\mario\\wLeft.PNG").getImage(); //Constructor public Mario(){ super("Mario", 50); wLeft = wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST); }

    Read the article

  • Java - Resize images upon class instantiation

    - by Tyler J Fisher
    Hey StackExchange GameDev community, I'm attempting to: Resize series of sprites upon instantiation of the class they're located in (x2) I've attempted to use the following code to resize the images, however my attempts have been unsuccessful. I have been unable to write an implementation that is even compilable, so no error codes yet. wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST); I've heard that Graphics2D is the best option. Any suggestions? I think I'm probably best off loading the images into a Java project, resizing the images then outputting them to a new directory so as not to have to resize each sprite upon class instantiation. What do you think? Photoshopping each individual sprite is out of the question, unless I used a macro. Code: package game; //Import import java.awt.Image; import javax.swing.ImageIcon; public class Mario extends Human { Image wLeft = new ImageIcon("sprites\\mario\\wLeft.PNG").getImage(); //Constructor public Mario(){ super("Mario", 50); wLeft.getScaledInstance(wLeft.getWidth()*2, wLeft.getHeight()*2, Image.SCALE_FAST); } Thanks! Note: not homework, just thought Mario would be a good, overused starting point in game dev.

    Read the article

  • I can't scroll my tilemap ... HELP!

    - by Sri Harsha Chilakapati
    Hello and I'm trying to make my own game engine in Java. I have completed all the necessary ones but I can't figure it out with the TileGame class. It just can't scroll. Also there are no exceptions. Here I'm listing the code. TileGame.java @Override public void draw(Graphics2D g) { if (back!=null){ back.render(g); } if (follower!=null){ follower.render(g); follower.draw(g); } for (int i=0; i<actors.size(); i++){ Actor actor = actors.get(i); if (actor!=follower&&getVisibleRect().intersects(actor.getBounds())){ g.drawImage(actor.getAnimation().getFrameImage(), actor.x - OffSetX, actor.y - OffSetY, null); actor.draw(g); } } } /** * This method returns the visible rectangle * @return The visible rectangle */ public Rectangle getVisibleRect(){ return new Rectangle(OffSetX, OffSetY, global.WIDTH, global.HEIGHT); } @Override public void update(){ if (follower!=null){ if (scrollHorizontally){ OffSetX = global.WIDTH/2 - Math.round((float)follower.x) - tileSize; OffSetX = Math.min(OffSetX, 0); OffSetX = Math.max(OffSetX, global.WIDTH - mapWidth); } if (scrollVertically){ OffSetY = global.HEIGHT/2 - Math.round((float)follower.y) - tileSize; OffSetY = Math.min(OffSetY, 0); OffSetY = Math.max(OffSetY, global.HEIGHT - mapHeight); } } for (int i=0; i<actors.size(); i++){ Actor actor1 = actors.get(i); if (getVisibleRect().contains(actor1.x, actor1.y)){ actor1.update(); for (int j=0; j<actors.size(); j++){ Actor actor2 = actors.get(j); if (actor1.isCollidingWith(actor2)){ actor1.collision(actor2); actor2.collision(actor1); } } } } } but the problem is that all the actors are working, but it just won't scroll. Help Please.. Thanks in Advance.

    Read the article

  • Alternatives to Component Based Architecture?

    - by Ben Lakey
    Usually when I develop a game I will use an architecture like what you see below. What other architectures are popular for simple game development? I'm concerned about having a narrow view of what exists out there for architectures beyond this. Is this an example of component-based architecture? Or is this something else? What would that look like? What alternatives exist? public abstract class ComponentBase { protected final Collection<ComponentBase> subComponents = new LinkedList<ComponentBase>(); private boolean enableInput; private boolean isVisible; protected ComponentBase(boolean enableInput, boolean isVisible) { this.enableInput = enableInput; this.isVisible = isVisible; } public void render(Graphics2D graphics) { for(ComponentBase gameComponent : this.subComponents) { if(gameComponent.isVisible()) { gameComponent.render(graphics); } } } public void input(InputData input) { for(ComponentBase gameComponent : this.subComponents) { if(gameComponent.inputIsEnabled()) { gameComponent.input(input); } } } ... getters/setters ... public void update(long elapsedTimeMillis) { for(ComponentBase gameComponent : this.subComponents) { gameComponent.update(elapsedTimeMillis); } } }

    Read the article

  • Facing a character towards the mouse

    - by ratata
    I'm trying to port a simple 2d top down shooter game from C++(Allegro) to Java and i'm having problems with rotating my character. Here's the code i used in c++ if (keys[A]) RotateRight(player, degree); if (keys[D]) RotateLeft(player, degree); void RotateLeft(Player& player, float& degree) { degree += player.rotatingSpeed; if ( degree >= 360 ) degree = 0; } void RotateRight(Player& player, float& degree) { degree -= player.rotatingSpeed; if ( degree <= 0) degree = 360; } And this is what i have in render section: al_draw_rotated_bitmap(player.image, player.frameWidth / 2, player.frameHeight / 2, player.x, player.y, degree * 3.14159 / 180, 0); Instead of using A-D keys i want to use mouse this time. I've been searching since last night and came up to few sample codes however noone of them worked. For example this just made my character to circle around the map: int centerX = width / 2; int centerY = height / 2; double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2; ((Graphics2D)g).rotate(angle, centerX, centerY); g.fillRect(...); // draw your rectangle Any help is much appreciated.

    Read the article

  • Drawing visible tiles - side scrolling

    - by Troubleshoot
    Currently I'm calling drawMap every time repaint is called. This is the code I've written for my drawMap method so far. public void drawMap(Graphics2D g2d) { float cameraX = Player.getX() - (Frame.CANVAS_WIDTH / 2); float cameraY = Player.getY() - (Frame.CANVAS_HEIGHT / 2); int tileX = (int) cameraX; int tileY = (int) cameraY; int xIndent = 0, yIndent = 0; int a = 0, b = 0; while (tileX % TILE_SIZE != 0) { tileX--; xIndent++; } while (tileY % TILE_SIZE != 0) { tileY--; yIndent++; } for (int y = tileY; y < tileY + Frame.CANVAS_HEIGHT; y += Map.TILE_SIZE) { for (int x = tileX; x < tileX + Frame.CANVAS_WIDTH; x += Map.TILE_SIZE) { if ((y / TILE_SIZE < 0 || x / TILE_SIZE < 0) || (y / TILE_SIZE > columnSize)) break; g2d.drawImage(map[y / TILE_SIZE][x / TILE_SIZE], a - xIndent, b - yIndent, null); a += TILE_SIZE; } a = 0; b += TILE_SIZE; } } The idea behind this is that it gets the camera position and draws the map relative to the player position. However, instead of the player being in the center of the screen all the time, the player actually moves away from the center as it scrolls to the right, and moves towards to center as it scrolls to the left. I've been trying to pinpoint what I've done wrong but I can't seem to find it. My code also seems quite messy, so am I doing this the correct way?

    Read the article

  • Transforms in Box2D

    - by user1264811
    I'm attempting to implement a camera in my game. I had it working for regular objects, but I began using Box2D and obviously things changed a bit. I have a Body object that I want to draw at the center of the screen. Basically what I'm doing is subtracting the viewportX and viewportY to the Body. I use this code that currently is not working as it should: public void paint(Graphics2D g, int viewportX, int viewportY) { Transform xf = new Transform(); // m_body is the Body object xf.set(m_body.getTransform()); // Here what I attemp to do is take the transform and alter it // by the viewportX and Y, which is something like **-240, -150**. // Why is it negative? Because an object has coordinates 500, 300 would be displayed // at 160, 150 when the subtraction is done. // With the DrawUtils.toScale(), it's just how I convert the units from JBox2D units // to my units. Vec2 v = Transform.mulTrans(xf, new Vec2(DrawUtils.toScale(-viewportX), DrawUtils.toScale(-viewportY))); // Set the new transform to the new vector. Keep the old angle. xf.set(v, xf.q.getAngle()); g.setColor(Color.white); // I know for a fact that the following method works 100%. It correctly displays // my object, just that it doesn't follow it. for (Fixture f = m_body.getFixtureList(); f != null; f = f.getNext()) DrawUtils.drawShape(f, xf); } Hopefully I didn't over comment this and you understand my problem. I don't want to alter the actual physics position of the object, I just want to display it in the center.

    Read the article

  • osx web service spawns icon in taskbar - osx - while drawing image

    - by wuntee
    I have a web endpoint that displays an image of a string... When the following code is run (in tomcat) it spawns a java icon in the taskbar on OSX. Not sure if it is a problem, or whats going on. Looking for some sort of explination @RequestMapping("/text/{text}") public void textImage(HttpServletResponse response, @PathVariable("text") String text){ response.setContentType("image/png"); try{ OutputStream os = response.getOutputStream(); BufferedImage bufferedImage = new BufferedImage( (text.length()*10) , 14, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = bufferedImage.createGraphics(); g2d.setBackground(Color.WHITE); g2d.setPaint(Color.BLACK); Font font = new Font("sansserif", Font.PLAIN, 12); g2d.setFont(font); g2d.drawString(text, 0, 12); ImageIO.write(bufferedImage, "png", os); } catch(Exception e) { // nothing we can do, simply log the error logger.error("Could not draw string: ", e); } }

    Read the article

  • Thread not behaving correctly

    - by ivor
    Hello, I wonder if anyone can help me to understand where I could be going wrong with this code; Basically I'm working on a turorial and calling the class below from another class - and it is getting the following error; Exception in thread "Thread-1" java.lang.NullPointerException at org.newdawn.spaceinvaders.TCPChat.run(TCPChat.java:322) at java.lang.Thread.run(Unknown Source) I realise the error is beibg flagged in another class- but I have tested the other class with a small class which sets up a separate thread - and it works fine, but as soon as I try and implement a new thread in this class - it causes all sorts of problems. Am I setting up the thread correctly in this class? Basically I can set up a thread in this class, with a test loop and it's fine, but when I bring in the functionality of the rest of the game it sometimes hangs, or does not display at all. Any suggestions on where I could be going wrong would be greatly appreciated. Thanks for looking. package org.newdawn.spaceinvaders; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Scanner; import java.awt.*;//maybe not needed import javax.swing.*;//maybenot needed import java.util.Random; //import java.io.*; /** * The main hook of our game. This class with both act as a manager * for the display and central mediator for the game logic. * * Display management will consist of a loop that cycles round all * entities in the game asking them to move and then drawing them * in the appropriate place. With the help of an inner class it * will also allow the player to control the main ship. * * As a mediator it will be informed when entities within our game * detect events (e.g. alient killed, played died) and will take * appropriate game actions. * * @author Kevin Glass */ public class Game extends Canvas implements Runnable{ /** The stragey that allows us to use accelerate page flipping */ private BufferStrategy strategy; /** True if the game is currently "running", i.e. the game loop is looping */ private boolean gameRunning = true; /** The list of all the entities that exist in our game */ private ArrayList entities = new ArrayList(); /** The list of entities that need to be removed from the game this loop */ private ArrayList removeList = new ArrayList(); /** The entity representing the player */ private Entity ship; /** The speed at which the player's ship should move (pixels/sec) */ private double moveSpeed = 300; /** The time at which last fired a shot */ private long lastFire = 0; /** The interval between our players shot (ms) */ private long firingInterval = 500; /** The number of aliens left on the screen */ private int alienCount; /** The number of levels progressed */ private double levelCount; /** high score for the user */ private int highScore; /** high score for the user */ private String player = "bob"; //private GetUserInput getPlayer; /** The list of entities that need to be removed from the game this loop */ /** The message to display which waiting for a key press */ private String message = ""; /** True if we're holding up game play until a key has been pressed */ private boolean waitingForKeyPress = true; /** True if the left cursor key is currently pressed */ private boolean leftPressed = false; /** True if the right cursor key is currently pressed */ private boolean rightPressed = false; /** True if we are firing */ private boolean firePressed = false; /** True if game logic needs to be applied this loop, normally as a result of a game event */ private boolean logicRequiredThisLoop = false; //private Thread cThread = new Thread(this); //public Thread t = new Thread(this); //private Thread g = new Thread(this); void setHighscore(int setHS) { highScore = setHS; } public int getHighscore() { return highScore; } public void setPlayer(String setPlayer) { player = setPlayer; } public String getPlayer() { return player; } public void run() { //setup(); System.out.println("hello im running bob"); /*int count = 1; do { System.out.println("Count is: " + count); count++; try{Thread.sleep(1);} catch(InterruptedException e){} } while (count <= 2000000);*/ //Game g =new Game(); //Game g = this; // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //setup(); //this.gameLoop(); //try{thread.sleep(1);} //catch{InterruptedException e} } /** * Construct our game and set it running. */ public Game () { //Thread t = new Thread(this);//set up new thread for invaders game //t.run();//run the run method of the game //Game g =new Game(); //setup(); //Thread t = new Thread(this); //thread.start(); //SwingUtilities.invokeLater(this); Thread er = new Thread(this); er.start(); } public void setup(){ //initialise highscore setHighscore(0); // create a frame to contain our game JFrame container = new JFrame("Space Invaders 101"); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(800,600)); //panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,800,600); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); // finally make the window visible container.pack(); container.setResizable(false); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //cThread.interrupt(); System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler()); // request the focus so key events come to us requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(2); strategy = getBufferStrategy(); // initialise the entities in our game so there's something // to see at startup initEntities(); } /** * Start a fresh game, this should clear out any old data and * create a new set. */ private void startGame() { // clear out any existing entities and intialise a new set entities.clear(); initEntities(); //initialise highscore setHighscore(0); // blank out any keyboard settings we might currently have leftPressed = false; rightPressed = false; firePressed = false; } /** * Initialise the starting state of the entities (ship and aliens). Each * entitiy will be added to the overall list of entities in the game. */ //private void initEntities() { public void initEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = 1.02; for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){ //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",100+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } } //private void initEntities() { public void initAlienEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal //ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side //entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = levelCount + 0.10;//this increases the speed on every level for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){//randome check to show alien //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",-250+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } advanceAlienSpeed(levelCount); } /** * Notification from a game entity that the logic of the game * should be run at the next opportunity (normally as a result of some * game event) */ public void updateLogic() { logicRequiredThisLoop = true; } /** * Remove an entity from the game. The entity removed will * no longer move or be drawn. * * @param entity The entity that should be removed */ public void removeEntity(Entity entity) { removeList.add(entity); } /** * Notification that the player has died. */ public void notifyDeath() { message = "Oh no! They got you, try again?"; waitingForKeyPress = true; } /** * Notification that the player has won since all the aliens * are dead. */ public void notifyWin() { message = "Well done! You Win!"; waitingForKeyPress = true; } /** * Notification that an alien has been killed */ public void notifyAlienKilled() { // reduce the alient count, if there are none left, the player has won! alienCount--; if (alienCount == 0) { //notifyWin();win not relevant here... this.initAlienEntities();//call fresh batch of aliens } // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens advanceAlienSpeed(1.30); } public void advanceAlienSpeed(double speed) { // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { // speed up by 2% entity.setHorizontalMovement(entity.getHorizontalMovement() * speed); //entity.setVerticalMovement(entity.getVerticalMovement() * 1.02); } } } /** * Attempt to fire a shot from the player. Its called "try" * since we must first check that the player can fire at this * point, i.e. has he/she waited long enough between shots */ public void tryToFire() { // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) { return; } // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30); entities.add(shot); } /** * The main game loop. This loop is running during all game * play as is responsible for the following activities: * <p> * - Working out the speed of the game loop to update moves * - Moving the game entities * - Drawing the screen contents (entities, text) * - Updating game events * - Checking Input * <p> */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); // keep looping round til the game ends while (gameRunning) { // work out how long its been since the last update, this // will be used to calculate how far the entities should // move this loop long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Get hold of a graphics context for the accelerated // surface and blank it out Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,800,600); // cycle round asking each entity to move itself if (!waitingForKeyPress) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } } // cycle round drawing all the entities we have in the game for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // brute force collisions, compare every entity against // every other entity. If any of them collide notify // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } // remove any entity that has been marked for clear up entities.removeAll(removeList); removeList.clear(); // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // their personal logic should be considered. if (logicRequiredThisLoop) { //g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } // if we're waiting for an "any key" press then draw the // current message //show highscore at top of screen //show name at top of screen g.setColor(Color.white); g.drawString("Player : "+getPlayer()+" : Score : "+getHighscore(),20,20); if (waitingForKeyPress) { g.setColor(Color.white); g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250); g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); } // finally, we've completed drawing so clear up the graphics // and flip the buffer over g.dispose(); strategy.show(); // resolve the movement of the ship. First assume the ship // isn't moving. If either cursor key is pressed then // update the movement appropraitely ship.setVerticalMovement(0);//set to vertical movement if ((leftPressed) && (!rightPressed)) { ship.setVerticalMovement(-moveSpeed);//**took out setHorizaontalMOvement } else if ((rightPressed) && (!leftPressed)) { ship.setVerticalMovement(moveSpeed);//**took out setHorizaontalMOvement } // if we're pressing fire, attempt to fire if (firePressed) { tryToFire(); } // finally pause for a bit. Note: this should run us at about // 100 fps but on windows this might vary each loop due to // a bad implementation of timer try { Thread.sleep(10); } catch (Exception e) {} } } /** * A class to handle keyboard input from the user. The class * handles both dynamic input during game play, i.e. left/right * and shoot, and more static type input (i.e. press any key to * continue) * * This has been implemented as an inner class more through * habbit then anything else. Its perfectly normal to implement * this as seperate class if slight less convienient. * * @author Kevin Glass */ private class KeyInputHandler extends KeyAdapter { /** The number of key presses we've had while waiting for an "any key" press */ private int pressCount = 1; /** * Notification from AWT that a key has been pressed. Note that * a key being pressed is equal to being pushed down but *NOT* * released. Thats where keyTyped() comes in. * * @param e The details of the key that was pressed */ public void keyPressed(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "press" if (waitingForKeyPress) { return; } // if (e.getKeyCode() == KeyEvent.VK_LEFT) { ////leftPressed = true; ///} //// if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_UP) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = true; } } /** * Notification from AWT that a key has been released. * * @param e The details of the key that was released */ public void keyReleased(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "released" if (waitingForKeyPress) { return; } if (e.getKeyCode() == KeyEvent.VK_UP) {//changed from VK_LEFT leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) {//changed from VK_RIGHT rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = false; } } /** * Notification from AWT that a key has been typed. Note that * typing a key means to both press and then release it. * * @param e The details of the key that was typed. */ public void keyTyped(KeyEvent e) { // if we're waiting for a "any key" type then // check if we've recieved any recently. We may // have had a keyType() event from the user releasing // the shoot or move keys, hence the use of the "pressCount" // counter. if (waitingForKeyPress) { if (pressCount == 1) { // since we've now recieved our key typed // event we can mark it as such and start // our new game waitingForKeyPress = false; startGame(); pressCount = 0; } else { pressCount++; } } // if we hit escape, then quit the game if (e.getKeyChar() == 27) { //cThread.interrupt(); System.exit(0); } } } /** * The entry point into the game. We'll simply create an * instance of class which will start the display and game * loop. * * @param argv The arguments that are passed into our game */ //public static void main(String argv[]) { //Game g =new Game(); // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //g.gameLoop(); //} }

    Read the article

  • Creating ActionEvent object for CustomButton in Java

    - by Crystal
    For a hw assignment, we were supposed to create a custom button to get familiar with swing and responding to events. We were also to make this button an event source which confuses me. I have an ArrayList to keep track of listeners that would register to listen to my CustomButton. What I am getting confused on is how to notify the listeners. My teacher hinted at having a notify and overriding actionPerformed which I tried doing, but then I wasn't sure how to create an ActionEvent object looking at the constructor documentation. The source, id, string all confuses me. Any help would be appreciated. Thanks! code: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class CustomButton { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CustomButtonFrame frame = new CustomButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } public void addActionListener(ActionListener al) { listenerList.add(al); } public void removeActionListener(ActionListener al) { listenerList.remove(al); } public void actionPerformed(ActionEvent e) { System.out.println("Button Clicked!"); } private void notifyListeners() { ActionEvent event = new ActionEvent(CONFUSED HERE!!!!; for (ActionListener action : listenerList) { action.actionPerfomed(event); } } List<ActionListener> listenerList = new ArrayList<ActionListener>(); } class CustomButtonFrame extends JFrame { // constructor for CustomButtonFrame public CustomButtonFrame() { setTitle("Custom Button"); CustomButtonSetup buttonSetup = new CustomButtonSetup(); this.add(buttonSetup); this.pack(); } } class CustomButtonSetup extends JComponent { public CustomButtonSetup() { ButtonAction buttonClicked = new ButtonAction(); this.addMouseListener(buttonClicked); } // because frame includes borders and insets, use this method public Dimension getPreferredSize() { return new Dimension(200, 200); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // first triangle coords int x[] = new int[TRIANGLE_SIDES]; int y[] = new int[TRIANGLE_SIDES]; x[0] = 0; y[0] = 0; x[1] = 200; y[1] = 0; x[2] = 0; y[2] = 200; Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES); // second triangle coords x[0] = 0; y[0] = 200; x[1] = 200; y[1] = 200; x[2] = 200; y[2] = 0; Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES); g2.drawPolygon(firstTriangle); g2.setColor(firstColor); g2.fillPolygon(firstTriangle); g2.drawPolygon(secondTriangle); g2.setColor(secondColor); g2.fillPolygon(secondTriangle); // draw rectangle 10 pixels off border int s1[] = new int[RECT_SIDES]; int s2[] = new int[RECT_SIDES]; s1[0] = 5; s2[0] = 5; s1[1] = 195; s2[1] = 5; s1[2] = 195; s2[2] = 195; s1[3] = 5; s2[3] = 195; Polygon rectangle = new Polygon(s1, s2, RECT_SIDES); g2.drawPolygon(rectangle); g2.setColor(thirdColor); g2.fillPolygon(rectangle); } private class ButtonAction implements MouseListener { public void mousePressed(MouseEvent e) { System.out.println("Click!"); firstColor = Color.GRAY; secondColor = Color.WHITE; repaint(); } public void mouseReleased(MouseEvent e) { System.out.println("Released!"); firstColor = Color.WHITE; secondColor = Color.GRAY; repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} } public static final int TRIANGLE_SIDES = 3; public static final int RECT_SIDES = 4; private Color firstColor = Color.WHITE; private Color secondColor = Color.DARK_GRAY; private Color thirdColor = Color.LIGHT_GRAY; }

    Read the article

  • JTable how to change BackGround Color

    - by mKorbel
    I inspired by MeBigFatGuy interesting question, in this conection I have very specific question about Graphisc2D, how to change BackGround Color by depends if is JTables Row visible in the JViewPort, 1) if 1st. & last JTables Row will be visible in the JViewPort, then BackGround would be colored to the Color.red 2) if 1st. & last JTables Row will not be visible in the JViewPort, then BackGround would be colored to the Color.whatever from SSCCE import java.awt.*; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import javax.swing.*; import javax.swing.RepaintManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.TableModel; /* http://stackoverflow.com/questions/1249278/ how-to-disable-the-default-painting-behaviour-of-wheel-scroll-event-on-jscrollpan * and * http://stackoverflow.com/questions/8195959/ swing-jtable-event-when-row-is-visible-or-when-scrolled-to-the-bottom */ public class ViewPortFlickering { private JFrame frame = new JFrame("Table"); private JViewport viewport = new JViewport(); private Rectangle RECT = new Rectangle(); private Rectangle RECT1 = new Rectangle(); private JTable table = new JTable(50, 3); private javax.swing.Timer timer; private int count = 0; public ViewPortFlickering() { GradientViewPort tableViewPort = new GradientViewPort(table); viewport = tableViewPort.getViewport(); viewport.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { RECT = table.getCellRect(0, 0, true); RECT1 = table.getCellRect(table.getRowCount() - 1, 0, true); Rectangle viewRect = viewport.getViewRect(); if (viewRect.intersects(RECT)) { System.out.println("Visible RECT -> " + RECT); } else if (viewRect.intersects(RECT1)) { System.out.println("Visible RECT1 -> " + RECT1); } else { // } } }); frame.add(tableViewPort); frame.setPreferredSize(new Dimension(600, 300)); frame.pack(); frame.setLocation(50, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RepaintManager.setCurrentManager(new RepaintManager() { @Override public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { Container con = c.getParent(); while (con instanceof JComponent) { if (!con.isVisible()) { return; } if (con instanceof GradientViewPort) { c = (JComponent) con; x = 0; y = 0; w = con.getWidth(); h = con.getHeight(); } con = con.getParent(); } super.addDirtyRegion(c, x, y, w, h); } }); frame.setVisible(true); start(); } private void start() { timer = new javax.swing.Timer(100, updateCol()); timer.start(); } public Action updateCol() { return new AbstractAction("text load action") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { System.out.println("updating row " + (count + 1)); TableModel model = table.getModel(); int cols = model.getColumnCount(); int row = 0; for (int j = 0; j < cols; j++) { row = count; table.changeSelection(row, 0, false, false); timer.setDelay(100); Object value = "row " + (count + 1) + " item " + (j + 1); model.setValueAt(value, count, j); } count++; if (count >= table.getRowCount()) { timer.stop(); table.changeSelection(0, 0, false, false); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { table.clearSelection(); } }); } } }; } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { ViewPortFlickering viewPortFlickering = new ViewPortFlickering(); } }); } } class GradientViewPort extends JScrollPane { private static final long serialVersionUID = 1L; private final int h = 50; private BufferedImage img = null; private BufferedImage shadow = new BufferedImage(1, h, BufferedImage.TYPE_INT_ARGB); private JViewport viewPort; public GradientViewPort(JComponent com) { super(com); viewPort = this.getViewport(); viewPort.setScrollMode(JViewport.BLIT_SCROLL_MODE); viewPort.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); viewPort.setScrollMode(JViewport.SIMPLE_SCROLL_MODE); Graphics2D g2 = shadow.createGraphics(); g2.setPaint(new Color(250, 150, 150)); g2.fillRect(0, 0, 1, h); g2.setComposite(AlphaComposite.DstIn); g2.setPaint(new GradientPaint(0, 0, new Color(0, 0, 0, 0f), 0, h, new Color(0.5f, 0.8f, 0.8f, 0.5f))); g2.fillRect(0, 0, 1, h); g2.dispose(); } @Override public void paint(Graphics g) { if (img == null || img.getWidth() != getWidth() || img.getHeight() != getHeight()) { img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); } Graphics2D g2 = img.createGraphics(); super.paint(g2); Rectangle bounds = getViewport().getVisibleRect(); g2.scale(bounds.getWidth(), -1); int y = (getColumnHeader() == null) ? 0 : getColumnHeader().getHeight(); g2.drawImage(shadow, bounds.x, -bounds.y - y - h, null); g2.scale(1, -1); g2.drawImage(shadow, bounds.x, bounds.y + bounds.height - h + y, null); g2.dispose(); g.drawImage(img, 0, 0, null); } }

    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

  • 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

  • Making interactive touch objects on Android

    - by Greenhouse_Gases
    I've never built a game before, and I've not programmed for Android before but am looking to do so over the summer by building a game. What type of object do I use for a shape that I want the user to be able to drag around the screen for instance using touch gestures? How do I tie together the MotionEvent, View and Graphics2D to make objects drawn on screen that can be interacted with? I imagine this will use ActionListeners / Handlers but I'm a bit confused at this stage... A simple breakdown of steps would be much appreciated. Thanks

    Read the article

  • How do I get my character to move after adding to JFrame?

    - by A.K.
    So this is kind of a follow up on my other JPanel question that got resolved by playing around with the Layout... Now my MouseListener allows me to add a new Board(); object from its class, which is the actual game map and animator itself. But since my Board() takes Key Events from a Player Object inside the Board Class, I'm not sure if they are being started. Here's my Frame Class, where SideScroller S is the player object: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Button; import java.awt.CardLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; JFrame frm = new JFrame("Action-Packed Jack"); ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel TitlePane = new JPanel(); public JPanel BoardPane = new JPanel(); JPanel cards; JButton StartB = new JButton(StartImg); Board nBoard = new Board(); static Sound nSound; public Frame() { frm.setLayout(new GridBagLayout()); cards = new JPanel(new CardLayout()); nSound = new Sound("/Sounds/BunchaJazz.wav"); TitleL.setPreferredSize(new Dimension(970, 420)); frm.add(TitleL); frm.add(cards); cards.setSize(new Dimension(150, 45)); cards.setLayout(new GridBagLayout ()); cards.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(150, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); frm.pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Frame(); } }); } public void mouseClicked(MouseEvent e) { nSound.play(); StartB.setContentAreaFilled(false); cards.remove(StartB); frm.remove(TitleL); frm.remove(cards); frm.setLayout(new GridLayout(1, 1)); frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200 nBoard.setPreferredSize(new Dimension(1200, 420)); cards.revalidate(); frm.validate(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Can't remove JPanel from JFrame while adding new class into it

    - by A.K.
    Basically, I have my Frame class, which instantiates all the properties for the JFrame, and draws a JLabel with an image (my title screen). Then I made a separate JPanel with a start button on it, and made a mouse listener that will allow me to remove these objects while adding in a new Board() class (Which paints the main game). *Note: The JLabel is SEPARATE from the JPanel, but it still gets moved to the side by it. Problem: Whenever I click the button though, it only shows a little square of what I presume is my board class trying to run. Code below for the Frame Class: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel panel = new JPanel(); JButton StartB = new JButton(StartImg); JFrame frm = new JFrame("Action-Packed Jack"); public Frame() { TitleL.setPreferredSize(new Dimension(1200, 420)); frm.add(TitleL); frm.setLayout(new GridBagLayout()); frm.add(panel); panel.setSize(new Dimension(220, 45)); panel.setLayout(new GridBagLayout ()); panel.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(220, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); } public static void main(String[] args) { new Frame(); } public void mouseClicked(MouseEvent e) { StartB.setContentAreaFilled(false); panel.remove(StartB); frm.remove(panel); frm.remove(TitleL); //frm.setLayout(null); frm.add(new Board()); //Add Game "Tiles" Or Content. x = 1200 frm.validate(); System.out.println("Hit!"); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Problem with using APACHE-POI to convert PPT to Image

    - by SpawnCxy
    Hi all, I got a problem when I try to use Apache POI project to convert my PPT to Images.My code as follows: FileInputStream is = new FileInputStream("test.ppt"); SlideShow ppt = new SlideShow(is); is.close(); Dimension pgsize = ppt.getPageSize(); Slide[] slide = ppt.getSlides(); for (int i = 0; i < slide.length; i++) { BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); //clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); //render slide[i].draw(graphics); //save the output FileOutputStream out = new FileOutputStream("slide-" + (i+1) + ".png"); javax.imageio.ImageIO.write(img, "png", out); out.close(); It works fine except that all Chinese words are converted to some squares.The png image I got is like following image: Then how can I fix this?Thanks in advance!

    Read the article

  • Using java2d user space measurements with TextLayout and LineBreakMeasurer

    - by Andrew Wheeler
    I have a java2d image defined in user space (mm) to print an identity card. The transformation to pixels is by using an AffineTransform for the required DPI (Screen or print). I want to wrap text across several lines but the the TextLayout does not respect user space co-ordinates. private void drawParagraph(Graphics2D g2d, Rectangle2D area, String text) { LineBreakMeasurer lineMeasurer; AttributedString string = new AttributedString(text); AttributedCharacterIterator paragraph = string.getIterator(); int paragraphStart = paragraph.getBeginIndex(); int paragraphEnd = paragraph.getEndIndex(); FontRenderContext frc = g2d.getFontRenderContext(); lineMeasurer = new LineBreakMeasurer(paragraph, frc); float breakWidth = (float)area.getWidth(); float drawPosY = (float)area.getY(); float drawPosX = (float)area.getX(); lineMeasurer.setPosition(paragraphStart); while (lineMeasurer.getPosition() < paragraphEnd) { TextLayout layout = lineMeasurer.nextLayout(breakWidth); drawPosY += layout.getAscent(); layout.draw(g2d, drawPosX, drawPosY); drawPosY += layout.getDescent() + layout.getLeading(); } } The above code determines font metrics using user space sizing of the Font and thus turn out rather large. The font size is calculated as best vertical fit for the number of lines in an area with the calculation as below. E.g. attr.put(TextAttribute.SIZE, (geTextArea().getHeight() / noOfLines - LINE_SPACING) ); When using g2d.drawString("Some text to display", x, y); the font size appears correct. Does anyone have a better way of doing text layout in user space co-ords?

    Read the article

  • How to effectively color pixels in a BufferedImage?

    - by Ed Taylor
    I'm using the following pice of code to iterate over all pixels in an image and draw a red 1x1 square over the pixels that are within a certain RGB-tolerance. I guess there is a more efficient way to do this? Any ideas appreciated. (bi is a BufferedImage and g2 is a Graphics2D with its color set to Color.RED). Color targetColor = new Color(selectedRGB); for (int x = 0; x < bi.getWidth(); x++) { for (int y = 0; y < bi.getHeight(); y++) { Color pixelColor = new Color(bi.getRGB(x, y)); if (withinTolerance(pixelColor, targetColor)) { g2.drawRect(x, y, 1, 1); } } } private boolean withinTolerance(Color pixelColor, Color targetColor) { int pixelRed = pixelColor.getRed(); int pixelGreen = pixelColor.getGreen(); int pixelBlue = pixelColor.getBlue(); int targetRed = targetColor.getRed(); int targetGreen = targetColor.getGreen(); int targetBlue = targetColor.getBlue(); return (((pixelRed >= targetRed - tolRed) && (pixelRed <= targetRed + tolRed)) && ((pixelGreen >= targetGreen - tolGreen) && (pixelGreen <= targetGreen + tolGreen)) && ((pixelBlue >= targetBlue - tolBlue) && (pixelBlue <= targetBlue + tolBlue))); }

    Read the article

  • How to scale JPEG images with a non-standard sampling factor in Java?

    - by HRJ
    I am using Java AWT for scaling a JPEG image, to create thumbnails. The code works fine when the image has a normal sampling factor ( 2x2,1x1,1x1 ) However, an image which has this sampling factor ( 1x1, 1x1, 1x1 ) creates problem when scaled. The colors get corrupted though the features are recognizable. The original and the thumbnail: The code I am using is roughly equivalent to: static BufferedImage awtScaleImage(BufferedImage image, int maxSize, int hint) { // We use AWT Image scaling because it has far superior quality // compared to JAI scaling. It also performs better (speed)! System.out.println("AWT Scaling image to: " + maxSize); int w = image.getWidth(); int h = image.getHeight(); float scaleFactor = 1.0f; if (w > h) scaleFactor = ((float) maxSize / (float) w); else scaleFactor = ((float) maxSize / (float) h); w = (int)(w * scaleFactor); h = (int)(h * scaleFactor); // since this code can run both headless and in a graphics context // we will just create a standard rgb image here and take the // performance hit in a non-compatible image format if any Image i = image.getScaledInstance(w, h, hint); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(i, null, null); g.dispose(); i.flush(); return image; } (Code courtesy of this page ) Is there a better way to do this? Here's a test image with sampling factor of [ 1x1, 1x1, 1x1 ].

    Read the article

  • Obtaining FontMetrics before getting a Graphics instance

    - by Tom Castle
    Typically, I'd obtain a graphics instance something like this: BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); However, in the current project I'm working on, the width and height variables above are dependent upon the size of a number of text fragments that will later be drawn onto the graphics instance. But, to obtain the dimensions of the font being used I would usually use the FontMetrics that I get from the graphics object. FontMetrics metrics = g.getFontMetrics(); So, I have a nasty little dependency cycle. I cannot create the graphics object until I know the size of the text, and I cannot know the size of the text until I have a graphics object. One solution is just to create another BufferedImage/Graphics pair first in order to get the FontMetrics instance I need, but this seems unnecessary. So, is there a nicer way? Or is it the case that the width, height etc. properties for a Font are somehow dependent upon what (graphics, component...) the text is to be drawn on?

    Read the article

  • scroll bar problems in java Layered Panes

    - by vondip
    Hi all, I've been trying to build this small java app. I find it very difficult to design UI in java, tasks that seem very simple become complicated and all these strange misbehaviors occur. In my app I've created a JLayeredPane which contains two layers. One on top on the other, They both contain scrollbars. Here's an explanation of the two layers: Layer 1: A very big image inside something similar to a scrollpane. The image is scrollable. Layer 2: A graphics2d object, this object draws an image. Once the image reaches a certain length, the layer gets a scrollpane that advances with the drawing with time. I'd like to connect both layers. I want layer two to update the scrollbar on layer 1. Meaning that once it reaches a certain length, both scrollbars will advance together. When I try doing that, the two scroll bars really do advance, but ( ! ) this strange flickering occurs. I don't understand what is the reason for the flickering. Is there any other way to implement this in a simple manner? I must have the second layer on top of the first one (drawing on top of image) since I cannot open a special post for thanking the wonderful people of this forum, I'll do it here. Thank you, you are great help. I hope this problem is solvable as well.

    Read the article

  • java setting resolution and print size for an Image

    - by Ingrid
    I wrote a program that generates a BufferedImage to be displayed on the screen and then printed. Part of the image includes grid lines that are 1 pixel wide. That is, the line is 1 pixel, with about 10 pixels between lines. Because of screen resolution, the image is displayed much bigger than that, with several pixels for each line. I'd like to draw it smaller, but when I scale the image (either by using Image.getScaledInstance or Graphics2D.scale), I lose significant amounts of detail. I'd like to print the image as well, and am dealing with the same problem. In that case, I am using this code to set the resolution: HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet(); PrinterResolution pr = new PrinterResolution(250, 250, ResolutionSyntax.DPI); set.add(pr); job.print(set); which works to make the image smaller without losing detail. But the problem is that the image is cut off at the same boundary as if I hadn't set the resolution. I'm also confused because I expected a larger number of DPI to make a smaller image, but it's working the other way. I'm using java 1.6 on Windows 7 with eclipse.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >