Hot questions for Using Applets in image

Question:

Before I actually get to my question, let me just say that I'm not a fan of Java applets and this is for a project. I understand there are much better ways to do what I want.

Anyway, the question.

I'm creating a tortoise and hare race, where a random number between one and ten is generated. That number will then be used to determine the number of spaces that the tortoise or hare moves (i.e. if the random number is 2, then the hare will move 1 square over). I have to show the hare and tortoise moving along, but the code I'm using doesn't move the pictures anywhere, the simply remain stationary.

Here's my code:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;

    public class experiment extends Applet {


Image tortoise, hare; //create the images
final int tortoiseYPos = 50, hareYPos = 400, square = 20, end = 1256; //create x positions and y positions
int tortoiseXPos = 180, hareXPos = 180;
public void init()
{
    tortoise = getImage(getDocumentBase(), "picresources/tortoise.jpg"); //get the images for the objects
    hare = getImage(getDocumentBase(), "picresources/hare.jpg");

   }

public void paint(Graphics field)
{

    drawField(field); //draw the field

}

public void drawField(Graphics field)
{

    Font f  = new Font("Times New Roman", Font.BOLD, 48);
    field.setFont(f);
    field.drawString("Tortoise", 0, 75);
    field.drawString("Hare", 0, 425);

    //fill alternating black and white rectangles       
    field.setColor(Color.black);
    int x = 180;
    for(int i = 0; i < 50; i++)
    {
        field.fillRect(x, 50, square, 50);
        field.fillRect(x, 400, square, 50);
        x += (square);
    } 


    field.drawImage(tortoise, 180, tortoiseYPos, this);       
    field.drawImage(hare, 180, hareYPos, this);
}

public void drawMoves (Graphics g) {
    while(tortoiseXPos < end && hareXPos < end)
    {
        int move = (int)(Math.random() * 10);
        tortoiseMoves(move);
        delay();
        delay();
        delay();
        hareMoves(move);
        delay();
        delay();
        delay();
        clearCurrent(g);
        delay();
        g.drawImage(tortoise, tortoiseXPos, tortoiseYPos, this);
        g.drawImage(hare, hareXPos, hareYPos, this);

    }
}

public void tortoiseMoves(int move)
{ //Moves for Tortoise, 180 is start, 1200 is finish
    if(move <= 5)
    {
        tortoiseXPos += (3 * square);

    }
    else if(move <= 8)
    {
        tortoiseXPos += square;

    }
    else if(move <= 10)
    {
        tortoiseXPos -= (6 * square);

    }

    if(tortoiseXPos < 180)
    {
        tortoiseXPos = 180;

    }

    if(tortoiseXPos > end)
    {
        tortoiseXPos = end;

    }

}

public void hareMoves(int move)
{ //Moves for Hare, 180 is start, 1200 is finish
    if(move <= 2)
    {
        hareXPos += (9 * square);

    }
    else if(move <= 5)
    {
        hareXPos += (square);

    }
    else if(move <= 6)
    {
        hareXPos -= (12 * square);

    }
    else if(move <= 8)
    {
        hareXPos -= (2 * square);

    }
    else if(move <= 10)
    {

    }

    if(hareXPos < 180)
    {
        hareXPos = 180;

    }

    if(hareXPos > end)
    {
        hareXPos = end;

    }
}

public void clearCurrent( Graphics s )
{
    s.clearRect(tortoiseXPos+1, tortoiseYPos+1, WIDTH-1, HEIGHT-1);
    s.clearRect(hareXPos+1, hareYPos+1, WIDTH-1, HEIGHT-1);
}

public void delay()
{
    try {
        Thread.sleep(1000);                 
    } catch(Exception ex) {

    }
}
    }

Thanks in advance!


Answer:

You are not calling your drawMoves(g) method anywhere. Jut call this method from paint(Graphics field) and it will work. That's only thing is missing.

public void paint(Graphics field)
{
    drawField(field); //draw the field
    drawMoves (field)
}

And your implementation will repaint your objects so over time you will see so many tortoise and hare.

Question:

I am trying to draw about 100 images on the Applet. When i did that I was not able to look at an image as the process was too fast. So I added sleep function so that I can give a pause between transition from one image to another. But that worked abnormally. I could not see any pictures and I think the sleep is getting called again and again. Please help. Here is my code:

public class Test extends Applet
{
public void init()
{

    setSize(1000,1000);


}

public void make(Graphics g,int i)
{


}
public void paint(Graphics g)
{
    int i=0;
    for(i=0;i<100;i++)
    {
        if(i!=65)
        {
            Image img = getImage(getDocumentBase(), "abc"+i+".png");
            g.drawImage(img, 0, 0, this);
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception exception)
            {

            }
        }
    }

}

}

Now you can see I have images from 0 to 99 and I want them on my Applet window and after an image is displayed 1 sec delay should be there. But this is not the case. Please help


Answer:

sleep will freeze the EDT (Event Dispatching Thread). Since Swing is single threaded framework, anything that blocks (like sleep), prevents the EDT from running since paint is called from the context of the EDT. Don't use sleep, use Timer instead.

Another note, it's bad practice to catch an exception and not handling it. This will hide serious unexpected things that might occur in your code, at least print the error message.

Question:

Hi im new to programming and im starting to program with java im creating a program that will paint in the applet and everything seems good.

The thing is i want to save the paint that i have done and i was wondering it is possible to convert that applet or the paint method to png file. If not i was working on that everytime the user paint it will save the coordinates, color and size and save it in txt then i have to create a reader or a display for it.

Is it possible to make an applet to png file ?


Answer:

You can convert an image into a png file by using ImageIO.write(...). Hopefully it should be fairly easy to extract the image from your painting, but this depends on much that has not yet been shown to us. Please show us your pertinent code so that I can improve this answer with concrete code.

Assuming that you're drawing within a JPanel's paintComponent method or an Applet's paint method, then you can instead paint into a BufferedImage, and then use that Image to convert to your png file.

The other issue is writing from the applet itself to the file on the disk, and there may be permission issues with this. Myself, I avoid programming applets like the plague, since they're really not used much any more, and in fact some browsers don't allow use of them.

Question:

I'm currently working on a Project that shows a tortoise vs. hare race in real-time as an Applet. A random number is chosen, and the animals either move forward, backward, or not at all based on that number. My problem is getting the animals to be seen in real-time. It currently displays the images at their starting positions, and says who wins. Any pointers on how to get this done would be great.

my code:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
import java.awt.Font;

public class Project2 extends Applet
{
Image tortoise, hare;
Image scaledTortoise, scaledHare;
final int tortoiseYPos = 50, hareYPos = 400, SQUARE = 20, END = 1200;
int tortoiseXPos = 180, hareXPos = 180;

public void init()
{
    tortoise = getImage(getDocumentBase(), "tortoise.gif");
    hare = getImage(getDocumentBase(), "hare.gif");
    scaledTortoise = tortoise.getScaledInstance(20, 50, Image.SCALE_SMOOTH);
    scaledHare = hare.getScaledInstance(20, 50, Image.SCALE_SMOOTH);
}

public void paint(Graphics field)
{
    drawField(field);
    drawMoves(field);

    field.setFont(new Font("Times New Roman", Font.ITALIC, 72));
    //Display winner when they get to the finish line
    if(tortoiseXPos >= END)
    {
            field.drawString("Tortoise Wins!!", 650, 240);
    }
        else if(hareXPos >= END)
        {
            field.drawString("Hare Wins!!", 650, 240);
    }
}   

public void drawField(Graphics field)
{
    setBackground(Color.green);
    Font f  = new Font("Times New Roman", Font.BOLD, 48);
    field.setFont(f);
    field.drawString("Tortoise", 0, 75);
    field.drawString("Hare", 0, 425);

    //fill alternating black and white rectangles       
    field.setColor(Color.black);
    int x = 180;
    for(int i = 0; i < 50; i++)
    {
        field.fillRect(x, 50, SQUARE, 50);
        field.fillRect(x, 400, SQUARE, 50);
        x += (SQUARE);
    } 


    field.drawImage(scaledTortoise, 180, tortoiseYPos, this);       
    field.drawImage(scaledHare, 180, hareYPos, this);
}

public void drawMoves(Graphics s)
{ 
    while(tortoiseXPos < END && hareXPos < END)
    {
        int move = (int)(Math.random() * 10);
        tortoiseMoves(move); hareMoves(move);
        s.drawImage(scaledTortoise, tortoiseXPos, tortoiseYPos, this);
        s.drawImage(scaledHare, hareXPos, hareYPos, this);
        delay(); delay(); delay();
    }
}
public void tortoiseMoves(int move)
{ //Moves for Tortoise, 180 is start, 1200 is finish
    if(move <= 5)
    {
        tortoiseXPos += (3 * SQUARE);
    }
    else if(move <= 8)
    {
        tortoiseXPos += SQUARE;
    }
    else if(move <= 10)
    {
        tortoiseXPos -= (6 * SQUARE);
    }

    if(tortoiseXPos < 180)
    {
        tortoiseXPos = 180;
    }

    if(tortoiseXPos > END)
    {
        tortoiseXPos = END;
    }

}

public void hareMoves(int move)
{ //Moves for Hare, 180 is start, 1200 is finish
    if(move <= 2)
    {
        hareXPos += (9 * SQUARE);
    }
    else if(move <= 5)
    {
        hareXPos += (SQUARE);
    }
    else if(move <= 6)
    {
        hareXPos -= (12 * SQUARE);
    }
    else if(move <= 8)
    {
        hareXPos -= (2 * SQUARE);
    }
    else if(move <= 10)
    {
        hareXPos = hareXPos;
    }

    if(hareXPos < 180)
    {
        hareXPos = 180;
    }

    if(hareXPos > END)
    {
        hareXPos = END;
    }
}

public void delay()
{
    for(int i = 0; i <= 90000000; i++)
    {
    }
}
}

I should note that I am not familiar with and should not be using java swing, as I am only supposed to be using awt.


Answer:

The problem is with your delay function. Entering a loop keeps the applet running your code and it does not get a chance to render the display between moves. If you allow the Thread that your applet is running in to sleep, then that gives it a chance to display as it runs.

public void delay()
{
    try {
        Thread.sleep(100);
    } catch (Exception e) {}
}

Question:

The problem is that when I press the down button, the image (blueboy) disappears, and it also doesn't move up but it can move side to side, I cant understand why? please help. (I'm using RealJ). If there is a website that can help me on 2d side scrolling games that would help me as well.

import java.applet.Applet;
import java.awt.event.*;     
import java.awt.*;  
public class projectblue extends Applet implements     ActionListener,KeyListener,MouseListener {

Image blueboy,trees;    //image variable
int size = 4,jump = 50, cx = 1, cy = 1;    

public void init() {

   blueboy = getImage(getDocumentBase(),"png.png"); 
   trees=     getImage(getDocumentBase(),"background.jpg");
addKeyListener( this ); 
addMouseListener( this );
}

public void paint(Graphics g)
{   
  int width = trees.getWidth(this);     
  int height = trees.getHeight(this);   
  //System.out.println("" + cx +","+ cy);   

  //The later images are drawn on top of the earlier ones.
  g.drawImage(trees, 1 ,1, width*size,height*7,this);
  g.drawImage(blueboy, cx, cy, this);
}

 public void actionPerformed(ActionEvent e) {
 repaint();

}
 public void left(){
      cx = cx -100;
      // blueboy moves left
}

public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
 System.out.println("key pressed");
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_LEFT) {
        left();
    }

    if (key == KeyEvent.VK_RIGHT) {
        cx = cx + 100;
        //blueboy moves right
    }

    if (key == KeyEvent.VK_UP) {
        while (cy >= 0 && cy <=1000)
        cy = cy - 100;
            if (cy < 0){
                cy = 1;
               //blueboy moves up, but if it goes out of bounds it goes back to the top
               }
    }

    if (key == KeyEvent.VK_DOWN) {
       while (cy >= 0 && cy <=1000)
        cy = cy + 100;
            if (cy > 1001){
                cy = 999;
               }
        //blueboy moves down, but if it goes out of bounds it goes back to the bottim
    }
    repaint();
}

public void keyReleased(KeyEvent e) {
}

public void mouseEntered( MouseEvent e ) { } 
public void mouseExited( MouseEvent e ) { }
 public void mousePressed( MouseEvent e ) { }
  public void mouseReleased( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) {
   int x = getX();
   int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
} }

Answer:

Those while loops will tie up your GUI thread, rendering your animation useless. Shouldn't they be if blocks instead? Also, you should enclose all blocks in curly braces. Your indentation is lying to you, and the braces will show you why.

Also you will need to call your super.paint(g) method in your paint override.

Also, is this an assignment, and if so are you required to code with AWT/Applets and not Swing?

Question:

I am working with a Java to create a small applet. I am interested if there is a way I can "scan" an image to get the color values of a certain pixel. I would prefer to not have to display the image on the screen, but if you find that is the only way, please tell me. I would ideally like to be able to have my applet scan an image file and create an image on the screen according to the image. Please try to keep the answers a little bit simple, as I am still getting used to all of the technical terms.

Thanks, ~Rane

What I have so far:

import java.applet.Applet;

public class LoadGuideImage {

Applet applet;

public LoadGuideImage(Applet applet){
    this.applet = applet;
}

public String getPixelColor(String pathToImage, int Xpix, int Ypix){
    int redC = 0;
    int greenC = 0;
    int blueC = 0;

    //Get Pixel colors here and save to ints

    return redC + " " + greenC + " " + blueC;
}

}

Are you suggesting something like this 'the other guy'?:

        BufferedImage img = (BufferedImage) getImage(pathToImage);

    System.out.println("Color: " + img.getRGB(3, 3));

getImage method:

    public Image getImage(String path) {

    Image img;
    URL url = null;

    try {
        url = applet.getDocumentBase();
    } catch (Exception e){
        // TODO: handle exception
    }
    img = applet.getImage(url, path);

    return img;
}

Answer:

nice name by the way. So I was in the same position a while ago.

use this for your get image method, just tweak it and use it to benefit you:

public class ImageLoader {

    public BufferedImage load(String path){
        try {
            return ImageIO.read(getClass().getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

I have a been making a game that uses individual pixels to load those pixels and then put tiles where certain pixels are located in the map. If you would like to take my code snippet from there let me know and ill hook you up :P

Question:

I am trying to bounce a ball image between the boundaries of my window. However when the ball gets to the top boundary it does not bounce back. I hope some can help me solve this issue.

Here is my code:

    import java.awt.*;
    import java.applet.*;
    public class Ball {
    private int x=355 ;
    private int y=500;
    private int xVel = -3;
    private int yVel = 3;

    private Image ball;

    public Ball (Breakout bR){

        ball = bR.getImage(bR.getDocumentBase(),"ball.png");


    }
    public void update(Breakout bR){
       x += xVel;
       y += yVel;
       if (x < 0){
           xVel = 3;
        }
       else if (x > bR.getWidth()){
            xVel = -3;
        }
       if(y > bR.getHeight()){
           yVel = -3;
        }
       else if (y < 0){
            xVel = 3;
        }
    }

    public void paint (Graphics g, Breakout bR){
        g.drawImage(ball,x,y,bR);

    }
}

Thanks for your help :)   

Answer:

You have a typo in your last else-if... It should read

   else if (y < 0){
        yVel = 3;
    }

Question:

I'm trying to code where an image can be dragged using the mouseDragged method, but I can't seem to successfully do it with my current code. My aim is to ensure that when I place drag on every image in the applet, it follows the cursor.

/* Using drag mouseEvent, all objects in the app can be dragged...
 */
package finals_two;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* 10/16/2015
 * @author michael.pabilona
 */
public class Finals_Two extends Applet implements MouseMotionListener
{
    int hei, wid, xCoordinate, yCoordinate;
    Image leftReceiver1, leftReceiver2, leftReceiver3;
    Image rightReceiver1, rightReceiver2, rightReceiver3;    
    Image leftSpiker, rightSpiker, center, setter;

    public void init()
    {
        hei = getSize().height;
        wid = getSize().width;
        xCoordinate = hei;
        yCoordinate = wid;
        addMouseMotionListener(this);
    }

    public void mouseDragged(MouseEvent e)
    {
        xCoordinate = e.getX();
        yCoordinate = e.getY();
        repaint();
    }

    public void paint(Graphics gr)
    {
        setBackground(Color.white);
        gr.setColor(Color.black);
        //court bound top line
        gr.drawLine(400, 130, 1200, 130);
        //court bound bottom line
        gr.drawLine(200, 530, 1000, 530);
        //court bound left line
        gr.drawLine(400, 130, 200, 530);
        //court bound right line
        gr.drawLine(1000, 530, 1200, 130);
        //net
        gr.drawLine(800, 130, 600, 530);
        gr.drawLine(800, 130, 800, 0);
        gr.drawLine(600, 530, 600, 400);
        //net horizontal lines
        gr.drawLine(800, 0, 600, 400);
        gr.drawLine(800, 10, 600, 410);
        gr.drawLine(800, 20, 600, 420);
        gr.drawLine(800, 30, 600, 430);
        gr.drawLine(800, 40, 600, 440);
        gr.drawLine(800, 50, 600, 450);
        gr.drawLine(800, 60, 600, 460);
        gr.drawLine(800, 70, 600, 470);
        gr.drawLine(800, 80, 600, 480);
        //net vertical lines
        gr.drawLine(795, 5, 795, 90);
        gr.drawLine(790, 20, 790, 100);
        gr.drawLine(785, 30, 785, 110);
        gr.drawLine(780, 40, 780, 120);
        gr.drawLine(775, 50, 775, 130);
        gr.drawLine(770, 60, 770, 140);
        gr.drawLine(765, 70, 765, 150);
        gr.drawLine(760, 80, 760, 160);
        gr.drawLine(755, 90, 755, 170);
        gr.drawLine(750, 100, 750, 180);
        gr.drawLine(745, 110, 745, 190);
        gr.drawLine(740, 120, 740, 200);
        gr.drawLine(735, 130, 735, 210);
        gr.drawLine(730, 140, 730, 220);
        gr.drawLine(725, 150, 725, 230);
        gr.drawLine(720, 160, 720, 240);
        gr.drawLine(715, 170, 715, 250);
        gr.drawLine(710, 180, 710, 260);
        gr.drawLine(705, 190, 705, 270);
        gr.drawLine(700, 200, 700, 280);
        gr.drawLine(695, 210, 695, 290);
        gr.drawLine(690, 220, 690, 300);
        gr.drawLine(685, 230, 685, 310);
        gr.drawLine(680, 240, 680, 320);
        gr.drawLine(675, 250, 675, 330);
        gr.drawLine(670, 260, 670, 340);
        gr.drawLine(665, 270, 665, 350);
        gr.drawLine(660, 280, 660, 360);
        gr.drawLine(655, 290, 655, 370);
        gr.drawLine(650, 300, 650, 380);
        gr.drawLine(645, 310, 645, 390);
        gr.drawLine(640, 320, 640, 400);
        gr.drawLine(635, 330, 635, 410);
        gr.drawLine(630, 340, 630, 420);
        gr.drawLine(625, 350, 625, 430);
        gr.drawLine(620, 360, 620, 440);
        gr.drawLine(615, 370, 615, 450);
        gr.drawLine(610, 380, 610, 460);
        gr.drawLine(605, 390, 605, 470);
        gr.drawLine(600, 390, 600, 480);
        //left mid line
        gr.drawLine(625, 130, 425, 530);
        //right mid line
        gr.drawLine(975, 130, 775, 530);
        //left backend receivers
        leftReceiver1 = getImage(getDocumentBase(),"receiver.jpg");
        gr.drawImage(leftReceiver1, 400, 100, 90, 90, this);
        leftReceiver2 = getImage(getDocumentBase(),"receiver.jpg");
        gr.drawImage(leftReceiver2, 325, 250, 90, 90, this);
        leftReceiver3 = getImage(getDocumentBase(),"server1.jpg");
        gr.drawImage(leftReceiver3, 75, 375, 150, 150, this);      
        //right backend receivers
        rightReceiver1 = getImage(getDocumentBase(),"receiver1.jpg");
        gr.drawImage(rightReceiver1, 1000, 100, 100, 100, this);
        rightReceiver2 = getImage(getDocumentBase(),"receiver1.jpg");
        gr.drawImage(rightReceiver2, 950, 250, 100, 100, this);
        rightReceiver3 = getImage(getDocumentBase(),"receiver1.jpg");
        gr.drawImage(rightReceiver3, 900, 400, 100, 100, this);
        //left front liners
        leftSpiker = getImage(getDocumentBase(),"spiker.jpg");
        gr.drawImage(leftSpiker, 650, 30, 100, 100, this);
        center = getImage(getDocumentBase(),"spiker.jpg");
        gr.drawImage(center,600,150,100,100,this);
        setter = getImage(getDocumentBase(),"setter.jpg");
        gr.drawImage(setter, 500, 300, 150, 150, this);
        //right front liners
        rightSpiker = getImage(getDocumentBase(),"spiker1.jpg");
        gr.drawImage(rightSpiker,650,350,130,130,this);
        center = getImage(getDocumentBase(),"server.jpg");
        gr.drawImage(center,750,150,130,130,this);        
        setter = getImage(getDocumentBase(),"defense1.jpg");
        gr.drawImage(setter,850,90,110,110,this);
    }


    @Override
    public void mouseMoved(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }


}

This is my current code. Can someone direct me what I am missing or what I did wrong here?


Answer:

In order to drag anything, you need to know a few things. You need to know where they are and the space the occupy.

Once you know that, you can monitor the mouseDragged event and update their location.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DragMe {

    public static void main(String[] args) {
        new DragMe();
    }

    public DragMe() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Map<Image, Point> locations;

        public TestPane() {
            locations = new HashMap<>(25);
            try {
                locations.put(ImageIO.read(getClass().getResource("/Pony.png")), new Point(0, 0));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            MouseAdapter ma = new MouseAdapter() {

                private Image dragImage;
                private Point clickOffset;

                @Override
                public void mousePressed(MouseEvent e) {
                    for (Map.Entry<Image, Point> entry : locations.entrySet()) {
                        Image image = entry.getKey();
                        Point point = entry.getValue();
                        Rectangle bounds = new Rectangle(
                                        point.x, point.y,
                                        image.getWidth(TestPane.this), image.getHeight(TestPane.this));
                        if (bounds.contains(e.getPoint())) {
                            dragImage = image;
                            clickOffset = new Point(point.x - e.getPoint().x, point.y - e.getPoint().y);
                            break;
                        }
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    dragImage = null;
                    clickOffset = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (dragImage != null) {
                        Point dragPoint = new Point(e.getPoint());
                        dragPoint.x += clickOffset.x;
                        dragPoint.y += clickOffset.y;

                        locations.put(dragImage, dragPoint);
                        repaint();
                    }
                }

            };

            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Map.Entry<Image, Point> entry : locations.entrySet()) {
                Point point = entry.getValue();
                g2d.drawImage(entry.getKey(), point.x, point.y, this);
            }
            g2d.dispose();
        }

    }

}

Question:

I'm working on this project in Java and need an image to display, along with a bio, and button that plays a song/sound. I finished the button and bio but I can figure out how to get the image to display in the NORTH part of the layout along with the button in the center part, any help would be great.

This is my error: The method add(String, Component) in the type Container is not applicable for the arguments (Image, String)

public void init() {
    // image
    myPicture = getImage(getCodeBase(), "sample.jpg");
    // THIS IS WHERE MY PROBLEM IS vvvvvvv      
    add(myPicture, BorderLayout.NORTH);

    add(bio);

    paneSouth.add(play);
    getContentPane().add(paneSouth, BorderLayout.SOUTH);
    mySound = getAudioClip(getDocumentBase(), "sample.wav");
    play.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mySound.play();
        }});    
}

public void paint(Graphics g){
    g.drawImage(myPicture, 10, 10, this);
}

private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio thing");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;

}

EDIT:

public void init() {
    // image
    ImageIcon icon = new ImageIcon(myPicture);
    JLabel myLabelImage = new Image(icon);
    add(myLabelImage, BorderLayout.NORTH);

    // bio
    add(bio);
    add(bio, BorderLayout.CENTER);

    // sound
    paneSouth.add(play);
    getContentPane().add(paneSouth, BorderLayout.SOUTH);
    mySound = getAudioClip(getDocumentBase(), "sample.wav");
    play.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mySound.play();
        }});    
}

private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio.");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}

Answer:

I guess you are using JApplet because you are using Swing components. Try something like this:

public class ImageApplet extends JApplet {

    private JPanel paneSouth = new JPanel();
    private JTextArea bio = new JTextArea("bio thing");
    private JButton play = new JButton("Play");
    private Image myPicture;
    private ImageIcon icon;
    private JLabel label;

    public void init() {
        try {
            URL pic = new URL(getDocumentBase(), "sample.jpg");
            myPicture = ImageIO.read(pic);
            icon = new ImageIcon(myPicture);
            label = new JLabel(icon);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // add image
        add(label, BorderLayout.NORTH);
        // bio
        add(bio, BorderLayout.CENTER);
        // sound
        paneSouth.add(play);
        add(paneSouth, BorderLayout.SOUTH);

        // here add your sound declaration and button event...
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }
}

And try change your TextArea for a JTextArea since you are only using swing components.

Question:

I watched a tutorial on YouTube on how to display an image in Java, and he used something called "Applet" and "Graphics" to display it, I've got it to work, and I am happy with it. Now what I was planning to make is a chrome logo in the center of my screen, transparent with no background, and then chrome opens. I've called the class CustomChrome cus you know. Custom and stuff. I just want a cool opening whenever I start chrome.

Here is the current code:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

public class CustomChrome extends Applet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Image logo = null;

    public void paint(Graphics g) {

        this.setSize(960, 540);

        if (logo == null)
            logo = getImage("/chromelgo.png");

        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(logo, 0, 0, 960, 540, this);
    }

    public Image getImage(String path) {

        Image tempImage = null;
        try {

            URL imageURL = CustomChrome.class.getResource(path);
            tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
        } catch (Exception e) {

            System.out.println("An error occured - " + e.getMessage());

        }

        return tempImage;
    }


}

What I want to do, however, is the make the background + the window to vanish, Once that's was done I will set the image and window size to 1920x1080. How do I go forward on making the window behind the image disappear? I've heard something about implementing ActionListener, but still I ain't sure what to do.

Keep in mind! I have no experience with java so sorry for upsetting you if you try to help me :P


Answer:

Okay, let's start with the really obvious issue, applets are effectively deprecated and you should stop using them, see Java Plugin support deprecated and Moving to a Plugin-Free Web for more details.

paintXxx is for painting, you should never change the state of a component from within a paint method (and you should not be calling setSize in an applet anyway). See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works and how you can make use of it

As a general piece of advice, I'd recommend ImageIO.read over Toolkit#getImage or ImageIcon for loading images, apart from throwing an Exception when the image can't be read (instead of failing silently), it's also a blocking call, meaning that when it returns, the image is fully loaded.

See Reading/Loading an Image for more details

A word of warning - What you're trying to do is not difficult per se, but it's involved and requires a certain amount of knowledge about how the API works.

Now what I was planning to make is a chrome logo in the center of my screen, transparent with no background, and then chrome opens.

Okay, well, this was never going to work with applets, as applets are intended to be displayed inside a browser, so you can't control the window, instead, you need something like a JFrame, see How to Make Frames (Main Windows)

What I want to do, however, is the make the background + the window to vanish, Once that's was done I will set the image and window size to 1920x1080. How do I go forward on making the window behind the image disappear?

Now, this is where the real fun begins. You're going to want to start by having a look at How to Create Translucent and Shaped Windows. This will allow you control the opacity of the frame, making it disappear, but allowing the content to remain, there are some tricks you need to do to pull it off, but that's the basic idea

So, this example will make a transparent window and display and image centered within it.

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage img = ImageIO.read(getClass().getResource("/Chrome.png"));
                    ImageIcon icon= new ImageIcon(img);
                    JLabel label = new JLabel(icon);

                    JFrame frame = new JFrame("Testing");
                    frame.setUndecorated(true);
                    frame.setBackground(new Color(0, 0, 0, 0));
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}

In this is example, I make use of a JLabel to display the image, in most cases, it's all you really need, see How to Use Labels for more details.

What I want to do, however, is the make the background + the window to vanish

Well, it just comes down to what you mean by vanish. You could just all dispose or setVisible on the window, which would close it, all you could use some animation to make it fade away ... and because I like animation...

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage img = ImageIO.read(getClass().getResource("/Chrome.png"));
                    ImageIcon icon = new ImageIcon(img);
                    JLabel label = new JLabel(icon);

                    JFrame frame = new JFrame("Testing");
                    frame.setUndecorated(true);
                    frame.setBackground(new Color(0, 0, 0, 0));
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                    Timer timer = new Timer(40, new ActionListener() {
                        float opacity = 1.0f;
                        float delta = 0.05f;

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            opacity -= delta;
                            if (opacity < 0.0f) {
                                opacity = 0.0f;
                                ((Timer)(e.getSource())).stop();
                                frame.dispose();
                            }
                            frame.setOpacity(opacity);
                        }
                    });
                    timer.setInitialDelay(2000);
                    timer.start();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}

Okay, there is a lot going on here, you'll want to have a read through Concurrency in Swing and How to use Swing Timers for more details, needless to say, it's a little complicated to get started with.

Basically, all this does is, waits 2 seconds and then every 40 milliseconds, decreases the frames opacity by a factor or 0.05 till it reaches 0 and it then disposes of the window.

Now, I might use a mixture of these techniques, for example, I might show the logo frame (maybe set to display on top), I would then show the main frame and then trigger the logo frame to fade out. This could be done from a controller class to simplify the code, but, that's up to you.

A would also suggest having a look at Creating a GUI With JFC/Swing

Question:

How would I go and add an image on the mouse coordinates when the mouse clicks? I have looked at this :Adding Images on Mouse Click to JPanel

But I don't understand it and am trying to add it on mouse click in an applet

And please don't say, "Learn some basic java first! and provide me with a link to some oracle docs", I just can't get any info from those things.

Code:

> `import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
`import java.net.URL;

import javax.imageio.ImageIO;

public class SHR extends Applet implements MouseListener{

    int a;
    int b;

    @Override
    public void mouseClicked(MouseEvent e) {
        a = e.getX();
        b = e.getY();

        paint(null, a, b);/this is the part i am having trouble with
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {

    }

    @Override
    public void mouseExited(MouseEvent arg0) {

    }

    @Override
    public void mousePressed(MouseEvent arg0) {

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {

    }

    public void paint(Graphics g, int x, int y){
        BufferedImage photo = null;
          try 
          {
             URL u = new URL(getCodeBase(),"SilverHandRecruit.png");
             photo = ImageIO.read(u);
          }   
          catch (IOException e) 
          {
             g.drawString("Problem reading the file", 100, 100);
          }

          g.drawImage(photo,x, y, 10, 30, null);
    }



}
`

The problem is, I don't know what I am supposed to replace "null" with to get it to work

Thanks


Answer:

Start by taking a look at Painting in AWT and Swing and Performing Custom Painting to understand how painting works in AWT/Swing.

Then, take a look at 2D Graphics for more details about how you can use the Graphics class to paint things with.

This is a really basic example which loads a single image and every time you click on the panel, moves it to that point.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class DrawImage {

    public static void main(String[] args) {
        new DrawImage();
    }

    public DrawImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage image;
        private Point drawPoint;

        public TestPane() {
            try {
                image = ImageIO.read(getClass().getResource("/SmallPony.png"));
                addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        drawPoint = new Point(e.getPoint());
                        repaint();
                    }

                });
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (drawPoint != null) {
                g2d.drawImage(image, drawPoint.x, drawPoint.y, this);
            }
            g2d.dispose();
        }

    }

}

Question:

I am trying to automatically save the graphic content of a Java applet to an image file but I have an issue that the file doesn't save properly. My complete Java code is:

package nl.mark.SierpinskiCarpet;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SierpinskiCarpet extends Applet {
    private Graphics g = null;
    private int d0 = 729; // 3^6
    private BufferedImage bufferedImage;
    private final GraphicsConfiguration gConfig = GraphicsEnvironment
            .getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();

    public void init() {
        g = getGraphics();
        resize(d0, d0);
    }

    public void paint(Graphics g) {
        drawSierpinskiCarpet(0, 0, getWidth(), getHeight());
        storeImage();
    }

    public void storeImage() {
        BufferedImage image = create(d0, d0, true);
        Graphics2D g = image.createGraphics();
        // you can disable this if you don't want smooth graphics
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        drawSierpinskiCarpet(0, 0, getWidth(), getHeight());
        g.dispose();
        try {
            ImageIO.write(image, "png", new File(
                    "N:\\Tapijt van SierpiƄski\\image.png"));
        } catch (IOException e) {
        }
    }

    private void drawSierpinskiCarpet(int xOL, int yOL, int breedte, int hoogte) {
        if (breedte > 2 && hoogte > 2) {
            int b = breedte / 3;
            int h = hoogte / 3;
            g.fillRect(xOL + b, yOL + h, b, h);
            for (int k = 0; k < 9; k++)
                if (k != 4) {
                    int i = k / 3;
                    int j = k % 3;
                    drawSierpinskiCarpet(xOL + i * b, yOL + j * h, b, h);
                }
        }
    }

    private BufferedImage create(final int width, final int height,
            final boolean alpha) {
        BufferedImage buffer = gConfig.createCompatibleImage(width, height,
                alpha ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
        return buffer;
    }
}

The image (Sierpinski Carpet) that is shown in the applet is correct but the file that was created is a blank image only. To draw the pattern, the method drawSierpinskiCarpet() is called and after executing the function, the function storeImage() is called to save the image but results in blank image file in the output directory. Whats going wrong during saving of the image?


Answer:

You should NEVER call getGraphics on a component (and NEVER store a Graphics object that was given as a parameter to paint or so).

(And you should never silently swallow an IOException. At least add some e.printStackTrace() to know when something goes wrong).

The problem here is that you obtained the Graphics object from the image, but the call to drawSierpinskiCarpet still used the Graphics g that was stored as a field in the class.

In this case, one easy solution is to pass the Graphics object as a parameter through the recursive calls:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SierpinskiCarpet extends Applet
{
    private int d0 = 729; // 3^6
    private BufferedImage bufferedImage;
    private final GraphicsConfiguration gConfig = GraphicsEnvironment
        .getLocalGraphicsEnvironment().getDefaultScreenDevice()
        .getDefaultConfiguration();

    public void init()
    {
        resize(d0, d0);
    }

    public void paint(Graphics g)
    {
        drawSierpinskiCarpet(g, 0, 0, getWidth(), getHeight());
        storeImage();
    }

    public void storeImage()
    {
        BufferedImage image = create(d0, d0, true);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        drawSierpinskiCarpet(g, 0, 0, getWidth(), getHeight());
        g.dispose();
        try
        {
            ImageIO.write(image, "png", new File(
                "C:\\Users\\User\\Desktop\\sierpinskiImage.png"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void drawSierpinskiCarpet(Graphics g, int xOL, int yOL,
        int breedte, int hoogte)
    {
        if (breedte > 2 && hoogte > 2)
        {
            int b = breedte / 3;
            int h = hoogte / 3;
            g.fillRect(xOL + b, yOL + h, b, h);
            for (int k = 0; k < 9; k++)
                if (k != 4)
                {
                    int i = k / 3;
                    int j = k % 3;
                    drawSierpinskiCarpet(g, xOL + i * b, yOL + j * h, b, h);
                }
        }
    }

    private BufferedImage create(final int width, final int height,
        final boolean alpha)
    {
        BufferedImage buffer =
            gConfig.createCompatibleImage(width, height, alpha
                ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
        return buffer;
    }
}

Question:

This is the code I used for displaying an image in applet.The applet is working, but not displaying the image.The image is present in the src folder.

import java.awt.*;  
import java.applet.*;  


public class DisplayImage extends Applet {  

Image picture;  

public void init() {  
 picture = getImage(getDocumentBase(),"IMG-20160319-WA0003.jpg");  
}  

public void paint(Graphics g) {  
 g.drawImage(picture, 30,30, this);  
}  

} 

The HTML code:

     <html> 
       <HEAD>
   </HEAD>
<body>  
<applet code="DisplayImage.class" width="300" height="300">  
</applet>  
</body>  
</html>  

Answer:

Make sure that the image is in the same folder as the .class file, and not the .java file, as the .class file is the one that is being executed.

A better solution still would be to create a jar containing the code and the image. The base folder of the jar I created looks as follows:

Within the applet folder you can find the .class files. Put the jar file in the same folder as you html file. You then have to adapt your .html file:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <applet archive="applet.jar" code="applet.DisplayImage.class" width="300" height="300">  
        </applet> 
    </body>
</html>

Question:

I have been struggling with this for a while and did not find a solution. I am trying to display a tooltip (a rectangular box with different color which contains some text) when user hovers the mouse over specific markers displayed in side a PGraphics object. It is programmed in java and run as a java applet using the PApplet class.

The problem is that, text is not seen clearly as not all of it stays on top of other images. Although the color is changed and preserved to the color of the tooltip, the edges of other markers still stay on top.

here is part of the code to explain better what I am trying to do:

// Common piece of drawing method for markers; 
    // Note that you should implement this by making calls 
    // drawMarker and showTitle, which are abstract methods 
    // implemented in subclasses
    public void draw(PGraphics pg, float x, float y) {
        // For starter code just drawMaker(...)
        if (!hidden) {

            drawMarker(pg, x, y);

            if (selected) {
                showTitle(pg, x, y);  // You will implement this in the subclasses
            }

        }
    }

@Override
    public void drawMarker(PGraphics pg, float x, float y) {
        // TODO Auto-generated method stub
        pg.pushStyle();

        // IMPLEMENT: drawing triangle for each city
        pg.fill(150, 30, 30);
        pg.triangle(x, y-TRI_SIZE, x-TRI_SIZE, y+TRI_SIZE, x+TRI_SIZE, y+TRI_SIZE);

        // Restore previous drawing style
        pg.popStyle();
    }

public void showTitle(PGraphics pg, float x, float y)
    {
        // TODO: Implement this method
        pg.pushStyle();

        pg.fill(255, 255, 202);
        pg.rect(x+TRI_SIZE+1, y-TRI_SIZE, 150, 15);
        pg.textAlign(PConstants.LEFT, PConstants.CENTER);
        pg.fill(0,0,0);
        pg.text(getCity()+", " + getCountry() + ", " + getPopulation(), x+TRI_SIZE+2, y);

        // Restore previous drawing style
        pg.popStyle();
    }

Is it possible to remove the edges of some markers to not be displayed or another way to insure that the tooltip always stays on top? Thanks in advance


Answer:

Well, I already found a solution. What you have to do is to display (draw) the text (tooltip) only after every other image/object is displayed (drawn). This will make the text always stay on stop and appear clearly without problem. To Do This, You have to it in the main class in the draw method as in this ex:

public void draw() {
        background(0);
        map.draw();
        addKey();

        if (lastSelected != null)
        {
            lastSelected.showToolTip(this,lastSelected.getScreenPosition(map).x,lastSelected.getScreenPosition(map).y);

        }

    } 

Hope other people find this useful.

Question:

I'm in the process of developing a java applet game following a tutorial found here: http://www.kilobolt.com/unit-2-creating-a-game-i.html I'm using this as a foundation to extend my own app. But here is the problem.

I want to add JButtons to the applet for certain features (start, options etc). But I found them to be flickering when i hover over them and completely hidden if left untouched. I read that it has to do with double buffering and that I should use the paintComponent rather than paint eg

public void paintComponents(Graphics g) {
    super.paintComponents(g);
}

That solves the Jbuttons from flickering but then the g.drawimage methods are broke or I don't understand it fully, as the images I'm trying to draw are not showing. I don't know if they are hidden or can't be load or what. If someone could please point to the right direction that would be great.

public class StartingClass extends Applet implements Runnable, KeyListener, ActionListener {

    private PlayerChar playerChar;
    private Image image, currentSprite, character, characterDown, characterJumped, background;
    private Graphics second;
    private URL base;
    private static Background bg1, bg2;
    private JButton start, options;
    private boolean running = false;
    private int score;

    @Override
    public void init() {

        setSize(800, 480);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("GraviOn-Alpha");
        try {
            base = getDocumentBase();

        }
        catch (Exception e) {
            // TODO: handle exception
        }

        // Image Setups
        character = getImage(base, "data/character.png");
        characterDown = getImage(base, "data/down.png");
        characterJumped = getImage(base, "data/jumped.png");
        currentSprite = character;
        background = getImage(base, "data/background.png");

        score = 0;
    }

    @Override
    public void start() {

        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        playerChar = new PlayerChar();

        JPanel myPanel = new JPanel();
        start = new JButton("Start");
        start.addActionListener(this);
        options = new JButton("Change Colour");
        options.addActionListener(this);
        myPanel.add(start);
        myPanel.add(options);
        myPanel.setBackground(Color.BLACK);
        myPanel.setPreferredSize(new Dimension(100, 75));
        this.add(myPanel);

        Thread thread = new Thread(this);
        thread.start();

    }

    @Override
    public void stop() {
        // TODO Auto-generated method stub
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void run() {
        while (true) {
            if (running == true) {
                playerChar.moveRight();
                score += 3;
                start.setVisible(false);
                options.setVisible(false);
            }
            else {

            }
            playerChar.update();
            if (playerChar.isJumped()) {
                currentSprite = characterJumped;
            }
            else if (playerChar.isJumped() == false && playerChar.isDucked() == false) {
                currentSprite = character;
            }

            bg1.update();
            bg2.update();
            repaint();

            try {
                Thread.sleep(17);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            second = image.getGraphics();
        }

        second.setColor(getBackground());
        second.fillRect(0, 0, getWidth(), getHeight());
        second.setColor(getForeground());
        paint(second);

        g.drawImage(image, 0, 0, this);

    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
        g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
        g.drawImage(currentSprite, playerChar.getCenterX() - 61, playerChar.getCenterY() - 63, this);
        g.drawString("Score: " + score, 50, 50);

    }

    @Override
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                System.out.println("Move up");
                break;

            case KeyEvent.VK_DOWN:
                currentSprite = characterDown;
                if (playerChar.isJumped() == false) {
                    playerChar.setDucked(true);
                    playerChar.setSpeedX(0);
                }
                break;

            case KeyEvent.VK_LEFT:
                // playerChar.moveLeft();
                playerChar.setMovingLeft(true);
                break;

            case KeyEvent.VK_RIGHT:
                // playerChar.moveRight();
                playerChar.setMovingRight(true);
                break;

            case KeyEvent.VK_SPACE:
                playerChar.jump();
                break;

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP:
                System.out.println("Stop moving up");
                break;

            case KeyEvent.VK_DOWN:
                currentSprite = character;
                playerChar.setDucked(false);
                break;

            case KeyEvent.VK_LEFT:
                playerChar.stopLeft();
                break;

            case KeyEvent.VK_RIGHT:
                playerChar.stopRight();
                break;

            case KeyEvent.VK_SPACE:
                break;

        }

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    public static Background getBg1() {
        return bg1;
    }

    public static Background getBg2() {
        return bg2;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Start")) {
            running = true;

        }
        if (e.getActionCommand().equals("Change Colour") && character == getImage(base, "data/character.png")) {

            character = getImage(base, "data/character2.png");
        }
        else if (e.getActionCommand().equals("Change Colour") && character == getImage(base, "data/character2.png")) {

            character = getImage(base, "data/character.png");
        }
        repaint();
    }
}

This is with trying to utilize the paintComponents method. I would greatly appreciate help.

EDIT: I have changed to using Japplet and used paintComponent in a Jpanel to draw everything and it worked fine, all based on JApplet - super.paint(); causes flicker.


Answer:

I have changed to using Japplet and used paintComponent in a Jpanel to draw everything and it worked fine.

JPanel myPanel = new JPanel(){

        @Override    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
            g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
            g.drawImage(currentSprite, playerChar.getCenterX() - 61, playerChar.getCenterY() - 63, this);
            g.drawString("Score: " + score, 50, 50);


    }

Question:

I want to move an Image ( here is rectangle ) in applet, applet draws it, but I wonder why the image is not moving? there is no compile error!

here is my code:

package game;

import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;



public class Gamer extends JApplet implements KeyListener
{
    private int x=50,y=50;


@Override
public void init(  )
{
    addKeyListener(this);
}

@Override
public void keyPressed(KeyEvent e)
{
    int keyCode = e.getKeyCode();

    switch( keyCode )
    {
    case KeyEvent.VK_UP:
        if( y>0 )  //when up key is pressed and the position of the player is not on the edge
        {
            y=y-19;
            repaint();
        }
        break;
    case KeyEvent.VK_DOWN:
        if( y<171 ) //when down key is pressed and the position of the player is not on the edge
        {
            y=y+19;
            repaint();
        }
        break;
    case KeyEvent.VK_LEFT:
        if( x>0 )
        {
            x=x-15;
            repaint();
        }
        break;
    case KeyEvent.VK_RIGHT:
        if( x<285 )
        {
            x=x+15;
            repaint();
        }
        break;
    }
}
@Override
public void paint( Graphics g )  //will draw the background and the character
{
    g.fillRect(x, y, 200, 200);

}

@Override
public void keyReleased(KeyEvent arg0)
{
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent arg0)
{
    // TODO Auto-generated method stub

}
}

When I pressed my up/down/left/write arrow , the rectangle is not moving . Please explain why ? T.I.A.


Answer:

The problem is that your applet doesn't catch the KeyEvent, so your paint method does not get called.

In fact there is an issue when you want to add KeyListener to JApplet and it's not working.

Solution is to implement KeyEventDispatcher instead of KeyListener. Also I changed the size of your rectangle from 200 to 20 in order to be able to see the movements of the rectangle better:

package game;

import java.awt.Graphics;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

import javax.swing.JApplet;

public class Gamer extends JApplet implements KeyEventDispatcher {
    private int x = 50, y = 50;

    @Override
    public void init() {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
    }

    @Override
    public void paint(Graphics g) // will draw the background and the character
    {
        super.paint(g); // <- added to your code to clear the background
                        //         before re-painting the new square

        g.fillRect(x, y, 20, 20);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        int keyCode = e.getKeyCode();

        switch( keyCode )
        {
        case KeyEvent.VK_UP:
            if( y>0 )  //when up key is pressed and the position of the player is not on the edge
            {
                y=y-19;
                repaint();
            }
            break;
        case KeyEvent.VK_DOWN:
            if( y<171 ) //when down key is pressed and the position of the player is not on the edge
            {
                y=y+19;
                repaint();
            }
            break;
        case KeyEvent.VK_LEFT:
            if( x>0 )
            {
                x=x-15;
                repaint();
            }
            break;
        case KeyEvent.VK_RIGHT:
            if( x<285 )
            {
                x=x+15;
                repaint();
            }
            break;
        }
        return false;
    }

}

Hope this would be helpful.

Question:

I have an applet java displaying images from folder ,i cant run this applet using html i have this error :


Answer:

The error you are getting is because your applet is trying to read a file from a directory in the local system where it is getting downloaded. This is a standard security feature. This of this way, you go to a website which downloads an applet and read a file or executes an .exe in your local system. Naturally this should not be allowed for an applet / javascript or code served from a server.

You need to create a signed applet. Please go through the following link to accomplish your need :

http://www.developer.com/java/other/article.php/3303561/Creating-a-Trusted-Applet-with-Local-File-System-Access-Rights.htm