Using getGraphics()

Hi fellas,
i m a newbie in gui developing
when i draw using component.getGraphics().drawXYZ()
the drawing gets lost when the component is repainted
using setIgnoreRepaint doesnt work.
can someone tell be how to correct this problem.
ie using getGraphics and not losing your drawing..
thanks in advance
z_idane

For rendering that persists put the rendering code inside an appropriate paint method, eg,
    // Swing component
    protected void paintComponent(Graphics g)
    // AWT component or
    // advanced use in top-level containers or Swing
    public void paint(Graphics g).
This way the paint method will be called for/during each repaint. Using 'getGraphics' is generally not recommended for custom rendering work (graphics and images).

Similar Messages

  • How do you make an Image from a Graphics?

    1) Is it possible to make an Image from a graphics?
    I've returned the Graphics of an image in the method of one class so that I can work with it in another class. I was looking for a setGraphics in the Image class but there isn't one. Nor is there a graphics.createImage(). What I'd really like to do is get the background image, draw on it in a separate class, then return it to the original class (for buffering purposes).
    2) is there any way to make a blank Image of given dimensions (without actually making a .gif of a blank screen)? I want to draw on the background even if it is blank, but I can't get the Graphics of a null Image.
    thanks in advance.. :-) jen

    thanks for all your help guys!
    i looked at those websites.
    The reason why the site's buffered images work is becuase they are using the paint method in a single class. (i.e. they are not calling the graphics from someplace else). If you call a Graphics (using getGraphics and the like) from someplace else, you don't get a reference or pointer; you get a COPY. The copy will helpfully record your instructions. But the original graphics doesn't get the instructions. That's my problem. My graphics instructions are not getting sent to the originating Graphics, so drawRect never gets executed.
    Another problem is that I often have no background picture in my container, and hence, I have a null pointer when I try to draw stuff on the returned Graphics.
    So what I want to do is create an image in the subclass of the rectangles, lines, whatever, and send it to my handy little setBackground(Image im) method in my superclass. And whenever the background image is null, create a white image to draw on.
    I am calling the graphics from the background of a custom lightweight container. I would REALLY REALLY not like to mess with my container code... it took me a long time to get it working.
    I also don't want to override paint. That would make all the buffering work I did obsolete. :-(

  • Multiple Components in a JFrame (simple question)

    Hello everyone, I need to put two components in my JFrame, and I have been expieriencing some odd problems. I use this to add my components...
    MyComponent mc=new MyComponent();
    MyOtherComponent me = new MyOtherComponent();
    When I try to access methods they work fine. I can use repaint() in a method and it works. BUT when I try to draw on the component using anything besides paintComponent() It gives me a java.lang.NullPointerException
    here is what I tried.....
    me.draw(getGraphics());
    //later on in the component def..
    draw(Graphics g) {
    } // I get a java.lang.NullPointerException in main
    whenever i use getGraphics() it does'nt work what am I doing wrong?

    Yup I did that and repaint does jack all. When I run the code all I see the contents of the first component. I know that the methods of the second component are being executed, but the paintComponent method is simply not running. I put a System.out.println("hi"); in and it never showed in the console..
    Anyone who can help me gets a duke, here's my second component code..
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    class MyOtherComponent extends JComponent {
    public void paintComponent(Graphics gg) {
    System.out.println("paintComponent executed!!!");
    Graphics2D g2D = (Graphics2D)gg;
    ImageIcon icon = null;
    try {icon = new ImageIcon(new URL("http://images.neopets.com/m.gif")); }
    catch(MalformedURLException e) {
    System.out.println("no"); return;
    resize(icon.getIconWidth(),icon.getIconHeight());
    Image mark = icon.getImage();
    g2D.drawImage(mark,0,0,this);
    g2D.drawString("hello folk",40,40);
    drawe(g2D);
    public void drawe(Graphics2D g2D) {
    g2D.drawLine(50,50,500,500);
    g2D.fillRect(20,20,20,20);
    repaint();
    public void line() {
    System.out.println("Hello, from MyOtherComponent");
    public void re() {
    repaint();
    System.out.println("re");     
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • How do you locate a bug WITHOUT the emulator and the console?

    Hi.
    I'm new here and my English is not perfect but I'll try my best to explain my problem.
    I'm trying to port J2ME games to various mobile phone devices. I've no problem fixing bugs on Nokia, Sony Ericsson, or any models that offer an emulator and a console window.
    *** The problem is: In some case, The same build runs fine on Nokia/Sony emulator, but crash/freeze on LG phones.
    (this is just an example, it's not only LG phones that have this problem though)
    I believe it is possible to locate the bug by:
    - use the 'try/catch' block and print the error message using something like
    g.drawString(e.toString(),0,0,0);
    where 'g' and 'e' is a Graphics and Exception objects.
    But I wonder if there's a way to print 'everything that should be printed on the console', on the phones's display. So we don't need to manually put try/catch block.
    ok, to sum up the question.
    Question:
    1. Is there a way to print 'everything that will normally appear on the console', on the phones's screen?
    2. If no, then I'll need to try/catch the problem.
    But how can you use try/catch and "drawString" everywhere in the code?, while the actual drawing will be done only in the "paint()" method?
    I'm thinking of using 'getGraphics().drawString' when using try/catch outside the paint() method. but what's the point if the actual drawing will be done only in paint() method anyway...
    Sorry if it's a stupid question. I just started learning Java programming 3 months ago, let alone J2ME. >_<
    Thank you. =)
    /bow

    Hi Kakyoin,
    What I found was helpfull is creating a method in the MIDlet where you can display messages. For instance:
        public void createFormScreen(Alert alert) {
            // Set up the initial screen for the MIDlet
            Form formScreen = new Form("Your MIDlet name");
            firstScreen.append("Welcome to your MIDlet");
            myChoice = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
            myChoice.append("Your first choice", null);
            myChoice.append("Your second choice", null);
            formScreen .append(myChoice);
            formScreen .addCommand(OKCOMMAND);
            formScreen .addCommand(EXITCOMMAND);
            formScreen .setCommandListener(this);
            theListener = this;
            if (alert == null) {
                 theDisplay.setCurrent(formScreen Screen);
            } else {
                theDisplay.setCurrent(alert, formScreen);
        }So, from your constructor call the createFormScreen method, and your initial screen will be displayed.
    When an allert situation occurs in an object, call createFormScreen in a method like:
         protected void displayMessage(String title, String msg) {
              // Display the error message
              Alert error = new Alert(title, msg, null,
                        AlertType.ERROR);
              error.setTimeout(Alert.FOREVER);
              myMIDlet.createStartScreen(error);
         }Now the error message will be displayed on the screen indefenitaly. Off course your object where the error occurred should have a reference to the MIDlet object. I hope this helps you.
    Maik

  • How do I make a backbuffer in a canvas?

    Hi
    I am making a game, were I need to have several classes that extends canvas, so I can have one class drawing things, when traveling through space.
    one when I travel indoors, or in a city, with raycasting
    one when I travel outdoors, generating the terrain.
    one I already have showing the character I am talking with, besides a textarea, to show the dialog.
    one to show prerendered computer art backgrounds+transparent .gifs of characters on the same place.
    here is the code:
    landscape(){// create bump map
    super();
    gs=getGraphics();
    screen=createImage(640,480);
    //gx=screen.getGraphics();
    I cant use the last line, it generates a java.lang.nullpointerexception
    when I run it in appletviewer
    I also tried to call a method within the landscape class from run, using gs.drawLine etc, to draw directly in a thread, so I wont need to use paint.
    drawing everything in paint, is way too slow.
    any suggestions?
    here is the first test I made, uploaded it, so I could test how long it took to load so many images.
    but here I instead use add and remove different panels, and use a very messy paint, with lots of if statements.
    http://www.fortunecity.com/rivendell/henchman/1142/testchoice.html
    I am allowed to use some of Hamfast computer art.
    some of the pictures are only temporary.
    click on the woman, to talk to her.
    soo how shall I do, so I can create a backbuffer in the canvas's so I get rid of all the flicker I have now I my terraingenerating 3d engine.
    also looked at some extremely fast raycasting code.
    it doesnt use paint at all, it uses getGraphics(); to get the graphics context, draws everything in a thread, in an array, then it makes a image of it, and draws the image, directly in the thread, making a very fast frame rate.

    thanks
    I did this and it worked,
    I made a thread inside the canvas.
    and copied and pasted everything from paint to that thread.(and made that code inside the paint a comment)
    I use gs=getGraphics(); to output the backbuffer after I have drawed all terrain.
    it takes 50 milliseconds to do a frame. with 640*480 window.
    now I am wondering:will this gs(draw to screen)and gx(draw to backbuffer) be only local in run, or will they work in all methods I call from run?

  • Disappearing lines in a JPanel

    I have some buttons in a panel and the panel is placed in another panel which contains some lines and these two panels are added to a scrollpane. The problem is that, if I scroll the frame or place another window on the frame the lines disappear. I have not used getGraphics() method. All the painting has been done in the paintComponent().What might be the reason.

    What might be the reason. You are doing something wrong.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • How to transfer a figure drawn on a canvas via bluetooth?

    Hi,
    I am developing an application that will draw multiple figures like rectangle, circle,square on a canvas.I want to send this via bluetooth to other device.In which format should i send this?How?
    Thanks
    Aiswarya

    You will need capture the screen. Steps are
    1) Create Image of the size of your canvas.
    2) Get graphics object for this image using getGraphics() method of Image.
    3) Whenever you draw on the canvas, also draw on this image using the graphics object you obtained from Image.
    4) Use getRGB() method of the image to grab the pixels.
    Use JSR 82 to transfer this data over bluetooth.
    Atul

  • How can I set line wrap on a JButton??

    Hi...
    I am working on an application that required to have a long label on a button and I was wondering if anyone know how to set line wrap on a JButton. Any suggestion will be greatly appreciate.

    If it is not inconvenient for you to use mouse events instead of action events this procedure may be adequate.
    Invoke "createImage" on the JButton to obtain an "Image" object then use "getGraphics" on the image object to get "Graphics" object. Next call "getFontMetrics" on the "Graphics" object to obtain "FontMetrics". Now you can get the size of a String drawn from the "drawString" method of the "Graphics" object. This can be obtained in an int returned from "getHeight" method in "FontMetrics".
    You can obtain the center of the "Image" by using "getSize" method from JButton and dividing it by 2.
    You can get the width of characters by using "FontMetrics" "charsWidth" method. Now you can use the int returned from charsWidth and getHeight to align text in the JButton "Image" by using the "Dimension"
    object returned by the "getSize" method. Now invoke
    the "drawString" method for as many lines of text as you would like to display. After finished drawing strings you
    construct an ImageIcon with its one parameter being the "Image" object you have created and drawn on.
    Now you invoke the "setIcon" method of JButton to insert the ImageIcon as the image displayed on the JButton.
    At this point you have a JButton with all the text you want displayed on it, but with no event handling. So
    you are going to add a MouseListener to the JButton.
    In the MouseListener override the "mouseClicked" method
    inside the method obtain the MouseEvent's location through "getX" and "getY". Next invoke the JButton's
    "getLocation" method to obtain a "Point" object. Now invoke the "Point" objects "getX" and "getY" methods to return the int locations of the origin of the JButton.
    Now invoke the "getSize" method of the JButton to get
    a "Dimension" object containing the size of the JButton.
    Now you can use boolean operations to determine if the
    x, y coordinate that was obtained by the MouseEvent falls within the boundries of the JButton component.
    Something like this:
    public void mouseClicked(MouseEvent mouseEvent) {
    Point point=jbutton.getLocation();
    Dimension dimension=jbutton.getSize();
    int pX=point.getX();
    int pY=point.getY();
    int dW=dimension.width;
    int dH=dimension.height;
    int mX=mouseEvent.getX();
    int mY=mouseEvent.getY();
    if(mX>pX & mX<(pX+dW)) {
    if(mY>pY & mY<(pY+dH)) {
    //This means that the point does indeed fall within
    //the boundries of the JButton, so place the code
    //that would normally appear in actionPerformed
    //within this code block
    Good Luck.

  • Displaying images on a JPanel from another thread

    Hello all,
    I'm trying to write my first multithreaded program. I have a program with 2 threads. The first (ie main) thread sets up a gui and performs some calculations, and the second thread changes the background of the gui at intervals. I been having a couple of problems with loading images in the second thread.
    In my main thread, I initialise and make runnable the second thread, which is the thread that changes the gui background:
    ThreadChangeBackground myThread = new ThreadChangeBackground(graphicPanel);
    new Thread(myThread).start(); I have tested the threads and they are working fine.
    The problem is when I try to load images and show them. I've never worked with images before, so I don't know what the best way of loading them onto a GUI is.
    This is the code for the second thread:
    package Graphics;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Container.*;
    import java.awt.Toolkit.*;
    public class ThreadChangeBackground implements Runnable
        JPanel changeable; //changeable = graphicPanel
        Image bgImage1;
        Image bgImage2;
        Image bgImage3;
        Image bgImage4;
        Image bgImage5;
        Image bgImage6;
        Image bgImage7;
        Image bgImage8;
        Image bgImage9;
        Image bgImage10;
        public ThreadChangeBackground(JPanel changeable)
            this.changeable = changeable;
        public void run()
            try
                bgImage1 = Toolkit.getDefaultToolkit().getImage("1");
                bgImage2 = Toolkit.getDefaultToolkit().getImage("2");
                bgImage3 = Toolkit.getDefaultToolkit().getImage("3");
                bgImage4 = Toolkit.getDefaultToolkit().getImage("4");
                bgImage5 = Toolkit.getDefaultToolkit().getImage("5");
                bgImage6 = Toolkit.getDefaultToolkit().getImage("6");
                bgImage7 = Toolkit.getDefaultToolkit().getImage("7");
                bgImage8 = Toolkit.getDefaultToolkit().getImage("8");
                bgImage9 = Toolkit.getDefaultToolkit().getImage("9");
                bgImage10 = Toolkit.getDefaultToolkit().getImage("10");
                //run this thread process 200 times
                for (int i = 1; i <= 200; i++)
                    //load a new image every 3 seconds
                    for (int imageCount = 1; imageCount <= 10; imageCount++)
                        loadImage(imageCount);
                        Thread.sleep(3000);
            catch (Exception e) {}
    //the problem is here 
        private void loadImage(int imageNo)
            Graphics g = changeable.getGraphics();
            g.drawImage("bgImage" + imageNo, 400, 500, null);
    }The API suggests using getGraphics() to get the graphics context of a component. This allows you to invoke operations on the returned graphics object to draw on the component. When I try to call drawImage() i get the following error message:
    Graphics/ThreadChangeBackground.java [57:1] cannot resolve symbol
    symbol  : method drawImage (java.lang.String,int,int,<nulltype>)
    location: class java.awt.Graphics
            changeable.getGraphics().drawImage("bgImage"+ imageNo, 400, 500, null);
                                  ^
    1 error
    Errors compiling ThreadChangeBackground.If I change the code and try to do this:         g.drawImage("bgImage" + imageNo, 400, 500, null); everything complies but the background of my gui does not change. Adding changeable.repaint() to the loadImage() method does not change the gui background.
    I've got this far by reading the API (it's so big!), java textbooks and the java tutorial, but I really don't know what to do next.
    Any help would really be appreciated!

    These are all the drawImage methods in Graphics class:
    abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
    Draws as much of the specified image as is currently available.
    abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
    Draws as much of the specified image as is currently available.
    abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
    Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
    abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
    Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
    abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
    Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
    abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
    Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
    Notice that NONE of them takes String as the first argument.
    Your error:
    Cannot resolve symbol method drawImage (java.lang.String,int,int,<nulltype>)
    suggests that java is looking for drawImage method that takes String as its first argument - IT'S NOT IN THE GRAPHICS CLASS - that's the problem
    M
    suggests

  • Drawing a special cursor: completely repaint everytime or only a region?

    Hello, I'm currently building an application which displays a BufferedImage. When I move the cursor in the the component that displays the BufferedImage my app draws a special cursor. It's a square which is moved only if my current position is dividable by 16 (if there was a grid, it would change it's position when the mouse moves to another square in the grid, it is around the square that the mouse occupies). At first, I was only using on thread so the application was a little laggy and my cursor thing didn't work too well. So I decided to use another thread to take care of my cursor. The drawing is in another class (external to the drawing class), therefore, I use getGraphics (since my drawing class subclasses JComponent). I signal a draw by changing a variable. I have to erase my old cursor to draw the new one. The problem is that my component "'flashes" gray instead of staying the way it should be (which is black, for now). Here are my questions: Why does it flash gray ? and what should I do to change that?
    Here's my code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    class Cursor implements Runnable {
         public boolean draw;
         public int[] iCursorCoord;
         public JComponent drawSurface;
         private Thread t;
         private Rectangle cursor;
         Cursor(){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(int[] initCoord){
              cursor = new Rectangle(initCoord[0],initCoord[1],15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = null;
         Cursor(Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = null;
         Cursor(JComponent drawSurf){
              cursor = new Rectangle(0,0,15,15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = 0;
              iCursorCoord[1] = 0;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, Rectangle rect){
              cursor = rect;
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = rect.x;
              iCursorCoord[1] = rect.y;
              draw = false;
              drawSurface = drawSurf;
         Cursor(JComponent drawSurf, int[] initCoord){
              cursor = new Rectangle(initCoord[0], initCoord[1], 15, 15);
              t = new Thread(this);
              iCursorCoord = new int[2];
              iCursorCoord[0] = initCoord[0];
              iCursorCoord[1] = initCoord[1];
              draw = false;
              drawSurface = drawSurf;
         public void init(){
              t.start();
         public void run(){
              while(true){
                   if(!draw) continue;
                   draw = false;
                   cursor.x = iCursorCoord[0];
                   cursor.y = iCursorCoord[1];
                   System.out.println("Inside Cursor::run()");
                   Graphics2D gfx = (Graphics2D) drawSurface.getGraphics();
                   this.completePaint(gfx);
                   Color current = gfx.getColor();
                   gfx.setColor(new Color(84,255,3));
                   gfx.draw(cursor);
                   gfx.setColor(current);
         private void completePaint(Graphics2D gfx){
              int layer = MapMaker.getLayerMode();
              if(layer != 4){
                   BufferedImage bi = MapMaker.getCurrentMap().getData(MapMaker.getLayerMode());
                   gfx.setPaint(new TexturePaint(bi, new Rectangle(0,0,MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16)));
                   gfx.fillRect(0, 0, MapMaker.getCurrentMap().getWidth()*16, MapMaker.getCurrentMap().getHeight()*16);
                   //gfx.drawImage(bi, null, 0,0);     
              } else {//Will be implemented later, render will be modified
                   System.out.println("Will be implemented later");
    }P.S.: This is only part of my code. There are other classes that I do not post because I believe it is not necessary. I will post the full code if needed.

    You need to override the paint(Graphics g) method. E.g.:
    public class MyPanel extends JPanel {
         public void paint(Graphics g) {
                   super.paint(g);
                    // ... do draw code here
    }The reason your app is flashing is because your code only executes
    when the thread is requests it to. Inbetween the time your code is
    executing, other threads are calling the paint(Graphics g) method.
    Gray is the default color used in painting.
    You can use a thread to call the repaint() method, but no drawing
    should be done in the thread.

  • Problem in the game bomberman with  the position of the icon bomb

    hi
    in this code the player move with arrows in any where and when u press the space button bomb appear
    but the bomb not appear in the position where the player stay and the player go to anthor place
    please test my code to understande my problem
    import javax.swing.JFrame;
    public class Mainprogram extends JFrame {
        private MainBord mainbord;
        public Mainprogram() {
            mainbord = new MainBord();
            addKeyListener(mainbord);
            getContentPane().add(mainbord);
        public static void main(String[] args) {
            JFrame frame = new Mainprogram();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 900);
            //frame.setResizable(false);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class MainBord extends JPanel implements KeyListener {
        private BufferedImage bord;
        private JLabel bomabr_label;
        private JPanel bombar_panel;
        private ImageIcon divider_icon,bombar_icon,bomb_icon;
        private Graphics g;
        private int x;
        private int y;
        private int dividerSize = 40;
        public MainBord() {
            drawimage();
            drawComponents();
        private void drawComponents() {
            divider_icon = new ImageIcon(getClass().getResource("wall.gif"));
            bombar_icon = new ImageIcon(getClass().getResource("bombar.gif"));
            bomb_icon=new ImageIcon(getClass().getResource("bomb.gif"));
            x = (bord.getWidth() - (divider_icon.getIconWidth() + dividerSize) * 8) / 2;
            y = (bord.getHeight() - (divider_icon.getIconHeight() + dividerSize) * 8) / 2;
            for (int i = 0; i < 8; ++i) {
                for (int j = 0; j < 8; ++j) {
                    divider_icon.paintIcon(this, g, (divider_icon.getIconWidth() + dividerSize) * i + x, (divider_icon.getIconHeight() + dividerSize) * j + y);
            bombar_panel = new JPanel();
            bomabr_label = new JLabel(bombar_icon);
            bombar_panel.add(bomabr_label);
        private void drawimage() {
            bord = new BufferedImage(800, 900, BufferedImage.TYPE_INT_RGB);
            g = bord.getGraphics();
            g.setColor(Color.ORANGE);
            g.fillRect(0, 0, 1000, 1000);
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(bord, 0, 0, this);
            bombar_icon.paintIcon(this, g, x - bombar_icon.getIconWidth(), y - bombar_icon.getIconHeight());
        public void keyTyped(KeyEvent e) {
        @Override
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_RIGHT:
                    x += 5;
                    break;
                case KeyEvent.VK_LEFT:
                    x -= 5;
                    break;
                case KeyEvent.VK_UP:
                    y -= 5;
                    break;
                case KeyEvent.VK_DOWN:
                    y += 5;
                    break;
                case KeyEvent.VK_SPACE:
                    x=bombar_icon.getIconWidth();
                    y=bombar_icon.getIconHeight();
                    bomb_icon.paintIcon(this, g, x+dividerSize, y+dividerSize);
                    break;
            repaint();
        public void keyReleased(KeyEvent e) {
    }the problem in the last case in the switch
    please refactor it to ucerstande how you do this .
    the picture use in my code here:
    http://www.4shared.com/file/75272822/8ecd434d/pictures.html
    thanks
    beshoy

    you're doing it all wrong
    1) don't use getGraphics()
    2) don't override paint() for swing components - override paintComponent()
    3) do all your graphics in paintComponent - not in the listener
    your problem is that the bomb should appear over the 'player' when spacebar pressed?
    if so, I've stripped your code down to just that problem.
    if this works the way you want it to, then simply modify your main program accordingly
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class MainBord extends JPanel {
        private ImageIcon bombar_icon,bomb_icon;
        private int x = 100;
        private int y = 100;
        boolean paintBomb = false;
        public MainBord() {
            setFocusable(true);
            bombar_icon = new ImageIcon(getClass().getResource("player.gif"));
            bomb_icon=new ImageIcon(getClass().getResource("bomb.gif"));
            addKeyListener(new KeyAdapter(){
              public void keyPressed(KeyEvent e) {
                switch (e.getKeyCode()) {
                    case KeyEvent.VK_RIGHT:
                        x += 5;
                        break;
                    case KeyEvent.VK_LEFT:
                        x -= 5;
                        break;
                    case KeyEvent.VK_UP:
                        y -= 5;
                        break;
                    case KeyEvent.VK_DOWN:
                        y += 5;
                        break;
                    case KeyEvent.VK_SPACE:
                        paintBomb = true;
                        break;
                repaint();
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.ORANGE);
            g.fillRect(0, 0, getWidth(), getHeight());
            bombar_icon.paintIcon(this, g, x, y);
            if(paintBomb) bomb_icon.paintIcon(this, g, x, y);
            paintBomb = false;
    class Mainprogram{
        public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable(){
            public void run(){
              JFrame frame = new JFrame();
              frame.getContentPane().add(new MainBord());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(800, 600);
              //frame.setResizable(false);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

  • Drawing a rectanlge and moving it around

    Hi,
    I have a JTable in which I do drag and drop. To visually support this, I draw a marker in the JTable, when the cursor is over a valid drop position, to indicate where the object will be inserted. I do this by drawing a rectangle between two tables.
            Rectangle rect= tt1.getCellRect(row, col, true);
            Rectangle2D marker= new Rectangle2D.Double(rect.getX()-1, rect.getY(), 2, rect.getHeight());
            if (marker.equals(lastMarker)){
                return lastMarker;
            }else{
                //Line2D line= new Line2D.Double( rect.getX()-1, rect.getY()+rect.getHeight());
                tt1.repaint();
                Graphics2D g2= (Graphics2D) tt1.getGraphics();           
                g2.fill(marker);
                return marker;
            }(the lastMarker is used to avoid redrawing it, if would be on the same position.)
    Now my problem is the tt1.repaint(). (tt1 is the JTable)
    This repaint always deletes my rectangle. I think, this is because the actual redraw is done after the marker is drawn. Therefore the rectangle is shown for some milliseconds and then disappears. But how can I avoid this? Any ideas?

    Don't use getGraphics for this. Trying to draw from event code doesn't work because system
    repaint events work independently of your event code, ie, system repaints call the paint
    methods of the components in the component hierarchy which have no idea that you are
    drawing markers from event code. Override the paint method (which will draw on top of the
    component) in your JTable to draw your drop marker. This way it will always be called
    during both event-initiated and system repaints.

  • Drawing on a visual object

    Hi everyone,
    Is it possible to draw on visual objects in java 3d.
    e.g. Could the user draw a shape on a sphere?
    thanks

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

  • Putting Rectangle On top of Frame With Multiple Panels

    Ok, I can't Figure out how place a Black Rectangle that Covers The whole Frame, while the frame contains 3 panels (for example).
    Here is what I tried to do.
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    * @author Sammy
    public class TestEngine {
    private JPanel pnl;
      private Graphics g;
        private JPanel pnl1;
        private JPanel pnl2;
       public static void main(String[] args) {
       TestEngine test =  new TestEngine();
                test.gui();
       public void gui (){
           JFrame frame = new JFrame("Aurora Engine -- 1.0 Test  ");
           frame.setSize(400, 400);
           frame.setVisible(true);
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setLocationRelativeTo(null);
           pnl = new JPanel();
           pnl1 = new JPanel();
           pnl2 = new JPanel();
        frame.add(pnl);
        frame.add(pnl);
        frame.add(pnl2);
        g = frame.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
                g2.drawRect(0, 0, pnl.getWidth(), pnl.getHeight());
                g2.setColor(Color.BLACK);
                g2.fillRect(1, 1, pnl.getWidth(), pnl.getHeight());
            frame.paint(g2);
    }

    1. Don't do any custom painting in a top level window. Use a JComponent or JPanel.
    2. Never never never use getGraphics in custom painting. Use an override to a painting method.
    how place a Black Rectangle that Covers The whole Frame, while the frame contains 3 panels (for example).Place the 3 panels in a parent panel with a paint() override that invokes the super implementation and then draws the rectangle. For example:import java.awt.*;
    import javax.swing.*;
    public class OvalOverlay {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new OvalOverlay().makeUI();
      public void makeUI() {
        JPanel outer = new JPanel(new GridLayout(2, 2)) {
          @Override
          public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.RED);
            g.fillOval(50, 50, getWidth() - 100, getHeight() - 100);
        Color[] backgrounds = {Color.YELLOW, Color.GREEN, Color.CYAN, Color.ORANGE};
        for (Color background : backgrounds) {
          JPanel inner = new JPanel();
          inner.setBackground(background);
          outer.add(inner);
        JFrame frame = new JFrame();
        frame.add(outer);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }db

  • Drawing a Graphics object on a Graphics object

    Is there anyway to draw a Graphics object on another Graphics object? I'm trying to show 2 screens, side by side, on a Canvas and I'm trying to cheat a little :-P Basically, I want to take half of one screen and half of another and put them on top of each other to form one screen.
    OR is there a way to turn a Graphics object into an Image object?

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

Maybe you are looking for

  • How can we assign Items from One Organization to a different Organization.

    Team, 1. We have a requirement to load all the items from Organization A to Organization B. Both are in different Operating Unit. Is there any API available to do this? Thanks -Karthik

  • Possible to run iMovie 6 HD and iMovie 5?

    Is there a way to have both versions of iMovie on my mac? I've tried installing the older version of iMovie from the 2 OS disks that came with the computer that also contain bundled software, and when I try to do a custom installation and choose only

  • Crash during sync, now all my apps are gone.

    My laptop and iphone crashed during a sync. Laptop would lock up as soon as the phone was plugged in, and the phone started random reboots and freezes. I reinstalled WinXP and itunes on the laptop, but still could not sync. The phone would come up "s

  • Photo collages in Elements 11

    In my previous version of Photoshop (I think 6) I was able to easily create a completely custom photo collage. I've been frustrated in my attempts to do the same in Elements 11. No. 1, how can I get a plain white background? Am I really stuck with th

  • Basic 1000v for Hyper-V questions

    Hi All, I have a Hyper-V 2012 R2 server (free version of Hyper-V) and I am in the process of deploying the Cisco 1000v virtual switch. I have a few questions, however: 1) My server has a single NIC with 4 uplinks. At the Hyper-V parent OS level, ther