Problem in drawImage

Hi,
We are developing a project where in I need to Place different images in different rectangle . For this i have used JPanel and overrided the paint method. This images are made possible to move when the mouse is beeing dragged. At this stage i am facing problems. I can move the image but the movement of the image is not very smooth. I mean to say there is filckering and Image movement is not synchronised with the movement of the mouse. How can i solve this problem.
If i need to place the code please do let me know.
If any one have solved this problem please do suggest me the workaround for the problem.
Thanks in Advance.
regards
Ravi

Here is the modified code :
I added the background image.
To create a RectangularImage you have to specify the filename of the image, the location point of the initial top left corner location and the dimension of the rectangle.
There is a black line around the rectangle and it is filled with a "dynamic color".
If the image is smaller than the rectangle, it is centered in.
If the image is bigger than the rectangle, it rescaled to fit in.
Each time you click on an image the background color changes randomly.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
public class ImageDragging extends JComponent {
     Vector images;
     Image backgroundImage;
     RectangularImage selectedImage;
     final static Color[] colors = new Color[] {Color.blue, Color.red, Color.green, Color.yellow, Color.pink, Color.white, Color.orange };
     final static Random random = new Random(System.currentTimeMillis());
     public ImageDragging() {
          images = new Vector();
          backgroundImage = (new ImageIcon("backgroundImage.jpg")).getImage();
          images.add(new RectangularImage("im1.gif", new Point(10,10), new Dimension(150,150)));
          images.add(new RectangularImage("im1.gif", new Point(20,20), new Dimension(70,70)));
          images.add(new RectangularImage("im1.gif", new Point(30,30), new Dimension(20,20)));
          MyMouseAdapter mouseAdapter = new MyMouseAdapter();
          addMouseListener(mouseAdapter);
          addMouseMotionListener(mouseAdapter);
          setPreferredSize(new Dimension(400,400));
     final static Color getRandomColor() {
          return(colors[random.nextInt(colors.length)]);
     final class MyMouseAdapter extends MouseInputAdapter {
          public void mousePressed(MouseEvent e) {
               selectedImage = getImageAt(e.getPoint());
               if (selectedImage == null) {
                    return;
               else {
                    selectedImage.setMouseLocation(e.getPoint());
                    selectedImage.setColor(getRandomColor()); // change the background color randomly each time we click on the image
                    repaint(selectedImage.getRepaintBounds());
          public void mouseDragged(MouseEvent e) {
               if (selectedImage != null) {
                    repaint(selectedImage.getRepaintBounds());
                    selectedImage.moveTo(e.getPoint());
                    repaint(selectedImage.getRepaintBounds());
          public void mouseReleased(MouseEvent e) {
               if (selectedImage != null) {
                    selectedImage.moveTo(e.getPoint());
                    repaint(selectedImage.getRepaintBounds());
                    selectedImage = null;
     public final void paintComponent(Graphics g) {
          Graphics2D g2D = (Graphics2D)g;
          g2D.drawImage(backgroundImage, 0, 0, this);
          /* if you want to fill all the background and your background image is smaller than it,
          use this instead :
          g2D.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(),this);*/
          RectangularImage im;
          for (Enumeration e = images.elements(); e.hasMoreElements();) {     
               im = (RectangularImage)e.nextElement();
               im.draw(g2D, this);
     public final RectangularImage getImageAt(Point p) {
          RectangularImage im;
          for (ListIterator e = images.listIterator(images.size()); e.hasPrevious();) {     
               im = (RectangularImage)e.previous();
               if (im.contains(p)) {
                    return(im);     
          return(null);
     final class RectangularImage extends Rectangle {
          Image image;     
          Point selectedPoint;
          Color dynamicColor;
          Rectangle repaintBounds;
          int imageX;
          int imageY;
          int imageWidth;
          int imageHeight;
          public RectangularImage(String filename, Point location, Dimension dimension) {
               ImageIcon ic = new ImageIcon(filename);
               image = ic.getImage();
               setBounds((int)location.getX(), (int)location.getY(), (int)dimension.getWidth(), (int)dimension.getHeight());
               repaintBounds = new Rectangle(0,0,(int)getWidth()+1, (int)getHeight()+1);
               /* These following values are used to center the image in the rectangle if the image is smaller than it
               and to rescale the image if it is bigger. */
               imageWidth = (int)ic.getIconWidth();
               imageWidth = imageWidth>width-2?width-2:imageWidth;
               imageHeight = (int)ic.getIconHeight();
               imageHeight = imageHeight>height-2?height-2:imageHeight;
               imageX = imageWidth==width-2?1:(int)((width-2-imageWidth)/2);
               imageY = imageHeight==height-2?1:(int)((height-2-imageHeight)/2);
               selectedPoint = new Point(0,0);
               dynamicColor = Color.blue;
          public void setMouseLocation(Point p) {
               selectedPoint.setLocation((int)(p.getX()-getX()), (int)(p.getY()-getY()));
          public void moveTo(Point p) {
               setLocation((int)(p.getX()-selectedPoint.getX()), (int)(p.getY()-selectedPoint.getY()));
          public void setColor(Color c) {
               dynamicColor = c;
          public Rectangle getRepaintBounds() {
               repaintBounds.setLocation(getLocation());
               return(repaintBounds);
          public void draw(Graphics2D g, ImageObserver observer) {
               g.setColor(dynamicColor);
               g.fill(this);
               g.drawImage(image, (int)getX()+imageX, (int)getY()+imageY, imageWidth, imageHeight, observer);
               g.setColor(Color.black);
               g.draw(this);
     public static void main(String[] args) {
          JFrame frame = new JFrame("Image dragging");
          frame.getContentPane().add(new ImageDragging(), BorderLayout.CENTER);
          frame.pack();
          frame.setVisible(true);
}import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
public class ImageDragging extends JComponent {
     Vector images;
     Image backgroundImage;
     RectangularImage selectedImage;
     final static Color[] colors = new Color[] {Color.blue, Color.red, Color.green, Color.yellow, Color.pink, Color.white, Color.orange };
     final static Random random = new Random(System.currentTimeMillis());
     public ImageDragging() {
          images = new Vector();
          backgroundImage = (new ImageIcon("backgroundImage.jpg")).getImage();
          images.add(new RectangularImage("im1.gif", new Point(10,10), new Dimension(150,150)));
          images.add(new RectangularImage("im1.gif", new Point(20,20), new Dimension(70,70)));
          images.add(new RectangularImage("im1.gif", new Point(30,30), new Dimension(20,20)));
          MyMouseAdapter mouseAdapter = new MyMouseAdapter();
          addMouseListener(mouseAdapter);
          addMouseMotionListener(mouseAdapter);
          setPreferredSize(new Dimension(400,400));
     final static Color getRandomColor() {
          return(colors[random.nextInt(colors.length)]);
     final class MyMouseAdapter extends MouseInputAdapter {
          public void mousePressed(MouseEvent e) {
               selectedImage = getImageAt(e.getPoint());
               if (selectedImage == null) {
                    return;
               else {
                    selectedImage.setMouseLocation(e.getPoint());
                    selectedImage.setColor(getRandomColor()); // change the background color randomly each time we click on the image
                    repaint(selectedImage.getRepaintBounds());
          public void mouseDragged(MouseEvent e) {
               if (selectedImage != null) {
                    repaint(selectedImage.getRepaintBounds());
                    selectedImage.moveTo(e.getPoint());
                    repaint(selectedImage.getRepaintBounds());
          public void mouseReleased(MouseEvent e) {
               if (selectedImage != null) {
                    selectedImage.moveTo(e.getPoint());
                    repaint(selectedImage.getRepaintBounds());
                    selectedImage = null;
     public final void paintComponent(Graphics g) {
          Graphics2D g2D = (Graphics2D)g;
          g2D.drawImage(backgroundImage, 0, 0, this);
          /* if you want to fill all the background and your background image is smaller than it,
          use this instead :
          g2D.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(),this);*/
          RectangularImage im;
          for (Enumeration e = images.elements(); e.hasMoreElements();) {     
               im = (RectangularImage)e.nextElement();
               im.draw(g2D, this);
     public final RectangularImage getImageAt(Point p) {
          RectangularImage im;
          for (ListIterator e = images.listIterator(images.size()); e.hasPrevious();) {     
               im = (RectangularImage)e.previous();
               if (im.contains(p)) {
                    return(im);     
          return(null);
     final class RectangularImage extends Rectangle {
          Image image;     
          Point selectedPoint;
          Color dynamicColor;
          Rectangle repaintBounds;
          int imageX;
          int imageY;
          int imageWidth;
          int imageHeight;
          public RectangularImage(String filename, Point location, Dimension dimension) {
               ImageIcon ic = new ImageIcon(filename);
               image = ic.getImage();
               setBounds((int)location.getX(), (int)location.getY(), (int)dimension.getWidth(), (int)dimension.getHeight());
               repaintBounds = new Rectangle(0,0,(int)getWidth()+1, (int)getHeight()+1);
               /* These following values are used to center the image in the rectangle if the image is smaller than it
               and to rescale the image if it is bigger. */
               imageWidth = (int)ic.getIconWidth();
               imageWidth = imageWidth>width-2?width-2:imageWidth;
               imageHeight = (int)ic.getIconHeight();
               imageHeight = imageHeight>height-2?height-2:imageHeight;
               imageX = imageWidth==width-2?1:(int)((width-2-imageWidth)/2);
               imageY = imageHeight==height-2?1:(int)((height-2-imageHeight)/2);
               selectedPoint = new Point(0,0);
               dynamicColor = Color.blue;
          public void setMouseLocation(Point p) {
               selectedPoint.setLocation((int)(p.getX()-getX()), (int)(p.getY()-getY()));
          public void moveTo(Point p) {
               setLocation((int)(p.getX()-selectedPoint.getX()), (int)(p.getY()-selectedPoint.getY()));
          public void setColor(Color c) {
               dynamicColor = c;
          public Rectangle getRepaintBounds() {
               repaintBounds.setLocation(getLocation());
               return(repaintBounds);
          public void draw(Graphics2D g, ImageObserver observer) {
               g.setColor(dynamicColor);
               g.fill(this);
               g.drawImage(image, (int)getX()+imageX, (int)getY()+imageY, imageWidth, imageHeight, observer);
               g.setColor(Color.black);
               g.draw(this);
     public static void main(String[] args) {
          JFrame frame = new JFrame("Image dragging");
          frame.getContentPane().add(new ImageDragging(), BorderLayout.CENTER);
          frame.pack();
          frame.setVisible(true);
Hope this helps,
Denis

Similar Messages

  • Having a problem with drawImage() and dont know why...

    OK, I'm having some problems drawing my image onto the frame.. It will let me draw string, add components, etc.. but as soon as it come to trying to draw an image it just doesn't wanna..
    Here is my code:
    import java.awt.*;
    public class Messenger extends Frame {
         private boolean laidOut = false;
         private TextField words;
        private TextArea messages;
        private Button ip, port, nickname;
        public Messenger() {
             super();
             setLayout(null);
             //set layout font
             setFont(new Font("Helvetica", Font.PLAIN, 14));
             //set application icon
             Image icon =  Toolkit.getDefaultToolkit().getImage("data/dh002.uM");
             setIconImage((icon));
            //add components
            words = new TextField(30);
            add(words);
            messages = new TextArea("", 5, 20, TextArea.SCROLLBARS_VERTICAL_ONLY);
            add(messages);
            ip = new Button("IP Address");
            add(ip);
            port = new Button("Port");
            add(port);
            nickname = new Button("Nickname");
            add(nickname);
        public void paint(Graphics g) {
            if (!laidOut) {
                Insets insets = insets();
                //draw layout
                g.drawImage("data/dh003.uM", 0 + insets.left, 0 + insets.top);
                ip.reshape(5 + insets.left, 80 + insets.top, 100, 20);
                port.reshape(105 + insets.left, 80 + insets.top, 100, 20);
                nickname.reshape(205 + insets.left, 80 + insets.top, 100, 20);
                messages.reshape(5 + insets.left, 100 + insets.top, 485, 300);
                g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top) ;
                words.reshape(5 + insets.left, 440 + insets.top, 485, 20);
                laidOut = true;
        public boolean handleEvent(Event e) {
            if (e.id == Event.WINDOW_DESTROY) {
                System.exit(0);
            return super.handleEvent(e);
        public static void main(String args[]) {
            Messenger window = new Messenger();
            Insets insets = window.insets();
              //init window..
            window.setTitle("Unrivaled Messenger");
            window.resize(500 + insets.left + insets.right,
                          500 + insets.top + insets.bottom);
            window.setBackground(SystemColor.control);
            window.show();
    }Im only new to Java, maybe I've left something out ? Any help will be much appreciated, thanks :)

    Thanks! Got the image to display now... but, next problem.. its a strange one, whenever the application is minimized or has something dragged/popup over the top of it, those sections of text/images disappear... anyone know a reason for this? im using the d.drawImage() like displayed in my code above.. this is the final code for my image..
    Image banner = null;
    try {
         banner = ImageIO.read(new File("data/dh003.uM"));
    } catch(IOException e) { }
    g.drawImage(banner,0 + insets.left, 0 + insets.top, this);and as for my text...
    g.setFont(new Font("Arial",1,14));
    g.drawString("Type your message below:", 5 + insets.left, 425 + insets.top);Thanks in advance!

  • Problem with drawImage

    I've got a JLabel that i've extended in order to stretch an image to the full size of the JLabel.
    public class ImageLabel extends JLabel {
    public ImageLabel() {
    super();
    public ImageLabel(ImageIcon imageIcon) {
    super();
    super.setIcon(imageIcon);
    private void setIcon(ImageIcon imageIcon) {
    super.setIcon(imageIcon);
    public void paintComponent(Graphics g) {
    g.drawImage(
    ((ImageIcon)super.getIcon()).getImage().getScaledInstance
    (this.getWidth(), this.getHeight(), Image.SCALE_FAST), 0, 0,
    this);
    the above works just fine but the problem is that drawImage is getting the image from the original source which is the web server so it is making a request for the image to the web server. i don't want this because i've already cached the image and am passing the image as an ImageIcon to my class using setIcon.
    Is there a way to stretch an image using my cached image without it having to get the source image?
    I've tried getting around this problem by just using JLabel and the getScaledInstance method of the Image class. This also works however i can't get the correct width and height of the JLabel to scale the image. It never displays the correct size for the first image i display but works fine for subsequent images.
    Thanks for any suggestions!

    What do you have set for the source of the image that you're using to build the icon? Is this an applet or an application? If it's an application, and you have a URL set as the source of the image, then you could first have the program download the image into a file, then use that file as the source, and then later delete the file if you didn't want the file to stay permanently with the program.
    If it's an applet, then as far as I know, there's really no way around having it download the image from the web when it's requested, unless you did something such as stuck both the program and the graphic in a jar file so when the browser downloaded the program it also got the graphic along with it.

  • Problem for drawimage

    i want to draw a image random and they are not stick together but i try that code it only have one image show up.how to do draw a image and they are not stick together too?
    and i have one more question how to make a image stand on other image . because i want to make a person walk on a floor.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Ellipse2D;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Downstair  {
        Playscreen graphicComponent;
        JPanel centerPanel;
        private JPanel getCenterPanel() {
            graphicComponent = new Playscreen();
            CardLayout cards = new CardLayout();
            centerPanel = new JPanel(cards);
            centerPanel.add("Menu", getMenuPanel());
            centerPanel.add("Game", graphicComponent);
            return centerPanel;
        private JPanel getMenuPanel() {
            // Create components.
            String[] gameMenulist = {"New Game","Abouts","how to play","Options","Exit"};
            JList menulist= new JList(gameMenulist);
            ListSelectionModel menulistModel = menulist.getSelectionModel();
            //menulist setting
            menulist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
            menulist.setVisibleRowCount(-1);
            menulist.setBackground(Color.BLACK);
            menulist.setForeground(Color.WHITE);
            menulist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            menulist.addListSelectionListener(new ListListener());
            JPanel panel = new JPanel() {
                Image bg = new ImageIcon("image/bgimg.jpg").getImage();
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(bg, 0, 0, this);
            panel.setBackground(Color.white);
            panel.setOpaque(true);  // default value
            panel.setLayout(new GridBagLayout());
            GridBagConstraints a = new GridBagConstraints();
            // The anchor constraint requires a non-zero weight
            // constraint in the direction it is going, ie,
            // weightx for horizontal values such as EAST,
            // WEST, LINE_START, LINE_END.
            a.anchor = GridBagConstraints.PAGE_END;
            panel.add(menulist, a);
            return panel;
        public static void main(String[] args) {
            Downstair app = new Downstair();
            JFrame mainframe = new JFrame();
            mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainframe.getContentPane().add(app.getCenterPanel());
            mainframe.setSize(600, 600);
            mainframe.setVisible(true);
        private class ListListener implements ListSelectionListener {
            public void valueChanged(ListSelectionEvent e) {
                if(!e.getValueIsAdjusting()) {
                    JList list = (JList)e.getSource();
                    int index = list.getSelectedIndex();
                    switch(index) {
                        case 0:
                            CardLayout cards = (CardLayout)centerPanel.getLayout();
                            cards.show(centerPanel, "Game");
                            break;
                        case 4:
                            System.exit(0);
                            break;
                        default:
                            System.out.println("unexpected type: " + index);
    class Playscreen extends JPanel {
         ImageIcon playbg;
         ImageIcon playerIcon;
         ImageIcon[] stair;
         int floor;
         int live;
         int randomX;
         int randomY;
         int randompic;
         public Playscreen(){
              playbg = new ImageIcon("image/bgimg.jpg");
              playerIcon = new ImageIcon("image/ball.gif")[10];
              stair = new ImageIcon("image/stair.jpg");
              randomX = (int)( ( Math.random() * 400 ) + 1 );
              randomY = (int)( ( Math.random() * 400 ) + 1 );
              randompic = (int)( ( Math.random() * 10 ) + 10 );
              setBackground(Color.white);
              setOpaque(true);
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.drawImage(playbg.getImage(), 0, 0, this);
              for(int numpic= 0; numpic < 10 ; numpic++){
                   g.drawImage(playerIcon.getImage(), randomX, randomY, this);
    }Message was edited by:
    nickgoldgodl

    fileNames = new String[20];
    20 images is a lot for this small space.
    Recall one of comments from reply 5:
    About the method setRects: If there are too many rectangles or if they are too big
    or if the graphic component is too small this method may not be able to find a legal
    location for one of the rectangles.
    What this means is this: if an acceptable location cannot be found for any of the rects
    (which are used to place the images) your app will freeze while setRect goes on in an
    infinite loop.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Downstair  {
        Playscreen playScreen;
        Pseudo pseudo;
        JPanel rightPanel;
        private JPanel getCenterPanel() {
            // Instantiate components.
            playScreen = new Playscreen();
            pseudo = new Pseudo();
            // Layout right panel.
            rightPanel = new JPanel(new CardLayout());
            rightPanel.add("Menu", getMenuPanel());
            rightPanel.add("Game", playScreen);
            // Layout center panel.
            JPanel centerPanel = new JPanel(new BorderLayout());
            centerPanel.add(pseudo,     BorderLayout.LINE_START);
            centerPanel.add(rightPanel, BorderLayout.CENTER);
            return centerPanel;
        private JPanel getMenuPanel() {
            // Create components.
            String[] gameMenulist = {"New Game","Abouts","how to play","Options","Exit"};
            JList menulist= new JList(gameMenulist);
            ListSelectionModel menulistModel = menulist.getSelectionModel();
            //menulist setting
            menulist.setLayoutOrientation(JList.HORIZONTAL_WRAP);
            menulist.setVisibleRowCount(-1);
            menulist.setBackground(Color.BLACK);
            menulist.setForeground(Color.WHITE);
            menulist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            menulist.addListSelectionListener(new ListListener());
            JPanel panel = new JPanel() {
                Image bg = new ImageIcon(//"image/bgimg.jpg").getImage();
                                         "images/geek-----.gif").getImage();
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(bg, 0, 0, this);
            panel.setBackground(Color.white);
            panel.setOpaque(true);
            panel.setLayout(new GridBagLayout());
            GridBagConstraints a = new GridBagConstraints();
            a.anchor = GridBagConstraints.PAGE_END;
            panel.add(menulist, a);
            return panel;
        public static void main(String[] args) {
            Downstair app = new Downstair();
            JFrame mainframe = new JFrame();
            mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mainframe.getContentPane().add(app.getCenterPanel());
    //        mainframe.setSize(600, 600);
            mainframe.pack();
            mainframe.setVisible(true);
        private class ListListener implements ListSelectionListener {
            public void valueChanged(ListSelectionEvent e) {
                if(!e.getValueIsAdjusting()) {
                    JList list = (JList)e.getSource();
                    int index = list.getSelectedIndex();
                    switch(index) {
                        case 0:
                            CardLayout cards = (CardLayout)rightPanel.getLayout();
                            cards.show(rightPanel, "Game");
                            break;
                        case 4:
                            System.exit(0);
                            break;
                        default:
                            System.out.println("unexpected type: " + index);
    class Playscreen extends JPanel {
         ImageIcon playbg;
         ImageIcon playerIcon;
         ImageIcon[] stair;
         int floor;
         int live;
         Point loc = new Point(100,100);
         int dx = 3;
             int dy = 3;
         Rectangle[] rects;
         Random seed = new Random();
         String[] fileNames;
         boolean firstTime = true;
         public Playscreen(){
              String img = //"stair.jpg";
                             "../images/geek-----.gif";
              fileNames = new String[5];
              playbg = new ImageIcon(//"image/bgimg.jpg");
                                       "../images/Bird.gif");
              playerIcon = new ImageIcon(//"image/player.gif");            
                                           "../images/Cat.gif");
              setBackground(Color.white);
              setOpaque(true);
              registerKeys();
              setFocusable(true);
              for(int f = 0; f < fileNames.length; f++){
                   fileNames[f] = img;
              rects = new Rectangle[fileNames.length];
              stair = new ImageIcon[fileNames.length];
              for(int j = 0; j < rects.length; j++) {
                     stair[j] = new ImageIcon(//"Image/" + fileNames[j]);
                                               "../images/" + fileNames[j]);
                     rects[j] = new Rectangle(stair[j].getIconWidth(),
                                               stair[j].getIconHeight());
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.drawImage(playbg.getImage(), 0, 0, this);
              g.drawImage(playerIcon.getImage(), loc.x, loc.y, this);
              if(firstTime) {
                     setRects();
                     firstTime = false;
              for(int j = 0; j < stair.length; j++) {
                         g.drawImage(stair[j].getImage(), rects[j].x, rects[j].y, this);
        public Dimension getPreferredSize() {
            return new Dimension(600,500);
         private void setRects() {
                 Point p;
                int count = 0;
                 for(int j = 0; j < rects.length; j++) {
                     do {
                             p = getRandomLocationFor(rects[j]);
                              rects[j].setLocation(p);
                            System.out.println("count for " + j + " = " + count++);
                         } while(!notTouching(j));
             private boolean notTouching(int index) {
                for(int j = 0; j < index; j++) {
                     if(rects[j].intersects(rects[index]))
                          return false;
                 return true;
         private Point getRandomLocationFor(Rectangle r) {
                 Point p = new Point();
                 p.x = seed.nextInt(getWidth()  - r.width );
                 p.y = seed.nextInt(getHeight() - r.height);
                 return p;
         private void registerKeys() {
                 int c = JComponent.WHEN_IN_FOCUSED_WINDOW;
                 getInputMap(c).put(KeyStroke.getKeyStroke("UP"), "UP");
                 getActionMap().put("UP", upAction);
                 getInputMap(c).put(KeyStroke.getKeyStroke("LEFT"), "LEFT");
                 getActionMap().put("LEFT", leftAction);
                getInputMap(c).put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
                 getActionMap().put("DOWN", downAction);
                 getInputMap(c).put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
                 getActionMap().put("RIGHT", rightAction);
         private Action upAction = new AbstractAction() {
                 public void actionPerformed(ActionEvent e) {
             private Action leftAction = new AbstractAction() {
                     public void actionPerformed(ActionEvent e) {
                          loc.x -= dx;
                          repaint();
             private Action downAction = new AbstractAction() {
                 public void actionPerformed(ActionEvent e) {
             private Action rightAction = new AbstractAction() {
                 public void actionPerformed(ActionEvent e) {
                          loc.x += dx;
                          repaint();
    class Pseudo extends JPanel {
        JButton ok = new JButton("Okay");
        public Pseudo() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(new JLabel("Pseudo Panel", JLabel.CENTER), gbc);
            gbc.weighty = 1.0;
            add(ok, gbc);
            setBorder(BorderFactory.createLineBorder(Color.red));
        public Dimension getPreferredSize() {
            return new Dimension(200,100);
    }

  • Problems with drawImage

    Hi! I try to do following:
    1. I create BufferedImage and print some text on it' Graphics object via drawString().
    2. In paint() method of my applet I draw this image on applet's graphics using drawImage().
    3. I also print some text on applets' Graphics object via drawString().
    4. Then I launch the applet and print it contents on printer.
    And I found that text drawn directly on applet's graphic printed softly, but text drawn on image was sharp. On srceen they both were similar one to another.
    I have to use drawImage. Can anybody help me?
    There is code of my Applet:
    import java.awt.*;
    import java.applet.*;
    import java.awt.image.BufferedImage;
    import java.awt.image.Raster;
    public class Applet1 extends Applet {
    public void paint(Graphics g){
    Font font = new Font(null,Font.PLAIN,40);
    BufferedImage bi = new BufferedImage (400,300,BufferedImage.TYPE_BYTE_GRAY);
    Graphics graphics = (Graphics)bi.getGraphics();
    graphics.setColor(Color.white);
    graphics.fillRect(0,0,800,600);
    graphics.setColor(Color.black);
    graphics.setFont(font);
    graphics.drawString("First Testing String",20,40);
    graphics.drawString("Second Testing String",30,80);
    graphics.drawString("Third Testing String",40,120);
    g.drawImage(bi,0,0,null);
    g.setColor(Color.black);
    g.setFont(font);
    g.drawString("First Testing String",20,160);
    g.drawString("Second Testing String",30,200);
    g.drawString("Third Testing String",40,240);
    public static void main(String[] args) {
    Applet1 applet = new Applet1();
    applet.init();
    applet.start();

    As far as I remember there is passed a different Graphics object (other resolution for one thing) to either screen or printer device. Also you might check out the print(Graphics g) method.
    You might know that already.

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • Why there are nothing after I used drawImage()?

    Hello guys, I got a problem in drawImage(), and hoping that sombody can help me out.
    The code blew is copied from a Java book, it can run in my computer, without any error message, but why the image "mypc01_64.png" can not be drawn on the JPanel?
    package TwoD;
    import java.awt.*;
    import javax.swing.*;
    * @author Jack
    public class DisplayImage extends JFrame{
        /** Creates a new instance of DisplayImage */
        public DisplayImage() {
            add(new ImageCanvas());
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            JFrame frame = new DisplayImage();
            frame.setTitle("DisplayDemo");
            frame.setSize(300,300);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);       
    class ImageCanvas extends JPanel{
        ImageIcon imageIcon = new ImageIcon("/TwoD/mypc01_64.png");
        Image image = imageIcon.getImage();
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            if(image!=null){
                g.drawImage(image,0,0,getWidth(), getHeight(), this);
    }the source code and the image are in the same folder named "TwoD".

    hi,
    the same code is just working fine with me. i have just changes the image to a physical image that is present in my machine, and i have tried with absolute path. make sure you can see the image. it has got something. i have tried with Sunset.jpg provided with xp.
    ImageIcon     imageIcon     = new ImageIcon("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg");regards
    Aniruddha

  • Cant seem to get memoryimagesource to work right

    Ok ive been messing with memory image source for a while here.
    at least 6 hour's and i cant seem to get it to work in fullscreen.
    i have tryed it a few different ways and im getting errors no matter what i do.
    i figured id search the web for a example of memoryimagesorce in fullscreen but i can't find any!!!
    anyways im haveing problems with drawimage().
    i have the blue bar poping back up in this one even though i set undecorated to true.
    when i try to use bufferstrategy it was even worse it locked up my comp 2 time's
    here my horribly buggy code so far.
    anyone have a example of the right way to use memory image source in fullscreen.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class FStest6 extends Frame{
      // VARIABLES OR USED CLASSES
         DisplayMode D_Mode;
         Frame frame;
         int w,h;
         // MAIN
      public static void main(String[] args) {
          try {
       FStest6 test = new FStest6();// call constructor to begin 
       } catch (Exception e) {e.printStackTrace();}
       System.exit(0);
      // CONSTRUCTOR
      public FStest6(){
          GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
       GraphicsDevice device = env.getDefaultScreenDevice();
       if(device.isFullScreenSupported() == false){System.out.println(" Warning full screen is not supported "); }
       else{device.setFullScreenWindow(this);}
       GraphicsConfiguration gc = device.getDefaultConfiguration();
       frame = new Frame(gc);
       frame.setUndecorated(true);
       frame.setIgnoreRepaint(true);
       frame.setResizable(false);
       D_Mode = device.getDisplayMode();
       if (device.isDisplayChangeSupported() == false) {System.out.println(" warning display mode unsupported ");
       }else{
       D_Mode = new DisplayMode(640, 480, 32, 0);}
       show();
       w = getSize().width;
       h = getSize().height;
      try{
       int [] pixels = new int[w * h];
       DirectColorModel colorModel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF,0);
       MemoryImageSource source = new MemoryImageSource(w, h, colorModel, pixels, 0, w);
       source.setAnimated(true);
       source.setFullBufferUpdates(true);
       Image img = createImage(source);
       boolean going = true;long timer =0;
       while(going){
       if(timer > 9999999){going = false;System.out.println(" exiting loop ");}
       render(pixels,img,source);
      }catch (Exception e){e.printStackTrace();}
      frame.dispose();
    public void render(int [] pixels,Image img,MemoryImageSource source){
       //Graphics g = img.getGraphics();
       int n =0;int col = 0;
       long t = System.currentTimeMillis();
       for (int x=0;x<640;x++){
        for (int y=0;y<480;y++){
         n = y*640 + x;
         if(col < 254){col ++;}else{col = 0;}
         pixels[n] = col;
       source.newPixels();
       //g.drawImage(img, 0, 0, null);
       System.out.println((System.currentTimeMillis()-t)/100f);
    }//eof class

    Now my code is painting exactly one time, the loop is going but nothing's happening. It should be displaying the different color lines moveing and changeing color.
    Also ive come to a problem ive had before in the tutorial,
    about not useing paint and update.
    however thier should logically be a method like drawimage to use
    or i should be able to use it. but its not doing anything.
    the application window is drawn directly to the screen (active rendering).
    This simplifies painting quite a bit, since you don't ever need to worry about paint events.
    In fact, paint events delivered by the operating system may even be delivered
    at inappropriate or unpredictable times when in full-screen exclusive mode.
    Instead of relying on the paint method in full-screen exclusive mode, drawing code is usually
    more appropriately done in a rendering loop:
    public void myRenderingLoop() {
        while (!done) {
             Graphics myGraphics = getPaintGraphics();
             // Draw as appropriate using myGraphics
             myGraphics.dispose();
    Such a rendering loop can done from any thread,
    either its own helper thread or as part of the main application thread.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class FStest11 extends Frame implements Runnable, KeyListener {
    Image img;
    int w,h;
    int cx,cy;
    boolean done;
    public FStest11() {
        GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        setUndecorated(true);// knock out bars and stuff
        setIgnoreRepaint(true);// ignore automatic repaint.
        if (device.isFullScreenSupported()) {
        device.setFullScreenWindow(this);}
        if (device.isDisplayChangeSupported()) {
        device.setDisplayMode(new DisplayMode(640,480,16,0));}
        show();//show fullscreen.
        w = getSize().width;
        h = getSize().height;
        done = false;
        addKeyListener(this);
        //new Thread(this).start();
        run();
        public void run(){
        int [] pixels = new int[w * h];// create the array that we will use for the pixels that i alter myself
        DirectColorModel colorModel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF,0);// create are ARGB 32bit pixel colormodel
        MemoryImageSource producerobj = new MemoryImageSource(w, h, colorModel, pixels, 0, w);// create a new producer
        producerobj.setAnimated(true);//Changes this memory image into a multi-frame animation .
        img = createImage(producerobj);//create's image from specifyed producerobject thus img should be a producer
        // i could abstract this class and make the below into a abstracted method
        while (!done) {
        int n =0,rcol =0,gcol =50,bcol =101;
        //Graphics gfx = img.getGraphics();// ackk!!!! cant be used in this context
        for (int x=0;x<640;x++){
         for (int y=0;y<480;y++){
          n = y*640 + x;
          bcol ++;rcol ++;
          if(bcol >253){bcol =0;gcol ++;}
          if(gcol > 253){gcol = 0;}
          if(rcol > 253){rcol = 0;}
          pixels[n] = ( ((rcol &0xff) <<16)|((gcol &0xff) <<8)|(bcol &0xff) );  // draw some new pixels
        // this would be the render code but i cant get it to work like the tutorial says.
        Graphics g = this.getGraphics();
        producerobj.newPixels();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        System.out.println(" in loop " );
    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {if (!done){ done = true;System.out.println(" keypressed " ); } // program exits on any key press
    public static void main(String[] args) {
       System.out.println(" app " );
       new FStest11();
       System.out.println(" exit " );
       System.exit(0);
    }

  • Graphics disappearing from canvas

    I am writing an application with a canvas. But the graphics on the canvas are disappearing when the screen is minimised or another window comes on top of the canvas. The code below is a small part of it but the problem occurs in this part of the application. It will draw lines when mouse pressed and dragged on canvsas. The code should run. If anyone could help me I would be really grateful as I can't seem to find the problem and I think it just needs someone who has'nt seen the code before to find the problem.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class TestCanvas extends JFrame
       Container c;
       public TestCanvas()
            c = getContentPane();
            TheCanvas can = new TheCanvas();
            JPanel two = new JPanel();
            c.add(can.pad);
            setSize(600,600);
            setVisible(true);
       class TheCanvas extends Canvas implements MouseListener, MouseMotionListener
           Canvas pad;
           public static final int mode_paint = 0;
           public static final int mode_xor = 1;
           public static final int line = 1;
           public static final int drawType = 1;
           public Color drawColor;
           boolean showingPicture = false;
           protected Image offScreen = null;
           public int drawThickness = 1;
           tempLine draftLine;
           boolean dragging = false;
           int oldx = 0;
           int oldy = 0;
          TheCanvas()
             pad = new Canvas();
             pad.setBackground(Color.white);
             pad.setVisible(true);
             pad.setSize(500, 500);
             //setSize(300,300);
             drawColor = Color.black;
             pad.addMouseListener(this);
          pad.addMouseMotionListener(this);
          offScreen = null;
          synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
              else
                   width = pad.getWidth();
                   height = pad.getHeight();
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
                    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
           synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
          //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
        public void mouseDragged(MouseEvent e)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
    public static void main(String[] args)
         TestCanvas one = new TestCanvas();
    }

    Thanks for replying, I really appreciate it. I have made the changes but the problem is still occurring. I'll show you the code below. If you have any suggestions I would really appreciate it.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class TestCanvas extends JFrame
       Container c;
       public TestCanvas()
            c = getContentPane();
            TheCanvas can = new TheCanvas();
            JPanel two = new JPanel();
            c.add(can);
            setSize(600,600);
            setVisible(true);
       class TheCanvas extends Canvas implements MouseListener, MouseMotionListener
           Canvas pad;
           public static final int mode_paint = 0;
           public static final int mode_xor = 1;
           public static final int line = 1;
           public static final int drawType = 1;
           public Color drawColor;
           boolean showingPicture = false;
           protected Image offScreen = null;
           public int drawThickness = 1;
           tempLine draftLine;
           boolean dragging = false;
           int oldx = 0;
           int oldy = 0;
          TheCanvas()
             //pad = new Canvas();
             //pad.
                setBackground(Color.white);
             //pad.
                setVisible(true);
             //pad.
                setSize(500, 500);
             //setSize(300,300);
             drawColor = Color.black;
                addMouseListener(this);
          addMouseMotionListener(this);
          offScreen = null;
          synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
              else
                       width = getSize().width;
                            height = getSize().height;
                   //width = pad.getWidth();
                   //height = pad.getHeight();
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
                    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, this);
              g.dispose();
           synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
          //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         this.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent e)
         this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
        public void mouseDragged(MouseEvent e)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
    public static void main(String[] args)
         TestCanvas one = new TestCanvas();
    }

  • Graphic.drawImage Problem

    Hi everyone, here is my problem:
    I drew a knob using photoshop, saved as .gif file.
    I used drawImage method to draw the image into my application.
    However the rounded edge appear to be rough and with white dots, seems like the knob got bitten by some wild animal.
    I already used anti-aliasing, so why the image is still painted so poorly at the edges??
    Anyone got an idea? Thanks in advance!

    Hi everyone, here is my problem:
    I drew a knob using photoshop, saved as .gif file.
    I used drawImage method to draw the image into my
    application.
    However the rounded edge appear to be rough and with
    white dots, seems like the knob got bitten by some
    wild animal.
    I already used anti-aliasing, so why the image is
    still painted so poorly at the edges??
    Anyone got an idea? Thanks in advance!The problem is that gif files don't include the alpha channel for your image. Instead, one of the indexes in the color map (gifs use color maps, never true color) is designated as transparent.
    The result of this is that some of the pixels on the edge of the image that should have been only partly drawn according to the alpha channel, are drawn incorrectly.
    In order to get the desired result, you have a couple of choices:
    1. Create the image with the correct background color, then save it without specifying a transparent color. This may be impossible to do if you don't know the background color, or if you want to draw on top of an image or something.
    2. Save your image as two different files, one containing the image data and one containing the alpha channel. Then use the image manipulation API in Java2D to combine the two files into one Java Image. The image rendering methods of Java can handle transparency just fine, it's just a question of getting the transparency data into Java.

  • Graphics.drawImage() problem

    Hi,
    I am trying to draw an image to the screen.
    Here is my code:
    public void paintArrowButtonForeground(SynthContext context, Graphics g,
                   int x, int y, int w, int h, int direction) {
              if (direction == SwingUtilities.SOUTH) {
                   if (image == null) {
                        image = Toolkit.getDefaultToolkit().getImage(
                                  this.getClass().getResource(UIManager.getString("Arrow.8x8.down")));
                   g.drawImage(image, x + image.getWidth(context.getComponent()) / 2,
                             y + image.getHeight(context.getComponent()) / 2,
                             (JButton) context.getComponent());
    I get image but it does not &#1072;ppear on screen.
    Can some one tell me what is wrong?
    Thank you in advance

    First thing's first...
    Using Toolkit.getImage() doesn't load the image, it starts loading the image. You normally use a MediaTracker to make sure that the image is loaded.
    Second thing's..., well, second...
    It is generally a bad idea to load images in the paint method. You should load the images needed for the class in the constructor, maybe or some other thread or someplace else before they are need in the paint method.

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Swing and Active rendering problem

    Hopefully this is the right place to post. I have a problem with active rendering and swing. Basically my code below messes up when I start rendering the swing either using repaint() or paint(g).
    If I use repaint() then the gui flickers like mad and if I use paint(g) then I get deadlocks when typing into the textbox.
    Any help would be great for what am I doing wrong. How do I solve this problem?
    public GuiWindow() {
              try {
                   guiImage = ImageIO.read(this.getClass().getResource("Images/Gui2.png"));
              } catch (Exception e) {}
              this.setPreferredSize(new Dimension(800, 600));
              this.setUndecorated(true);
              this.setIgnoreRepaint(true);
              this.setResizable(false);
              this.addKeyListener(kl);
              this.setFocusable(true);
              this.requestFocus();
              this.setTitle("PWO");
              JPanel panel = new JPanel()
              public void paintComponent(Graphics g)
              //Scale image to size of component
                   super.paintComponent(g);
                   Dimension d = getSize();
                   g.drawImage(guiImage, 0, 0, d.width, d.height, null);
                   this.setIgnoreRepaint(true);
                            //draw background for the gui
              JTextField Name = new JTextField(20);
              panel.add(Name);
              this.setContentPane(panel);
                    myRenderingLoop();
    public void myRenderingLoop() {
              int fps = 20;
              long startTime;
              int frameDelay = 1000 / fps;
              this.createBufferStrategy(2);
              BufferStrategy myStrategy = this.getBufferStrategy();
              Graphics2D g;
              while (!done) {
                   startTime = System.currentTimeMillis();          
                   do {
                        do {
                             g = (Graphics2D)myStrategy.getDrawGraphics();
                             this.repaint();
                             this.render(g); //render the game
                             g.dispose();
                        } while (myStrategy.contentsRestored());
                        myStrategy.show();
                        Toolkit.getDefaultToolkit().sync();
                   } while (myStrategy.contentsLost());
                   while (System.currentTimeMillis() - startTime < frameDelay) {
                        try {
                             Thread.sleep(15);
                        } catch (InterruptedException ex){}
         }Edited by: Aammbi on Apr 6, 2008 7:05 PM

    I really have no idea what your code is trying to do, but a few comments.
    1) There is no need to use a BufferStrategy since Swing is double buffered automatically
    2) Don't use a while loop with a Thread.sleep(). Chances are the GUI EDT is sleeping which makes the GUI unresponsive
    3) Use a Swing Timer for animation.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Problem converting a (working) Java program into an applet

    When I'm trying to access an Image through a call to :
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    I'm getting a nullPointerException as a result of the call to getDocumentBase() :
    C:\Chantier\Java\BallsApplet
    AppletViewer testBallsApplet.htmljava.lang.NullPointerException
    at java.applet.Applet.getDocumentBase(Applet.java:125)
    at Balls.<init>(Balls.java:84)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
    orAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
    onstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    at java.lang.Class.newInstance0(Class.java:296)
    at java.lang.Class.newInstance(Class.java:249)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:548)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:477)
    at sun.applet.AppletPanel.run(AppletPanel.java:290)
    at java.lang.Thread.run(Thread.java:536)
    It seems very weird to me... :-/
    (all the .gif files are in the same directory than the .class files)
    The problem appears with AppletViewer trying to open an HTML file
    containing :
    <HTML>
    <APPLET CODE="Balls.class" WIDTH=300 HEIGHT=211>
    </APPLET>
    </HTML>
    (I tried unsuccessfully the CODEBASE and ARCHIVE attributes, with and without putting the .gif and .class into a .jar file)
    I can't find the solution by myself, so, I'd be very glad if someone could help
    me with this... Thank you very much in advance ! :-)
    You'll find below the source of a small game that I wrote and debugged (without
    problem) and that I'm now (unsuccessfully) trying to convert into an Applet :
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.URL;
    public class Balls extends java.applet.Applet implements Runnable, KeyListener
    private Image offScreenImage;
    private Image backGroundImage;
    private Image[] gifImages = new Image[6];
    private Image PressStart ;
    private Sprite pressStartSprite = null ;
    private Image YouLose ;
    private Sprite YouLoseSprite = null ;
    private Image NextStage ;
    private Sprite NextStageSprite = null ;
    private Image GamePaused ;
    private Sprite GamePausedSprite = null ;
    //offscreen graphics context
    private Graphics offScreenGraphicsCtx;
    private Thread animationThread;
    private MediaTracker mediaTracker;
    private SpriteManager spriteManager;
    //Animation display rate, 12fps
    private int animationDelay = 83;
    private Random rand = new Random(System.currentTimeMillis());
    private int message = 0 ; // 0 = no message (normal playing phase)
    // 1 = press space to start
    // 2 = press space for next level
    // 3 = game PAUSED, press space to unpause
    // 4 = You LOSE
    public static void main(String[] args)
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    }//end main
    public void start()
    //Create and start animation thread
    animationThread = new Thread(this);
    animationThread.start();
    public void init()
    try
    new Balls() ;
    catch (java.net.MalformedURLException e)
    System.out.println(e);
    public Balls() throws java.net.MalformedURLException
    {//constructor
    // Load and track the images
    mediaTracker = new MediaTracker(this);
    backGroundImage = getImage(getDocumentBase(), "background.gif");
    mediaTracker.addImage(backGroundImage, 0);
    PressStart = getImage(getDocumentBase(), "press_start.gif");
    mediaTracker.addImage(PressStart, 0);
    NextStage = getImage(getDocumentBase(), "stage_complete.gif");
    mediaTracker.addImage(NextStage, 0);
    GamePaused = getImage(getDocumentBase(), "game_paused.gif");
    mediaTracker.addImage(GamePaused, 0);
    YouLose = getImage(getDocumentBase(), "you_lose.gif");
    mediaTracker.addImage(YouLose, 0);
    //Get and track 6 images to use
    // for sprites
    gifImages[0] = getImage(getDocumentBase(), "blueball.gif");
    mediaTracker.addImage(gifImages[0], 0);
    gifImages[1] = getImage(getDocumentBase(), "redball.gif");
    mediaTracker.addImage(gifImages[1], 0);
    gifImages[2] = getImage(getDocumentBase(), "greenball.gif");
    mediaTracker.addImage(gifImages[2], 0);
    gifImages[3] = getImage(getDocumentBase(), "yellowball.gif");
    mediaTracker.addImage(gifImages[3], 0);
    gifImages[4] = getImage(getDocumentBase(), "purpleball.gif");
    mediaTracker.addImage(gifImages[4], 0);
    gifImages[5] = getImage(getDocumentBase(), "orangeball.gif");
    mediaTracker.addImage(gifImages[5], 0);
    //Block and wait for all images to
    // be loaded
    try {
    mediaTracker.waitForID(0);
    }catch (InterruptedException e) {
    System.out.println(e);
    }//end catch
    //Base the Frame size on the size
    // of the background image.
    //These getter methods return -1 if
    // the size is not yet known.
    //Insets will be used later to
    // limit the graphics area to the
    // client area of the Frame.
    int width = backGroundImage.getWidth(this);
    int height = backGroundImage.getHeight(this);
    //While not likely, it may be
    // possible that the size isn't
    // known yet. Do the following
    // just in case.
    //Wait until size is known
    while(width == -1 || height == -1)
    System.out.println("Waiting for image");
    width = backGroundImage.getWidth(this);
    height = backGroundImage.getHeight(this);
    }//end while loop
    //Display the frame
    setSize(width,height);
    setVisible(true);
    //setTitle("Balls");
    //Anonymous inner class window
    // listener to terminate the
    // program.
    this.addWindowListener
    (new WindowAdapter()
    {public void windowClosing(WindowEvent e){System.exit(0);}});
    // Add a key listener for keyboard management
    this.addKeyListener(this);
    }//end constructor
    public void run()
    Point center_place = new Point(
    backGroundImage.getWidth(this)/2-PressStart.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-PressStart.getHeight(this)/2) ;
    pressStartSprite = new Sprite(this, PressStart, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-NextStage.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-NextStage.getHeight(this)/2) ;
    NextStageSprite = new Sprite(this, NextStage, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-GamePaused.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-GamePaused.getHeight(this)/2) ;
    GamePausedSprite = new Sprite(this, GamePaused, center_place, new Point(0, 0),true);
    center_place = new Point(
    backGroundImage.getWidth(this)/2-YouLose.getWidth(this)/2,
    backGroundImage.getHeight(this)/2-YouLose.getHeight(this)/2) ;
    YouLoseSprite = new Sprite(this, YouLose, center_place, new Point(0, 0),true);
    BackgroundImage bgimage = new BackgroundImage(this, backGroundImage) ;
    for (;;) // infinite loop
    long time = System.currentTimeMillis();
    message = 1 ; // "press start to begin"
    while (message != 0)
    repaint() ;
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    boolean you_lose = false ;
    for (int max_speed = 7 ; !you_lose && max_speed < 15 ; max_speed++)
    for (int difficulty = 2 ; !you_lose && difficulty < 14 ; difficulty++)
    boolean unfinished_stage = true ;
    spriteManager = new SpriteManager(bgimage);
    spriteManager.setParameters(difficulty, max_speed) ;
    //Create 15 sprites from 6 gif
    // files.
    for (int cnt = 0; cnt < 15; cnt++)
    if (cnt == 0)
    Point position = new Point(
    backGroundImage.getWidth(this)/2-gifImages[0].getWidth(this)/2,
    backGroundImage.getHeight(this)/2-gifImages[0].getHeight(this)/2) ;
    spriteManager.addSprite(makeSprite(position, 0, false));
    else
    Point position = spriteManager.
    getEmptyPosition(new Dimension(gifImages[0].getWidth(this),
    gifImages[0].getHeight(this)));
    if (cnt < difficulty)
    spriteManager.addSprite(makeSprite(position, 1, true));
    else
    spriteManager.addSprite(makeSprite(position, 2, true));
    }//end for loop
    time = System.currentTimeMillis();
    while (!spriteManager.getFinishedStage() && !spriteManager.getGameOver())
    // Loop, sleep, and update sprite
    // positions once each 83
    // milliseconds
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    }//end while loop
    if (spriteManager.getGameOver())
    message = 4 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    you_lose = true ;
    if (spriteManager.getFinishedStage())
    message = 2 ;
    while (message != 0)
    spriteManager.update();
    repaint();
    try
    time += animationDelay;
    Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
    catch (InterruptedException e)
    System.out.println(e);
    }//end catch
    } // end for difficulty loop
    } // end for max_speed
    } // end infinite loop
    }//end run method
    private Sprite makeSprite(Point position, int imageIndex, boolean wind)
    return new Sprite(
    this,
    gifImages[imageIndex],
    position,
    new Point(rand.nextInt() % 5,
    rand.nextInt() % 5),
    wind);
    }//end makeSprite()
    //Overridden graphics update method
    // on the Frame
    public void update(Graphics g)
    //Create the offscreen graphics
    // context
    if (offScreenGraphicsCtx == null)
    offScreenImage = createImage(getSize().width,
    getSize().height);
    offScreenGraphicsCtx = offScreenImage.getGraphics();
    }//end if
    if (message == 0)
    // Draw the sprites offscreen
    spriteManager.drawScene(offScreenGraphicsCtx);
    else if (message == 1)
    pressStartSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 2)
    NextStageSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 3)
    GamePausedSprite.drawSpriteImage(offScreenGraphicsCtx);
    else if (message == 4)
    YouLoseSprite.drawSpriteImage(offScreenGraphicsCtx);
    // Draw the scene onto the screen
    if(offScreenImage != null)
    g.drawImage(offScreenImage, 0, 0, this);
    }//end if
    }//end overridden update method
    //Overridden paint method on the
    // Frame
    public void paint(Graphics g)
    //Nothing required here. All
    // drawing is done in the update
    // method above.
    }//end overridden paint method
    // Methods to handle Keyboard event
    public void keyPressed(KeyEvent evt)
    int key = evt.getKeyCode(); // Keyboard code for the pressed key.
    if (key == KeyEvent.VK_SPACE)
    if (message != 0)
    message = 0 ;
    else
    message = 3 ;
    if (key == KeyEvent.VK_LEFT)
    if (spriteManager != null)
    spriteManager.goLeft() ;
    else if (key == KeyEvent.VK_RIGHT)
    if (spriteManager != null)
    spriteManager.goRight() ;
    else if (key == KeyEvent.VK_UP)
    if (spriteManager != null)
    spriteManager.goUp() ;
    else if (key == KeyEvent.VK_DOWN)
    if (spriteManager != null)
    spriteManager.goDown() ;
    if (spriteManager != null)
    spriteManager.setMessage(message) ;
    public void keyReleased(KeyEvent evt)
    public void keyTyped(KeyEvent e)
    char key = e.getKeyChar() ;
    //~ if (key == 's')
    //~ stop = true ;
    //~ else if (key == 'c')
    //~ stop = false ;
    //~ spriteManager.setStop(stop) ;
    }//end class Balls
    //===================================//
    class BackgroundImage
    private Image image;
    private Component component;
    private Dimension size;
    public BackgroundImage(
    Component component,
    Image image)
    this.component = component;
    size = component.getSize();
    this.image = image;
    }//end construtor
    public Dimension getSize(){
    return size;
    }//end getSize()
    public Image getImage(){
    return image;
    }//end getImage()
    public void setImage(Image image){
    this.image = image;
    }//end setImage()
    public void drawBackgroundImage(Graphics g)
    g.drawImage(image, 0, 0, component);
    }//end drawBackgroundImage()
    }//end class BackgroundImage
    //===========================
    class SpriteManager extends Vector
    private BackgroundImage backgroundImage;
    private boolean finished_stage = false ;
    private boolean game_over = false ;
    private int difficulty ;
    private int max_speed ;
    public boolean getFinishedStage()
    finished_stage = true ;
    for (int cnt = difficulty ; cnt < size(); cnt++)
    Sprite sprite = (Sprite)elementAt(cnt);
    if (!sprite.getEaten())
    finished_stage = false ;
    return finished_stage ;
    public boolean getGameOver() {return game_over ;}
    public void setParameters(int diff, int speed)
    difficulty = diff ;
    max_speed = speed ;
    finished_stage = false ;
    game_over = false ;
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    sprite.setSpeed(max_speed) ;
    public SpriteManager(BackgroundImage backgroundImage)
    this.backgroundImage = backgroundImage ;
    }//end constructor
    public Point getEmptyPosition(Dimension spriteSize)
    Rectangle trialSpaceOccupied = new Rectangle(0, 0,
    spriteSize.width,
    spriteSize.height);
    Random rand = new Random(System.currentTimeMillis());
    boolean empty = false;
    int numTries = 0;
    // Search for an empty position
    while (!empty && numTries++ < 100)
    // Get a trial position
    trialSpaceOccupied.x =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().width);
    trialSpaceOccupied.y =
    Math.abs(rand.nextInt() %
    backgroundImage.
    getSize().height);
    // Iterate through existing
    // sprites, checking if position
    // is empty
    boolean collision = false;
    for(int cnt = 0;cnt < size(); cnt++)
    Rectangle testSpaceOccupied = ((Sprite)elementAt(cnt)).getSpaceOccupied();
    if (trialSpaceOccupied.intersects(testSpaceOccupied))
    collision = true;
    }//end if
    }//end for loop
    empty = !collision;
    }//end while loop
    return new Point(trialSpaceOccupied.x, trialSpaceOccupied.y);
    }//end getEmptyPosition()
    public void update()
    Sprite sprite;
    // treat special case of sprite #0 (the player)
    sprite = (Sprite)elementAt(0);
    sprite.updatePosition() ;
    int hitIndex = testForCollision(sprite);
    if (hitIndex != -1)
    if (hitIndex < difficulty)
    { // if player collides with an hunter (red ball), he loose
    sprite.setEaten() ;
    game_over = true ;
    else
    // if player collides with an hunted (green ball), he eats the green
    ((Sprite)elementAt(hitIndex)).setEaten() ;
    //Iterate through sprite list
    for (int cnt = 1;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's position
    sprite.updatePosition();
    //Test for collision. Positive
    // result indicates a collision
    hitIndex = testForCollision(sprite);
    if (hitIndex >= 0)
    //a collision has occurred
    bounceOffSprite(cnt,hitIndex);
    }//end if
    }//end for loop
    }//end update
    public void setMessage(int message)
    Sprite sprite;
    //Iterate through sprite list
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    //Update a sprite's stop status
    sprite.setMessage(message);
    }//end for loop
    }//end update
    public void goLeft()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goLeft() ;
    public void goRight()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goRight() ;
    public void goUp()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goUp() ;
    public void goDown()
    Sprite sprite = (Sprite)elementAt(0);
    sprite.goDown() ;
    private int testForCollision(Sprite testSprite)
    //Check for collision with other
    // sprites
    Sprite sprite;
    for (int cnt = 0;cnt < size(); cnt++)
    sprite = (Sprite)elementAt(cnt);
    if (sprite == testSprite)
    //don't check self
    continue;
    //Invoke testCollision method
    // of Sprite class to perform
    // the actual test.
    if (testSprite.testCollision(sprite))
    //Return index of colliding
    // sprite
    return cnt;
    }//end for loop
    return -1;//No collision detected
    }//end testForCollision()
    private void bounceOffSprite(int oneHitIndex, int otherHitIndex)
    //Swap motion vectors for
    // bounce algorithm
    Sprite oneSprite = (Sprite)elementAt(oneHitIndex);
    Sprite otherSprite = (Sprite)elementAt(otherHitIndex);
    Point swap = oneSprite.getMotionVector();
    oneSprite.setMotionVector(otherSprite.getMotionVector());
    otherSprite.setMotionVector(swap);
    }//end bounceOffSprite()
    public void drawScene(Graphics g)
    //Draw the background and erase
    // sprites from graphics area
    //Disable the following statement
    // for an interesting effect.
    backgroundImage.drawBackgroundImage(g);
    //Iterate through sprites, drawing
    // each sprite
    for (int cnt = 0;cnt < size(); cnt++)
    ((Sprite)elementAt(cnt)).drawSpriteImage(g);
    }//end drawScene()
    public void addSprite(Sprite sprite)
    addElement(sprite);
    }//end addSprite()
    }//end class SpriteManager
    //===================================//
    class Sprite
    private Component component;
    private Image image;
    private Rectangle spaceOccupied;
    private Point motionVector;
    private Rectangle bounds;
    private Random rand;
    private int message = 0 ; // number of message currently displayed (0 means "no message" = normal game)
    private int max_speed = 7 ;
    private boolean eaten = false ; // when a green sprite is eaten, it is no longer displayed on screen
    private boolean wind = true ;
    private boolean go_left = false ;
    private boolean go_right = false ;
    private boolean go_up = false ;
    private boolean go_down = false ;
    public Sprite(Component component,
    Image image,
    Point position,
    Point motionVector,
    boolean Wind
    //Seed a random number generator
    // for this sprite with the sprite
    // position.
    rand = new Random(position.x);
    this.component = component;
    this.image = image;
    setSpaceOccupied(new Rectangle(
    position.x,
    position.y,
    image.getWidth(component),
    image.getHeight(component)));
    this.motionVector = motionVector;
    this.wind = Wind ;
    //Compute edges of usable graphics
    // area in the Frame.
    int topBanner = ((Container)component).getInsets().top;
    int bottomBorder = ((Container)component).getInsets().bottom;
    int leftBorder = ((Container)component).getInsets().left;
    int rightBorder = ((Container)component).getInsets().right;
    bounds = new Rectangle( 0 + leftBorder, 0 + topBanner
    , component.getSize().width - (leftBorder + rightBorder)
    , component.getSize().height - (topBanner + bottomBorder));
    }//end constructor
    public void setMessage(int message_number)
    message = message_number ;
    public void setSpeed(int speed)
    max_speed = speed ;
    public void goLeft()
    go_left = true ;
    public void goRight()
    go_right = true ;
    public void goUp()
    go_up = true ;
    public void goDown()
    go_down = true ;
    public void setEaten()
    eaten = true ;
    setSpaceOccupied(new Rectangle(4000,4000,0,0)) ;
    public boolean getEaten()
    return eaten ;
    public Rectangle getSpaceOccupied()
    return spaceOccupied;
    }//end getSpaceOccupied()
    void setSpaceOccupied(Rectangle spaceOccupied)
    this.spaceOccupied = spaceOccupied;
    }//setSpaceOccupied()
    public void setSpaceOccupied(
    Point position){
    spaceOccupied.setLocation(
    position.x, position.y);
    }//setSpaceOccupied()
    public Point getMotionVector(){
    return motionVector;
    }//end getMotionVector()
    public void setMotionVector(
    Point motionVector){
    this.motionVector = motionVector;
    }//end setMotionVector()
    public void setBounds(Rectangle bounds)
    this.bounds = bounds;
    }//end setBounds()
    public void updatePosition()
    Point position = new Point(spaceOccupied.x, spaceOccupied.y);
    if (message != 0)
    return ;
    //Insert random behavior. During
    // each update, a sprite has about
    // one chance in 10 of making a
    // random change to its
    // motionVector. When a change
    // occurs, the motionVector
    // coordinate values are forced to
    // fall between -7 and 7. This
    // puts a cap on the maximum speed
    // for a sprite.
    if (!wind)
    if (go_left)
    motionVector.x -= 2 ;
    if (motionVector.x < -15)
    motionVector.x = -14 ;
    go_left = false ;
    if (go_right)
    motionVector.x += 2 ;
    if (motionVector.x > 15)
    motionVector.x = 14 ;
    go_right = false ;
    if (go_up)
    motionVector.y -= 2 ;
    if (motionVector.y < -15)
    motionVector.y = -14 ;
    go_up = false ;
    if (go_down)
    motionVector.y += 2 ;
    if (motionVector.y > 15)
    motionVector.y = 14 ;
    go_down = false ;
    else if(rand.nextInt() % 7 == 0)
    Point randomOffset =
    new Point(rand.nextInt() % 3,
    rand.nextInt() % 3);
    motionVector.x += randomOffset.x;
    if(motionVector.x >= max_speed)
    motionVector.x -= max_speed;
    if(motionVector.x <= -max_speed)
    motionVector.x += max_speed ;
    motionVector.y += randomOffset.y;
    if(motionVector.y >= max_speed)
    motionVector.y -= max_speed;
    if(motionVector.y <= -max_speed)
    motionVector.y += max_speed;
    }//end if
    //Move the sprite on the screen
    position.translate(motionVector.x, motionVector.y);
    //Bounce off the walls
    boolean bounceRequired = false;
    Point tempMotionVector = new Point(
    motionVector.x,
    motionVector.y);
    //Handle walls in x-dimension
    if (position.x < bounds.x)
    bounceRequired = true;
    position.x = bounds.x;
    //reverse direction in x
    tempMotionVector.x = -tempMotionVector.x;
    else if ((position.x + spaceOccupied.width) > (bounds.x + bounds.width))
    bounceRequired = true;
    position.x = bounds.x +
    bounds.width -
    spaceOccupied.width;
    //reverse direction in x
    tempMotionVector.x =
    -tempMotionVector.x;
    }//end else if
    //Handle walls in y-dimension
    if (position.y < bounds.y)
    bounceRequired = true;
    position.y = bounds.y;
    tempMotionVector.y = -tempMotionVector.y;
    else if ((position.y + spaceOccupied.height)
    > (bounds.y + bounds.height))
    bounceRequired = true;
    position.y = bounds.y +
    bounds.height -
    spaceOccupied.height;
    tempMotionVector.y =
    -tempMotionVector.y;
    }//end else if
    if(bounceRequired)
    //save new motionVector
    setMotionVector(
    tempMotionVector);
    //update spaceOccupied
    setSpaceOccupied(position);
    }//end updatePosition()
    public void drawSpriteImage(Graphics g)
    if (!eaten)
    g.drawImage(image,
    spaceOccupied.x,
    spaceOccupied.y,
    component);
    }//end drawSpriteImage()
    public boolean testCollision(Sprite testSprite)
    //Check for collision with
    // another sprite
    if (testSprite != this)
    return spaceOccupied.intersects(
    testSprite.getSpaceOccupied());
    }//end if
    return false;
    }//end testCollision
    }//end Sprite class
    //===================================//
    Thanks for your help...

    Sorry,
    Can you tell me how do you solve it because I have got the same problem.
    Can you indicate me the topic where did you find solution.
    Thank in advance.

  • Background picture n problem on display other JInternal frame

    beginer;
    this is my code below n i compile it n the picture display correctly, but it seems to hide other internal frame as well, what wrong with my code :(, the problem is been specified between ? symbols
    public class InternalFrameDemo extends JFrame implements ActionListener {
    JDesktopPane desktop;
    public InternalFrameDemo() {
    super("InternalFrameDemo");
    int inset = 50;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
    Toolkit kit = Toolkit.getDefaultToolkit();
    Image icon = kit.getImage("ADD.gif");
    setIconImage(icon);
    //Set up the GUI.
    desktop = new JDesktopPane(); //a specialized layered pane
    createFrame(); //create first "window"
    setContentPane(desktop);
    setJMenuBar(createMenuBar());
    //Make dragging a little faster but perhaps uglier.
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    ImageIcon image = new ImageIcon("abc.jpg");
    JLabel background = new JLabel(image);
    background.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
    getLayeredPane().add(background, new Integer(Integer.MIN_VALUE) );
    JPanel panel = new JPanel();
    panel.setOpaque(false);
    setContentPane( panel );
    protected JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();
    //Set up the menu item
    return menuBar;
    public void actionPerformed(ActionEvent e) {
    else {
    quit();
    protected void createFrame() {
    Books frame = new Books();
    frame.setVisible(true);
    desktop.add(frame);
    try {
    frame.setSelected(true);
    catch (java.beans.PropertyVetoException e) {}
    protected void quit() {
    System.exit(0);
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    catch (Exception e) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    InternalFrameDemo frame = new InternalFrameDemo();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Display the window.
    frame.setVisible(true);
    tanz.

    This might be what you are trying to do:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    public class TestInternalFrame extends JFrame
         ImageIcon icon;
         public TestInternalFrame()
              icon = new ImageIcon("????.jpg");
              JDesktopPane desktop = new JDesktopPane()
                 public void paintComponent(Graphics g)
                      Dimension d = getSize();
                      g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
              getContentPane().add( desktop );
              final JInternalFrame internal =
                   new JInternalFrame( "Internal Frame", true, true, true, true );
              desktop.add( internal );
              internal.setLocation( 50, 50 );
              internal.setSize( 300, 300 );
              internal.setVisible( true );
         public static void main(String args[])
              TestInternalFrame frame = new TestInternalFrame();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.setSize(400, 400);
              frame.setVisible(true);
    }

Maybe you are looking for

  • How do I create new folders in my mail?

    How do I create new folders to divide and save my mail into catergories?

  • So did anyone hack the iPad and made it work with Flash?

    Hello Dudes & Dudettes, I basically need to write a Flash game that would work through the Safari browser on the iPad. Did anyone try to re-write the Adobe iPhone packager and make it work for the iPad? I am curious... ? Also anyone  knows if it is p

  • Picking up default value 140000 for Recon account in FD02

    Hello Experts, I am an Abaper posting this query because FICO consultant is facing an issue on FD02 with Recon account To the company code CAP1 there are 2 Recon account configured 1) 20000 2) 50000. Now when we change the customer on FD02 or XD02 it

  • Periodic Billing: Invoicing with VF01 vs VF04

    Hello, I have created a basic billing plan for a rental contract. The contract is for 12 months (01.01.-31.12.2011) Billing date is at month end. Billing plan type is 02 = periodic and does NOT have a billing block assigned to it. Now I would like to

  • Creating Boot Environment for Live Upgrade

    Hello. I'd like to upgrade a Sun Fire 280R system running Solaris 8 to Solaris 10 U4. I'd like to use Live Upgrade to do this. As that's going to be my first LU of a system, I've got some questions. Before I start, I'd like to mention that I have rea