Search Results

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

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

  • Multiple Graphics2D Objects

    - by Trizicus
    I have a Graphics object of JPanel and that is working fine: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; public class GraphicsTest extends JPanel { private Graphics2D g2d; private String state; private int x, y; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; g2d.setClip(0, 0, getWidth(), getHeight()); g2d.setColor(Color.BLACK); g2d.drawString("STATE: " + state, 5, 15); g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30); g2d.setColor(Color.red); Rectangle2D r2d = new Rectangle2D.Double(x,y,10,10); g2d.draw(r2d); Test t = new Test(); super.add(t); repaint(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } } I was experimenting with a new Graphics component and when I instantiate a new Test and add it in GraphicsTest nothing happens. What is it that I am doing wrong? import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; public class Test extends JComponent { private Graphics2D g2d; private String state; private int x, y; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g.create(); g2d.setColor(Color.GREEN); g2d.fill(new Rectangle2D.Double(60, 60, 10, 10)); repaint(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } } Thanks!

    Read the article

  • [Java2D] Is this bad practice? Multiple Graphics2D Objects

    - by m00st
    I've created a JPanel canvas that holds all graphics; namely JLabel. To get animated sprites to work you have to over ride the paintComponent of the extended JLabel class. I've successfully implemented animated sprites this way. Is it bad practice to have a Graphics2D canvas and then have multiple 'images' in their own Graphics2D?

    Read the article

  • Using Graphics2D to overlay text on a BufferedImage and return a BufferedImage

    - by Andrew Bolster
    I have checked similarly named questions, but they don't answer this use case. Basically, I was to overlay some text (text) at a given coordinate (x,y) I have the below function in a package; protected BufferedImage Process2(BufferedImage image){ Graphics2D gO = image.createGraphics(); gO.setColor(Color.red); gO.setFont(new Font( "SansSerif", Font.BOLD, 12 )); gO.drawString(this.text, this.x, this.y); System.err.println(this.text+this.x+this.y); return image; } I feel like im missing something patently obvious; every reference to Graphics2D I can find is dealing with either games or writing directly to a file but I just want a BufferedImage returned. with the overlay 'rendered' In the current code, the image appears out the end unchanged. Thanks!

    Read the article

  • Render graphics using Doubles in Graphics2D

    - by thedeadlybutter
    Currently, I have a JFrame for my game to render in, and I'm using Graphics2D for drawing (The games graphics are fairly simple 2D sprites). However, my delta variable is a double, and all of the Graphics 2D methods (And Grpahics) use int. I tried to type cast the delta to an int, but it just rounds down to 0. So my question is, how can I render graphics using Graphics2D in Java with coordinates that are doubles. Can I convert it to work with Graphics2D if there is no built in way? Or, is there a graphics library that can support doubles for coordinates?

    Read the article

  • Cannot get right height of text in java.awt.BufferdImage/Graphics2D

    - by Tommy
    Im creating a servlet that renders a jpg/png with a given text. I want the text to be centered on the rendered image. I can get the width, but the height i'm getting seems to be wrong Font myfont = new Font(Font.SANS_SERIF, Font.BOLD, 400); BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setFont(myfont); g.setColor(Color.BLACK); FontMetrics fm = g.getFontMetrics(); Integer textwidth = fm.stringWidth(imagetext); Integer textheight = fm.getHeight(); FontRenderContext fr = g.getFontRenderContext(); LineMetrics lm = myfont.getLineMetrics("5", fr ); float ascent = lm.getAscent(); float descent = lm.getDescent(); float height = lm.getHeight(); g.drawString("5", ((imagewidth - textwidth) / 2) , y?); g.dispose(); ImageIO.write(image, "png", outputstream); These are the values I get: textwidth = 222 textheight = 504 ascent = 402 descent = 87 height = 503 Anyone know how to get the exact height om the "5" ? The estimated height should be around 250

    Read the article

  • Java Graphics2D DrawString....

    - by user69514
    Hey guys I have a little issue here. I have a panel where I am drawing a string. This is a game so I keep redrawing the score in order to update it. However when I draw it again it is drawn on top of the previous score so it looked all garbled up. Any ideas how to fix this? comp2d.drawString(GetScore(Score),ScoreX,ScoreY);

    Read the article

  • Java: Detecting image format, resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • Java: Detecting image formate - resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • Java - Layering issues with Lists and Graphics2D

    - by Mirrorcrazy
    So I have a DisplayPanel class that extends JPanel and that also paints my numerous images for my program using Graphics2D. In order to be able to easily customly use this I set it up so that every time the panel is repainted it uses a List, that I can add to or remove from as the program processes. My problem is with layering. I've run into an issue where the List must have reached its resizing point (or something whacky like that) and so the images i want to display end up beneath all of the other images already on the screen. I've come to the community for an answer because I have faith you will provide a good one. DisplayPanel: package earthworm; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; public class DisplayPanel extends JPanel { private List<ImageMap> images = new ArrayList(); public DisplayPanel() { setSize(800, 640); refresh(); } public void refresh() { revalidate(); repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.clearRect(0, 0, 800, 640); for(int i = 0; i < images.size(); i++) g2d.drawImage( images.get(i).getImage(), images.get(i).getX(), images.get(i).getY(), null); } public void paintImage(ImageMap[] images, ImageMap[] clearImages, boolean clear) { if(clear) this.images.clear(); else if(clearImages!=null) for(int i = 0; i < clearImages.length; i++) this.images.remove(clearImages[i]); if(images!=null) for(int i = 0; i<images.length; i++) this.images.add(images[i]); refresh(); } }

    Read the article

  • How can I rotate an image using Java/Swing and then set its origin to 0,0?

    - by JT
    I'm able to rotate an image that has been added to a JLabel. The only problem is that if the height and width are not equal, the rotated image will no longer appear at the JLabel's origin (0,0). Here's what I'm doing. I've also tried using AffineTransform and rotating the image itself, but with the same results. Graphics2D g2d = (Graphics2D)g; g2d.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2); super.paintComponent(g2d); If I have an image whose width is greater than its height, rotating that image using this method and then painting it will result in the image being painted vertically above the point 0,0, and horizontally to the right of the point 0,0.

    Read the article

  • How can I draw on JPanel using another quadrant for the coordinates?

    - by Sanoj
    I would like to draw some shapes on a JPanel by overriding paintComponent. I would like to be able to pan and zoom. Panning and zooming is easy to do with AffineTransform and the setTransform method on the Graphics2D object. After doing that I can easyli draw the shapes with g2.draw(myShape) The shapes are defined with the "world coordinates" so it works fine when panning and I have to translate them to the canvas/JPanel coordinates before drawing. Now I would like to change the quadrant of the coordinates. From the 4th quadrant that JPanel and computer often uses to the 1st quadrant that the users are most familiar with. The X is the same but the Y-axe should increase upwards instead of downwards. It is easy to redefine origo by new Point(origo.x, -origo.y); But How can I draw the shapes in this quadrant? I would like to keep the coordinates of the shapes (defined in the world coordinates) rather than have them in the canvas coordinates. So I need to transform them in some way, or transform the Graphics2D object, and I would like to do it efficiently. Can I do this with AffineTransform too?

    Read the article

  • Java Crossword Application - what package to use?

    - by Alex
    Hi guys, I'm about to create a java crossword application but I am unsure of what packages to use to draw the crossword grid. I know you can manually draw grids with Graphics2D etc. but I'm not sure if this is the easiest way to do it as I'll need text fields in the grid squares. Anyone have any suggestions as to creating the crossword grid.

    Read the article

  • Repaint() not calling paint() in Java

    - by Joshua Auriemma
    Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now. With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program. Entire code is below: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; public class Reflexology1 extends JFrame{ private static final long serialVersionUID = -1295261024563143679L; private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25); private Timer moveBallTimer; int _ballXpos, _ballYpos; JButton button1, button2; JButton movingButton; JTextArea textArea1; int buttonAClicked, buttonDClicked; private long _openTime = 0; private long _closeTime = 0; JPanel thePanel = new JPanel(); JPanel thePlacebo = new JPanel(); final JFrame frame = new JFrame("Reflexology"); final JFrame frame2 = new JFrame("The Test"); JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can."); public static void main(String[] args){ new Reflexology1(); } public Reflexology1(){ frame.setSize(600, 475); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Reflexology 1.0"); frame.setResizable(false); frame2.setSize(600, 475); frame2.setLocationRelativeTo(null); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setTitle("Reflexology 1.0"); frame2.setResizable(false); button1 = new JButton("Accept"); button2 = new JButton("Decline"); //movingButton = new JButton("Click Me"); ListenForAcceptButton lForAButton = new ListenForAcceptButton(); ListenForDeclineButton lForDButton = new ListenForDeclineButton(); button1.addActionListener(lForAButton); button2.addActionListener(lForDButton); //movingButton.addActionListener(lForMButton); JTextArea textArea1 = new JTextArea(24, 50); textArea1.setText("Tracking Events\n"); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setSize(15, 50); textArea1.setEditable(false); FileReader reader = null; try { reader = new FileReader("EULA.txt"); textArea1.read(reader, "EULA.txt"); } catch (IOException exception) { System.err.println("Problem loading file"); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException exception) { System.err.println("Error closing reader"); exception.printStackTrace(); } } } JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); AdjustmentListener listener = new MyAdjustmentListener(); thePanel.add(scrollBar1); thePanel.add(button1); thePanel.add(button2); frame.add(thePanel); ListenForMouse lForMouse = new ListenForMouse(); thePlacebo.addMouseListener(lForMouse); thePlacebo.add(label1); frame2.add(thePlacebo); ListenForWindow lForWindow = new ListenForWindow(); frame.addWindowListener(lForWindow); frame2.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();} } }); frame.setVisible(true); moveBallTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { moveBall(); System.out.println("Timer started!"); repaint(); } }); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(frame2.isVisible()){ moveBallTimer.start(); } } }); } private class ListenForAcceptButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button1){ Calendar ClCDateTime = Calendar.getInstance(); System.out.println(ClCDateTime.getTimeInMillis() - _openTime); _closeTime = ClCDateTime.getTimeInMillis() - _openTime; //frame.getContentPane().remove(thePanel); //thePlacebo.addKeyListener(lForKeys); //frame.getContentPane().add(thePlacebo); //frame.repaint(); //moveBallTimer.start(); frame.setVisible(false); frame2.setVisible(true); frame2.revalidate(); frame2.repaint(); } } } private class ListenForDeclineButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button2){ JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } private class ListenForWindow implements WindowListener{ public void windowActivated(WindowEvent e) { //textArea1.append("Window is active"); } // if this.dispose() is called, this is called: public void windowClosed(WindowEvent arg0) { } // When a window is closed from a menu, this is called: public void windowClosing(WindowEvent arg0) { } // Called when the window is no longer the active window: public void windowDeactivated(WindowEvent arg0) { //textArea1.append("Window is NOT active"); } // Window gone from minimized to normal state public void windowDeiconified(WindowEvent arg0) { //textArea1.append("Window is in normal state"); } // Window has been minimized public void windowIconified(WindowEvent arg0) { //textArea1.append("Window is minimized"); } // Called when the Window is originally created public void windowOpened(WindowEvent arg0) { //textArea1.append("Let there be Window!"); Calendar OlCDateTime = Calendar.getInstance(); _openTime = OlCDateTime.getTimeInMillis(); //System.out.println(_openTime); } } private class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent arg0) { AdjustmentEvent scrollBar1; //System.out.println(scrollBar1.getValue())); } } public void paint(Graphics g) { //super.paint(g); frame2.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(ball); System.out.println("Calling fill()"); } protected void moveBall() { //System.out.println("I'm in the moveBall() function!"); int width = getWidth(); int height = getHeight(); int min, max, randomX, randomY; min =200; max = -200; randomX = min + (int)(Math.random() * ((max - min)+1)); randomY = min + (int)(Math.random() * ((max - min)+1)); //System.out.println(randomX + ", " + randomY); Rectangle ballBounds = ball.getBounds(); //System.out.println(ballBounds.x + ", " + ballBounds.y); if (ballBounds.x + randomX < 0) { randomX = 200; } else if (ballBounds.x + ballBounds.width + randomX > width) { randomX = -200; } if (ballBounds.y + randomY < 0) { randomY = 200; } else if (ballBounds.y + ballBounds.height + randomY > height) { randomY = -200; } ballBounds.x += randomX; ballBounds.y += randomY; _ballXpos = ballBounds.x; _ballYpos = ballBounds.y; ball.setFrame(ballBounds); } public void start() { moveBallTimer.start(); } public void stop() { moveBallTimer.stop(); } private class ListenForMouse implements MouseListener{ // Called when the mouse is clicked public void mouseClicked(MouseEvent e) { //System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n"); if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) { System.out.println("TRUE"); } System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } // System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos); // Mouse over public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse left the mouseover area: public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.

    Read the article

  • Kerning problems when drawing text character by character

    - by shekel
    I'm trying to draw strings character by character to add lighting effects to shapes composed of text. while (i != line.length()) { c = line.substring(i, i + 1); cWidth = g.getFontMetrics().stringWidth(c); g.drawString(c, xx += cWidth, yy); i++; } The problem is, the width of a character isn't the actual distance it's drawn from another character when those two characters are printed as a string. Is there any way to get the correct distance in graphics2d?

    Read the article

  • How to print a page when a JButton is pressed in java swing using PrinterJob?

    - by Prayag Upd
    I tried the following code AWT but at runtime shows multiple print dialogs repeatedly.... package printerjob; import java.awt.BasicStroke; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.WindowAdapter; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; /** * * @author pragX */ public class FramePrinterJob extends Frame implements Printable{ public void start(){ add(button); } @Override public void paint(Graphics graphics){ PrinterJob printerJob=PrinterJob.getPrinterJob(); printerJob.setPrintable(this); if(printerJob.printDialog()){ try{ printerJob.print(); }catch(PrinterException printerException){ //printerException.printStackTrace(); System.out.println("Error Printing." + printerException); } } } public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { //throw new UnsupportedOperationException("Not supported yet."); if(pageIndex>=1){ return Printable.NO_SUCH_PAGE; } graphics.translate((int) pageFormat.getImageableX(), (int)pageFormat.getImageableY()); Graphics2D graphics2D=(Graphics2D)graphics; graphics2D.setStroke(new BasicStroke(4f)); graphics2D.drawLine(20, 20, 20, 120); graphics2D.drawLine(40, 20, 40, 120); graphics2D.drawLine(20, 70, 40, 70); graphics2D.drawLine(60, 70, 60, 120); graphics2D.drawLine(60, 40, 60, 45); return Printable.PAGE_EXISTS; } public static void main(String args[]){ Frame frame=new FramePrinterJob(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(){System.exit(0);}}); frame.setSize(300,400); frame.setVisible(true); } }

    Read the article

  • Path to background in servlet

    - by kapil chhattani
    //the below line is the element of my HTML form which renders the image sent by the servlet written further below. <img style="margin-left:91px; margin-top:-6px;" class="image" src="http://www.abcd.com/captchaServlet"> I generate a captcha code using the following code in java. public class captchaServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int width = 150; int height = 50; int charsToPrint = 6; String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy1234567890"; char[] chars = elegibleChars.toCharArray(); StringBuffer finalString = new StringBuffer(); for ( int i = 0; i < charsToPrint; i++ ) { double randomValue = Math.random(); int randomIndex = (int) Math.round(randomValue * (chars.length - 1)); char characterToShow = chars[randomIndex]; finalString.append(characterToShow); } System.out.println(finalString); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); Font font = new Font("Georgia", Font.BOLD, 18); g2d.setFont(font); RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHints(rh); GradientPaint gp = new GradientPaint(0, 0, Color.BLUE, 0, height/2, Color.black, true); g2d.setPaint(gp); g2d.fillRect(0, 0, width, height); g2d.setColor(new Color(255, 255, 0)); Random r = new Random(); int index = Math.abs(r.nextInt()) % 5; char[] data=new String(finalString).toCharArray(); String captcha = String.copyValueOf(data); int x = 0; int y = 0; for (int i=0; i<data.length; i++) { x += 10 + (Math.abs(r.nextInt()) % 15); y = 20 + Math.abs(r.nextInt()) % 20; g2d.drawChars(data, i, 1, x, y); } g2d.dispose(); response.setContentType("image/png"); OutputStream os = response.getOutputStream(); ImageIO.write(bufferedImage, "png", os); os.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } But in the above code background is also generated using the setPaint menthod I am guessing. I want the background to be some image from my local machine whoz URL i should be able to mention like URL url=this.getClass().getResource("Desktop/images.jpg"); BufferedImage bufferedImage = ImageIO.read(url); I am just writing the above two lines for making the reader understand better what the issue is. Dont want to use the exact same commands. All I want is the the background of the captcha code generated should be an image of my choice.

    Read the article

  • How to calculate the length of a Path2D in Java?

    - by Sanoj
    I have some paths represented by Path2D. The Path consist of multiple CubicCurve2D or Line2D segments that are connected to each other. I would like to calculate or get the length from the start to the end of a Path. How can I calculate it or get it? Is it possible? I have checked the API documentation, but couldn't find any useful methods.

    Read the article

  • Java2D: Fill a convex rounded polygon (QuadCurves)

    - by Martijn Courteaux
    Hi, If I have a QuadCurve like this (+ = node): + + \ ./ +--?? And I fill it in Java 2D the result is something like this: (x = colored) +xxxxxxxxx+ \xxxxxx./ +--?? But I want to color the other side: + + x\ ./x xxx +--??xx xxxxxxxxxxx This succeeds by drawing a rectangle around the curve in the color I want to color the other side and then fill the curve with the background color. But this isn't good enough to fill a convex rounded (based on QuadCurves) polygon. In case of some coordinates for the rectangles (as explained in the trick I used) overlap other pieces of the polygon. Here are two images (the green area is my polygon): So, the question is simple: "How can I color a shape build of curves?" But to the answer will not be simple I think... Any advice would be VERY VERY appreciated. Thanks in advance. Maybe I'm going to make a bounty for this question if I don't get an answer

    Read the article

  • paintComponent on JPanel, image flashes and then disappears

    - by mark
    I have a JApplet (MainClass extends JApplet), a JPanel (ChartWindow extends JPanel) and a Grafico class. The problem is that the Grafico class instance has 2 JPanel that should show 2 images (1 for each panel) but the images are shown and after a little while they disappears: instead of them i get a gray background (like an empty JPanel). This happens for every repaint() call (that are made in the ChartWindow class) the MainClass init() contains chartwindow=new ChartWindow(); add(chartwindow) chartwindow has a Grafico instance. it's the ChartWindow's paintComponent (override) paintComponent(Graphics g) { super.paintComponent(g); Image immagineGrafico=createImage(grafico.pannelloGrafico.getWidth() ,grafico.pannelloGrafico.getHeight()); Image immagineVolumi=createImage(grafico.pannelloVolumi.getWidth() ,grafico.pannelloVolumi.getHeight()); Graphics2D imgGrafico=(Graphics2D)immagineGrafico.getGraphics(); Graphics2D imgVolumi=(Graphics2D)immagineVolumi.getGraphics(); grafico.draw(imgGrafico,imgVolumi,mouseX,mouseY); ((Graphics2D)grafico.pannelloGrafico.getGraphics()).drawImage(immagineGrafico,0,0,this); ((Graphics2D)grafico.pannelloVolumi.getGraphics()).drawImage(immagineVolumi,0,0,this); } grafico's JPanels are added this way in the ChartWindow's constructor grafico=new Grafico() ................ add(grafico.pannelloGrafico); add(grafico.pannelloVolumi); Tell me if you need more information, thank you very much :-)

    Read the article

  • How to save image drawn on a JPanel?

    - by swift
    I have a panel with transparent background which i use to draw an image. now problem here is when i draw anything on panel and save the image as a JPEG file its saving the image with black background but i want it to be saved as same, as i draw on the panel. what should be done for this? plz guide me j Client.java public class Client extends Thread { static DatagramSocket datasocket; static DatagramSocket socket; Point point; Whiteboard board; Virtualboard virtualboard; JLayeredPane layerpane; BufferedImage image; public Client(DatagramSocket datasocket) { Client.datasocket=datasocket; } //This function is responsible to connect to the server public static void connect() { try { socket=new DatagramSocket (9000); //client connection socket port= 9000 datasocket=new DatagramSocket (9005); //client data socket port= 9002 ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //this is to tell server that this is a connection request dos.writeChar('c'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); //create the UDP packet DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); Client client=new Client(datasocket); client.createFrame(); client.run(); } catch(Exception e) { e.printStackTrace(); } } //This function is to create the JFrame public void createFrame() { JFrame frame=new JFrame("Whiteboard"); frame.setVisible(true); frame.setBackground(Color.black); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(680,501); frame.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { close(); } }); layerpane=frame.getLayeredPane(); board= new Whiteboard(datasocket); image = new BufferedImage(590,463, BufferedImage.TYPE_INT_ARGB); board.setBounds(74,2,590,463); board.setImage(image); virtualboard=new Virtualboard(); virtualboard.setImage(image); virtualboard.setBounds(74,2,590,463); layerpane.add(virtualboard,new Integer(2));//Panel where remote user draws layerpane.add(board,new Integer(3)); layerpane.add(board.colourButtons(),new Integer(1)); layerpane.add(board.shapeButtons(),new Integer(0)); //frame.add(paper.addButtons(),BorderLayout.WEST); } /* * This function is overridden from the thread class * This function listens for incoming packets from the server * which contains the points drawn by the other client */ public void run () { while (true) { try { byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datasocket.receive(packet); InputStream in=new ByteArrayInputStream(packet.getData(), packet.getOffset(),packet.getLength()); DataInputStream din=new DataInputStream(in); int x=din.readInt(); int y=din.readInt(); String varname=din.readLine(); String var[]=varname.split("-",4); point=new Point(x,y); virtualboard.addPoint(point, var[0], var[1],var[2],var[3]); } catch (IOException ex) { ex.printStackTrace(); } } } //This function is to broadcast the newly drawn point to the server public void broadcast (Point p,String varname,String shape,String event, String color) { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); dos.writeInt(p.x); dos.writeInt(p.y); dos.writeBytes(varname); dos.writeBytes("-"); dos.writeBytes(shape); dos.writeBytes("-"); dos.writeBytes(event); dos.writeBytes("-"); dos.writeBytes(color); dos.close(); byte[]data=baos.toByteArray(); InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8002); datasocket.send(packet); } catch (Exception e) { e.printStackTrace(); } } //This function is to close the client's connection with the server public void close() { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); //This is to tell server that this is request to remove the client dos.writeChar('r'); dos.close(); byte[]data=baos.toByteArray(); //Server IP address InetAddress ip=InetAddress.getByName("10.123.97.154"); DatagramPacket packet=new DatagramPacket(data, data.length,ip , 8000); socket.send(packet); System.out.println("closed"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { connect(); } } Whiteboard.java class Whiteboard extends JPanel implements MouseListener,MouseMotionListener,ActionListener,KeyListener { BufferedImage image; Boolean tooltip=false; int post; String shape; String selectedcolor="black"; Color color=Color.black; //Color color=Color.white; Point start; Point end; Point mp; Point tip; int keycode; String fillshape; Point fillstart=new Point(); Point fillend=new Point(); int noofside; Button r=new Button("rect"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button roundrect=new Button("roundrect"); Button polygon=new Button("poly"); Button text=new Button("text"); JButton save=new JButton("Save"); Button elipse=new Button("elipse"); ImageIcon fillicon=new ImageIcon("images/fill.jpg"); JButton fill=new JButton(fillicon); ImageIcon erasericon=new ImageIcon("images/eraser.gif"); JButton erase=new JButton(erasericon); JButton[] colourbutton=new JButton[28]; String selected; Point label; String key=""; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Boolean first; int w,h; public Whiteboard(DatagramSocket dataSocket) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } setLayout(null); setOpaque(false); setBackground(new Color(237,237,237)); this.dataSocket=dataSocket; client=new Client(dataSocket); addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { try { super.paintComponent(g); g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; if(color!=null) g2.setPaint(color); if(start!=null && end!=null) { if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "drag", selectedcolor); client.broadcast(end, "end", "poly", "drag", selectedcolor); } } if(tooltip==true) { System.out.println(selected); if(selected=="text") { g2.drawString("|", tip.x, tip.y-5); g2.drawString("Click to add text", tip.x+10, tip.y+23); g2.drawString("__", label.x+post, label.y); } if(selected=="erase") { g2.setPaint(new Color(237,237,237)); g2.fillRect(tip.x-10,tip.y-10,10,10); g2.setPaint(color); g2.drawRect(tip.x-10,tip.y-10,10,10); } } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = (Graphics2D) image.createGraphics(); Font font=new Font("Times New Roman",Font.PLAIN,14); g2.setFont(font); g2.setPaint(color); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("rrect")) g2.drawRoundRect(start.x, start.y, (end.x-start.x),(end.y-start.y),11,11); else if(selected==("poly")) { g2.drawLine(start.x,start.y,end.x,end.y); client.broadcast(start, "start", "poly", "release", selectedcolor); client.broadcast(end, "end", "poly", "release", selectedcolor); } fillstart=start; fillend=end; fillshape=selected; } if(selected!="poly") { start=null; end=null; } if(label!=null) { if(selected==("text")) { g2.drawString(key,label.x,label.y); client.broadcast(label, key, "text", "release", selectedcolor); } } repaint(); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.createGraphics(); Color erasecolor=new Color(237,237,237); pic.setPaint(erasecolor); if(start!=null) pic.fillRect(start.x-10, start.y-10, 10, 10); } //To set the size of the image public void setImage(BufferedImage image) { this.image = image; } //Function to add buttons into the panel, calling this function returns a panel public JPanel shapeButtons() { JPanel shape=new JPanel(); shape.setBackground(new Color(181, 197, 210)); shape.setLayout(new GridLayout(5,2,2,4)); shape.setBounds(0, 2, 74, 166); rectangle.addActionListener(this); rectangle.setToolTipText("Rectangle"); line.addActionListener( this); line.setToolTipText("Line"); erase.addActionListener(this); erase.setToolTipText("Eraser"); roundrect.addActionListener(this); roundrect.setToolTipText("Round edge Rectangle"); polygon.addActionListener(this); polygon.setToolTipText("Polygon"); text.addActionListener(this); text.setToolTipText("Text"); fill.addActionListener(this); fill.setToolTipText("Fill with colour"); elipse.addActionListener(this); elipse.setToolTipText("Elipse"); save.addActionListener(this); shape.add(elipse); shape.add(rectangle); shape.add(roundrect); shape.add(polygon); shape.add(line); shape.add(text); shape.add(fill); shape.add(erase); shape.add(save); return shape; } public JPanel colourButtons() { JPanel colourbox=new JPanel(); colourbox.setBackground(new Color(181, 197, 210)); colourbox.setLayout(new GridLayout(8,2,8,8)); colourbox.setBounds(0,323,70,140); //colourbox.add(empty); for(int i=0;i<16;i++) { colourbutton[i]=new JButton(); colourbox.add(colourbutton[i]); if(i==0) colourbutton[0].setBackground(Color.black); else if(i==1) colourbutton[1].setBackground(Color.white); else if(i==2) colourbutton[2].setBackground(Color.red); else if(i==3) colourbutton[3].setBackground(Color.orange); else if(i==4) colourbutton[4].setBackground(Color.blue); else if(i==5) colourbutton[5].setBackground(Color.green); else if(i==6) colourbutton[6].setBackground(Color.pink); else if(i==7) colourbutton[7].setBackground(Color.magenta); else if(i==8) colourbutton[8].setBackground(Color.cyan); else if(i==9) colourbutton[9].setBackground(Color.black); else if(i==10) colourbutton[10].setBackground(Color.yellow); else if(i==11) colourbutton[11].setBackground(new Color(131,168,43)); else if(i==12) colourbutton[12].setBackground(new Color(132,0,210)); else if(i==13) colourbutton[13].setBackground(new Color(193,17,92)); else if(i==14) colourbutton[14].setBackground(new Color(129,82,50)); else if(i==15) colourbutton[15].setBackground(new Color(64,128,128)); colourbutton[i].addActionListener(this); } return colourbox; } public void fill() { if(selected=="fill") { Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(color); System.out.println("Fill"); if(fillshape=="elipse") g2.fillOval(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape=="rect") g2.fillRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y)); else if(fillshape==("rrect")) g2.fillRoundRect(fillstart.x, fillstart.y, (fillend.x-fillstart.x),(fillend.y-fillstart.y),11,11); // else if(fillshape==("poly")) // g2.drawPolygon(x,y,2); } repaint(); } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="text") { start=e.getPoint(); client.broadcast(start,"start", selected,"press", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") mp = e.getPoint(); else if(selected=="poly") { if(first==true) { start=e.getPoint(); //client.broadcast(start,"start", selected,"press", selectedcolor); } else if(first==false) { end=e.getPoint(); repaint(); //client.broadcast(end,"end", selected,"press", selectedcolor); } } else if(selected=="erase") { start=e.getPoint(); erase(); } } public void mouseReleased(MouseEvent e) { if(selected=="text") { System.out.println("Reset"); key=""; post=0; label=new Point(); label=e.getPoint(); grabFocus(); } if(start!=null && end!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release", selectedcolor); draw(); } else if(selected=="poly") { draw(); first=false; start=end; end=null; } } } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag", selectedcolor); } else if(selected=="elipse"||selected=="rect"||selected=="rrect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag", selectedcolor); client.broadcast(end,"end", selected,"drag", selectedcolor); } else if(selected=="poly") end=e.getPoint(); System.out.println(tooltip); if(tooltip==true) { if(selected=="erase") { Graphics2D g2=(Graphics2D) getGraphics(); tip=e.getPoint(); g2.drawRect(tip.x-10,tip.y-10,10,10); } } repaint(); } public void mouseMoved(MouseEvent e) { if(selected=="text" ||selected=="erase") { tip=new Point(); tip=e.getPoint(); tooltip=true; repaint(); } } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; else if(e.getSource()==line) selected="line"; else if(e.getSource()==rectangle) selected="rect"; else if(e.getSource()==erase) { selected="erase"; tooltip=true; System.out.println(selected); erase(); } else if(e.getSource()==roundrect) selected="rrect"; else if(e.getSource()==polygon) { selected="poly"; first=true; start=null; } else if(e.getSource()==text) { selected="text"; tooltip=true; } else if(e.getSource()==fill) { selected="fill"; fill(); } else if(e.getSource()==save) save(); if(e.getSource()==colourbutton[0]) { color=Color.black; selectedcolor="black"; } else if(e.getSource()==colourbutton[1]) { color=Color.white; selectedcolor="white"; } else if(e.getSource()==colourbutton[2]) { color=Color.red; selectedcolor="red"; } else if(e.getSource()==colourbutton[3]) { color=Color.orange; selectedcolor="orange"; } else if(e.getSource()==colourbutton[4]) { selectedcolor="blue"; color=Color.blue; } else if(e.getSource()==colourbutton[5]) { selectedcolor="green"; color=Color.green; } else if(e.getSource()==colourbutton[6]) { selectedcolor="pink"; color=Color.pink; } else if(e.getSource()==colourbutton[7]) { selectedcolor="magenta"; color=Color.magenta; } else if(e.getSource()==colourbutton[8]) { selectedcolor="cyan"; color=Color.cyan; } } @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyChar()+" : "+e.getKeyCode()); if(label!=null) { if(e.getKeyCode()==10) //Check for Enter key { label.y=label.y+14; key=""; post=0; repaint(); } else if(e.getKeyCode()==8) //Backspace { try{ Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setPaint(new Color(237,237,237)); g2.fillRect(label.x+post-7, label.y-13, 14, 17); if(post>0) post=post-6; keycode=0; key=key.substring(0, key.length()-1); System.out.println(key.substring(0, key.length())); repaint(); Point broadcastlabel=new Point(); broadcastlabel.x=label.x+post-7; broadcastlabel.y=label.y-13; client.broadcast(broadcastlabel, key, "text", "backspace", selectedcolor); } catch(Exception ex) {} } //Block invalid keys else if(!(e.getKeyCode()>=16 && e.getKeyCode()<=20 || e.getKeyCode()>=112 && e.getKeyCode()<=123 || e.getKeyCode()>=33 && e.getKeyCode()<=40 || e.getKeyCode()>=144 && e.getKeyCode()<=145 || e.getKeyCode()>=524 && e.getKeyCode()<=525 ||e.getKeyCode()==27||e.getKeyCode()==155 ||e.getKeyCode()==127)) { key=key+e.getKeyChar(); post=post+6; draw(); } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } class Button extends JButton { String name; int i; public Button(String name) { this.name=name; try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } } public Button(int i) { this.i=i; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); if (name== "roundrect") g.drawRoundRect(5,5,25,23,10,10); int a[]=new int[]{20,9,20,23,20}; int b[]=new int[]{9,23,25,20,9}; if (name== "poly") g.drawPolyline(a, b, 5); if (name== "text") g.drawString("Text",8, 24); } }

    Read the article

  • Custom JComponent not displaying in Custom JPanel

    - by Trizicus
    I've tried the add() method but nothing is displayed when I try to add Test to GraphicsTest. How should I be adding it? Can someone show me? I've included the code I'm using. import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JComponent; public class Test extends JComponent { Test() { setOpaque(false); setBackground(Color.white); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("Hello", 50, 50); g2d.dispose(); } } import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; public class GraphicsTest extends JPanel implements MouseListener { private Graphics2D g2d; private String state; private int x, y; GraphicsTest() { add(new Test()); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g2d = (Graphics2D) g; g2d.setColor(Color.BLACK); g2d.drawString("STATE: " + state, 5, 15); g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30); g2d.setColor(Color.red); Rectangle2D r2d = new Rectangle2D.Double(x, y, 10, 10); g2d.draw(r2d); g2d.dispose(); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void setX(int x) { this.x = x; repaint(); } public void setY(int y) { this.y = y; repaint(); } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

    Read the article

  • Jframe using multiple classes?

    - by user2945880
    and im trying to make it so it can show multiple classes at once Jframe: import javax.swing.JFrame; import java.awt.BorderLayout; public class Concert { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(1000, 800); frame.setTitle("Concert!"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Concertbackground component = new Concertbackground(); BandComponent component1 = new BandComponent(); frame.add(component, BorderLayout.NORTH); frame.add(component1, BorderLayout.CENTER); frame.setVisible(true); } } These are the two classes mentioned in the Jframe: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import javax.swing.JComponent; import java.awt.Polygon; /* BandComponent.java Justin Walker 10/27/13 */ public class BandComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; int xScale = 250; int yScale = 100; int x = 343; int y = 343; //singer Polygon sing = new Polygon(); sing.addPoint(667 ,208 + xScale); sing.addPoint(676,213 + xScale); sing.addPoint(678,217 + xScale); sing.addPoint(682,221 + xScale); sing.addPoint(681,224 + xScale); sing.addPoint(680,231 + xScale); sing.addPoint(676,242 + xScale); sing.addPoint(672,244 + xScale); sing.addPoint(672,250 + xScale); sing.addPoint(682,248 + xScale); sing.addPoint(713,244 + xScale); sing.addPoint(734,247 + xScale); sing.addPoint(750,247 + xScale); sing.addPoint(794,232 + xScale); sing.addPoint(800,231 + xScale); sing.addPoint(801,223 + xScale); sing.addPoint(807,219 + xScale); sing.addPoint(806,221 + xScale); sing.addPoint(806,229 + xScale); sing.addPoint(818,222 + xScale); sing.addPoint(820,223 + xScale); sing.addPoint(825,227 + xScale); sing.addPoint(825,240 + xScale); sing.addPoint(817,243 + xScale); sing.addPoint(807,245 + xScale); sing.addPoint(803,247 + xScale); sing.addPoint(801,252 + xScale); sing.addPoint(781,257 + xScale); sing.addPoint(762,264 + xScale); sing.addPoint(734,271 + xScale); sing.addPoint(701,286 + xScale); sing.addPoint(691,296 + xScale); sing.addPoint(693,311 + xScale); sing.addPoint(690,317 + xScale); sing.addPoint(690,335 + xScale); sing.addPoint(691,339 + xScale); sing.addPoint(689,343 + xScale); sing.addPoint(712,382 + xScale); sing.addPoint(725,400 + xScale); sing.addPoint(731,418 + xScale); sing.addPoint(731,428 + xScale); sing.addPoint(738,454 + xScale); sing.addPoint(741,460 + xScale); sing.addPoint(746,468 + xScale); sing.addPoint(766,468 + xScale); sing.addPoint(771,481 + xScale);// sing.addPoint(723,482 + xScale); sing.addPoint(720,462 + xScale); sing.addPoint(718,454 + xScale); sing.addPoint(709,436 + xScale); sing.addPoint(703,436 + xScale); sing.addPoint(699,417 + xScale); sing.addPoint(686,396 + xScale); sing.addPoint(678,395 + xScale); sing.addPoint(676,437 + xScale); sing.addPoint(673,439 + xScale); sing.addPoint(638,435 + xScale); sing.addPoint(640,398 + xScale); sing.addPoint(634,410 + xScale); sing.addPoint(625,416 + xScale); sing.addPoint(622,436 + xScale); sing.addPoint(622,443 + xScale); sing.addPoint(615,447 + xScale); sing.addPoint(609,456 + xScale); sing.addPoint(606,481 + xScale);// sing.addPoint(557,481 + xScale); sing.addPoint(560,467 + xScale); sing.addPoint(579,467 + xScale); sing.addPoint(587,464 + xScale); sing.addPoint(593,452 + xScale); sing.addPoint(594,441 + xScale); sing.addPoint(592,434 + xScale); sing.addPoint(600,416 + xScale); sing.addPoint(608,405 + xScale); sing.addPoint(609,394 + xScale); sing.addPoint(617,376 + xScale); sing.addPoint(619,363 + xScale); sing.addPoint(632,334 + xScale); sing.addPoint(637,324 + xScale); sing.addPoint(635,314 + xScale); sing.addPoint(639,296 + xScale); sing.addPoint(627,285 + xScale); sing.addPoint(600,279 + xScale); sing.addPoint(582,278 + xScale); sing.addPoint(575,275 + xScale); sing.addPoint(546,256 + xScale); sing.addPoint(536,252 + xScale); sing.addPoint(533,350 + xScale); sing.addPoint(534,361 + xScale); sing.addPoint(532,367 + xScale); sing.addPoint(529,369 + xScale); sing.addPoint(524,363 + xScale); sing.addPoint(525,355 + xScale); sing.addPoint(531,254 + xScale); sing.addPoint(527,249 + xScale); sing.addPoint(527,242 + xScale); sing.addPoint(529,237 + xScale); sing.addPoint(532,237 + xScale); sing.addPoint(536,178 + xScale); sing.addPoint(534,129 + xScale); sing.addPoint(535,123 + xScale); sing.addPoint(541,120 + xScale); sing.addPoint(545,123 + xScale); sing.addPoint(547,131 + xScale); sing.addPoint(545,173 + xScale); sing.addPoint(538,233 + xScale); sing.addPoint(549,239 + xScale); sing.addPoint(558,241 + xScale); sing.addPoint(585,257 + xScale); sing.addPoint(599,257 + xScale); sing.addPoint(627,254 + xScale); sing.addPoint(647,251 + xScale); sing.addPoint(653,248 + xScale); sing.addPoint(652,235 + xScale); sing.addPoint(648,226 + xScale); sing.addPoint(652,218 + xScale); sing.addPoint(661,212 + xScale); g2.setColor(Color.black); g2.fill(sing); g2.draw(sing); //guitar Polygon guitar = new Polygon(); guitar.addPoint(148,28); guitar.addPoint(158,32); guitar.addPoint(164,38); guitar.addPoint(168,46); guitar.addPoint(169,52); guitar.addPoint(167,60); guitar.addPoint(164,65); guitar.addPoint(165,70); guitar.addPoint(161,76); guitar.addPoint(158,92); guitar.addPoint(162,97); guitar.addPoint(161,102); guitar.addPoint(158,106); guitar.addPoint(155,108); guitar.addPoint(151,127); guitar.addPoint(152,133); guitar.addPoint(155,137); guitar.addPoint(151,146); guitar.addPoint(153,147); guitar.addPoint(160,142); guitar.addPoint(162,133); guitar.addPoint(162,123); guitar.addPoint(161,113); guitar.addPoint(162,110); guitar.addPoint(164,117); guitar.addPoint(169,131); guitar.addPoint(171,144); guitar.addPoint(170,159); guitar.addPoint(166,167); guitar.addPoint(166,171); guitar.addPoint(174,174); guitar.addPoint(183,184); guitar.addPoint(191,195); guitar.addPoint(196,198); guitar.addPoint(198,200); guitar.addPoint(199,210); guitar.addPoint(211,225); guitar.addPoint(212,233); guitar.addPoint(220,248); guitar.addPoint(233,260); guitar.addPoint(245,266); guitar.addPoint(248,268); guitar.addPoint(249,277); guitar.addPoint(205,275); guitar.addPoint(204,262); guitar.addPoint(187,238); guitar.addPoint(178,224); guitar.addPoint(177,216); guitar.addPoint(156,201); guitar.addPoint(146,197); guitar.addPoint(134,211); guitar.addPoint(128,229); guitar.addPoint(125,244);// guitar.addPoint(121,246); guitar.addPoint(107,248); guitar.addPoint(100,252); guitar.addPoint(97,258); guitar.addPoint(96,253); guitar.addPoint(89,258); guitar.addPoint(65,267); guitar.addPoint(63,274); guitar.addPoint(64,283); guitar.addPoint(41,282); guitar.addPoint(44,270); guitar.addPoint(47,264); guitar.addPoint(51,255); guitar.addPoint(73,238); guitar.addPoint(79,228); guitar.addPoint(97,222); guitar.addPoint(101,204); guitar.addPoint(102,181); guitar.addPoint(100,170); guitar.addPoint(95,161); guitar.addPoint(97,154); guitar.addPoint(91,152); guitar.addPoint(77,131); guitar.addPoint(65,123); guitar.addPoint(61,105); guitar.addPoint(64,94); guitar.addPoint(72,91); guitar.addPoint(78,82); guitar.addPoint(78,76); guitar.addPoint(70,73); guitar.addPoint(70,67); guitar.addPoint(93,51); guitar.addPoint(101,48); guitar.addPoint(111,52); guitar.addPoint(118,59); guitar.addPoint(119,70); guitar.addPoint(117,78); guitar.addPoint(113,79); guitar.addPoint(112,86); guitar.addPoint(111,88); guitar.addPoint(109,89); guitar.addPoint(109,92); guitar.addPoint(122,99);// guitar.addPoint(124,99); guitar.addPoint(133,96); guitar.addPoint(145,93); //guitar.addPoint(138,124); guitar.addPoint(150,69); guitar.addPoint(150,62); guitar.addPoint(155,58); guitar.addPoint(154,53); guitar.addPoint(149,50); guitar.addPoint(154,46); guitar.addPoint(153,38); guitar.addPoint(147,28); g2.setColor(Color.black); g2.fill(guitar); g2.draw(guitar); Polygon guitar2 = new Polygon (); guitar2.addPoint(141,108); guitar2.addPoint(139,126); guitar2.addPoint(135,122); guitar2.addPoint(128,122); guitar2.addPoint(129,116); guitar2.addPoint(143,108); g2.setColor(Color.white); g2.fill(guitar2); g2.draw(guitar2); //bass guitar Polygon bassgt = new Polygon (); bassgt.addPoint(871,21); bassgt.addPoint(879,24); bassgt.addPoint(885,32); bassgt.addPoint(886,42); bassgt.addPoint(895,47); bassgt.addPoint(904,56); bassgt.addPoint(907,69); bassgt.addPoint(909,83); bassgt.addPoint(910,91); bassgt.addPoint(941,81); bassgt.addPoint(946,75); bassgt.addPoint(945,67); bassgt.addPoint(950,67); bassgt.addPoint(955,75); bassgt.addPoint(960,68); bassgt.addPoint(963,74); bassgt.addPoint(967,72); bassgt.addPoint(971,66); bassgt.addPoint(973,70); bassgt.addPoint(981,67); bassgt.addPoint(984,71); bassgt.addPoint(982,76); bassgt.addPoint(987,80); bassgt.addPoint(986,82); bassgt.addPoint(980,83); bassgt.addPoint(979,90); bassgt.addPoint(974,85); bassgt.addPoint(970,86); bassgt.addPoint(973,91); bassgt.addPoint(965,86); bassgt.addPoint(960,90); bassgt.addPoint(961,100); bassgt.addPoint(955,92); bassgt.addPoint(944,91); bassgt.addPoint(907,103); bassgt.addPoint(906,109); bassgt.addPoint(893,114); bassgt.addPoint(895,123); bassgt.addPoint(900,131); bassgt.addPoint(904,134); bassgt.addPoint(908,145); bassgt.addPoint(911,159); bassgt.addPoint(918,171); bassgt.addPoint(919,190); bassgt.addPoint(923,198); bassgt.addPoint(919,201); bassgt.addPoint(919,210); bassgt.addPoint(927,220); bassgt.addPoint(942,226); bassgt.addPoint(944,234); bassgt.addPoint(909,230); bassgt.addPoint(905,214); bassgt.addPoint(899,204); bassgt.addPoint(893,203); bassgt.addPoint(889,171); bassgt.addPoint(877,151); bassgt.addPoint(861,152); bassgt.addPoint(852,169); bassgt.addPoint(849,203); bassgt.addPoint(841,210); bassgt.addPoint(840,228); bassgt.addPoint(828,233); bassgt.addPoint(806,235); bassgt.addPoint(805,228); bassgt.addPoint(822,219); bassgt.addPoint(824,204); bassgt.addPoint(817,201); bassgt.addPoint(822,196); bassgt.addPoint(822,184); bassgt.addPoint(828,162); bassgt.addPoint(829,152); bassgt.addPoint(820,149); bassgt.addPoint(811,144); bassgt.addPoint(806,134); bassgt.addPoint(805,117); bassgt.addPoint(820,107); bassgt.addPoint(819,89); bassgt.addPoint(811,83); bassgt.addPoint(811,77); bassgt.addPoint(824,66); bassgt.addPoint(825,61); bassgt.addPoint(842,53); bassgt.addPoint(852,43); bassgt.addPoint(853,29); bassgt.addPoint(870,20); g2.setColor(Color.black); g2.fill(bassgt); g2.draw(bassgt); Polygon bassgt2 = new Polygon(); bassgt2.addPoint(845,78); bassgt2.addPoint(845,98); bassgt2.addPoint(843,98); bassgt2.addPoint(842,105); bassgt2.addPoint(839,109); bassgt2.addPoint(834,103); bassgt2.addPoint(832,85); bassgt2.addPoint(845,78); g2.setColor(Color.white); g2.fill(bassgt2); g2.draw(bassgt2); Polygon drums = new Polygon (); drums.addPoint(713,104); drums.addPoint(706,121); drums.addPoint(721,377); drums.addPoint(248,380); drums.addPoint(253,228); drums.addPoint(250,206); drums.addPoint(237,178); drums.addPoint(206,166); drums.addPoint(201,154); drums.addPoint(198,152); drums.addPoint(208,148); drums.addPoint(236,150); drums.addPoint(247,130); drums.addPoint(227,119); drums.addPoint(219,105); drums.addPoint(222,96); drums.addPoint(233,88); drums.addPoint(251,84); drums.addPoint(272,83); drums.addPoint(300,91); drums.addPoint(285,72); drums.addPoint(294,57); drums.addPoint(319,46); drums.addPoint(372,45); drums.addPoint(406,50); drums.addPoint(428,65); drums.addPoint(433,74); drums.addPoint(450,58); drums.addPoint(478,48); drums.addPoint(514,48); drums.addPoint(544,51); drums.addPoint(566,52); drums.addPoint(577,67); drums.addPoint(575,79); drums.addPoint(561,95); drums.addPoint(545,98); drums.addPoint(525,105); drums.addPoint(524,147); drums.addPoint(524,183); drums.addPoint(645,175); drums.addPoint(662,143); drums.addPoint(617,152); drums.addPoint(608,148); drums.addPoint(614,139); drums.addPoint(633,128); drums.addPoint(661,116); drums.addPoint(659,107); drums.addPoint(625,114); drums.addPoint(592,113); drums.addPoint(571,111); drums.addPoint(565,102); drums.addPoint(576,86); drums.addPoint(616,70); drums.addPoint(647,66); drums.addPoint(679,67); drums.addPoint(695,72); drums.addPoint(699,90); drums.addPoint(678,100); drums.addPoint(667,103); drums.addPoint(672,113); drums.addPoint(689,105); drums.addPoint(709,106); g2.setColor(Color.black); g2.fill(drums); g2.draw(drums); } } The second class: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import javax.swing.JComponent; import java.awt.GradientPaint; /* component that draws the concert background */ public class Concertbackground extends JComponent { public void paintComponent(Graphics g) { super.paintComponent(g); // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; //Background Top g2.setColor(Color.BLUE); Rectangle backgroundTop = new Rectangle (0, 0, getWidth(), getHeight() / 4); g2.fill(backgroundTop); // Background bottom g2.setColor(Color.GREEN); Rectangle backgroundBottom = new Rectangle (0, getHeight() / 2, getWidth(), getHeight() / 2); g2.fill(backgroundBottom); // Speaker base g2.setColor(Color.BLACK); Rectangle base = new Rectangle (0, 0, 50, 100); g2.fill(base); // Speakers circles gray top g2.setColor(Color.DARK_GRAY); Ellipse2D.Double speakerTop = new Ellipse2D.Double(10, 10, 30, 30); g2.fill(speakerTop); //speakers circles black top g2.setColor(Color.BLACK); Ellipse2D.Double speakerTop1 = new Ellipse2D.Double(15, 15, 20, 20); g2.fill(speakerTop1); // Speakers circles gray bottom g2.setColor(Color.DARK_GRAY); Ellipse2D.Double speakerBottom = new Ellipse2D.Double(10, 50, 30, 30); g2.fill(speakerBottom); //speakers circles black bottom g2.setColor(Color.BLACK); Ellipse2D.Double speakerBottom1 = new Ellipse2D.Double(15, 55, 20, 20); g2.fill(speakerBottom1); } } My main question is how do I change my Jframe so it can use as many classes as I want, It cant be the size of my classes because they were used with the same 1000, 800 Jframe to make the classes. I also need to be able to add more than just these two classes to my Jframe.

    Read the article

  • JPanel paint method is not being called, why?

    - by swift
    When i run this code the paintComponent method is not being called It may be very simple error but i dont know why this, plz. package test; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.JPanel; class Userboard extends JPanel { static BufferedImage image; String shape; Point start; Point end; Point mp; String selected; int ex,ey;//eraser int w,h; public Userboard() { setOpaque(false); System.out.println("paper"); setBackground(Color.white); setBorder(BorderFactory.createLineBorder(Color.black)); } public void paintComponent(Graphics g) { System.out.println("userboard-paint"); try { //g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected==("elipse")) { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } } catch(Exception e) {} } //Function to draw the shape on image public void draw() { System.out.println("Userboard-draw"); System.out.println(selected); System.out.println(start); System.out.println(end); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.black); if(start!=null && end!=null) { if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); else if(selected=="elipse") { System.out.println("userboard-elipse"); g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); System.out.println("userboard-elipse drawn"); } else if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); } start=null; repaint(); g2.dispose(); } //To add the point to the board which is broadcasted by the server public void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) this.selected="elipse"; else if(shape.equals("line")) this.selected="line"; else if(shape.equals("rect")) this.selected="rect"; else if(shape.equals("erase")) erase(); if(end!=null && start!=null) { if(varname.equals("end")) end=ps; else if(varname.equals("mp")) mp=ps; else if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } repaint(); } catch(Exception e) { e.printStackTrace(); } } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); if(start!=null) pic.fillRect(start.x, start.y, 10, 10); } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } //Function to add buttons into the panel, calling this function returns a panel }

    Read the article

  • how to double buffer in multiple classes with java

    - by kdavis8
    I am creating a Java 2D video game. I can load graphics just fine, but when it gets into double buffering I have issues. My source code package myPackage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GameView extends JFrame { private BufferedImage backbuffer; private Graphics2D g2d; public GameView() { setBounds(0, 0, 500, 500); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backbuffer = new BufferedImage(getHeight(), getWidth(), BufferedImage.TYPE_INT_BGR); g2d = backbuffer.createGraphics(); Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.getImage(this.getClass().getResource("cage.png")); g2d.setColor(Color.red); //g2d.drawString("Hello",100,100); g2d.drawImage(img, 100, 100, this); repaint(); } public static void main(String args[]) { new GameView(); } public void paint(Graphics g) { g2d = (Graphics2D)g; g2d.drawImage(backbuffer, 0, 0, this); } }

    Read the article

  • Thread safe double buffering

    - by kdavis8
    I am trying to implement a draw map method that will draw the tiled image across the surface of the component. I'm having issue with this code. The double buffering does not seem to be working, because the sprite flickers like crazy; my source code: package myPackage; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GameView extends JFrame implements Runnable { public BufferedImage backbuffer; public Graphics2D g2d; public Image img; Thread gameloop; Scene scene; public GameView() { super("Game View"); setSize(600, 600); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backbuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); g2d = backbuffer.createGraphics(); Toolkit tk = Toolkit.getDefaultToolkit(); img = tk.getImage(this.getClass().getResource("cage.png")); scene = new Scene(g2d, this); gameloop = new Thread(this); gameloop.start(); } public static void main(String args[]) { new GameView(); } public void paint(Graphics g) { g.drawImage(backbuffer, 0, 0, this); repaint(); } @Override public void run() { // TODO Auto-generated method stub Thread t = Thread.currentThread(); while (t == gameloop) { scene.getScene("dirtmap"); g2d.drawImage(img, 80, 80,this![enter image description here][1]); } } private void drawScene(String string) { // TODO Auto-generated method stub // g2d.setColor(Color.white); // g2d.fillRect(0, 0, getWidth(), getHeight()); scene.getScene(string); } } package myPackage; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; public class Scene { Graphics g2d; Component c; boolean loaded = false; public Scene(Graphics2D gr, Component co) { g2d = gr; c = co; } public void getScene(String mapName) { Toolkit tk = Toolkit.getDefaultToolkit(); Image tile = tk.getImage(this.getClass().getResource("dirt.png")); // g2d.setColor(Color.red); for (int y = 0; y <= 18; y++) { for (int x = 0; x <= 18; x += 1) { g2d.drawImage(tile, x * 32, y * 32, c); } } loaded = true; } }

    Read the article

1 2 3 4 5  | Next Page >