Drawing Multiple Images

Can anyone tell me why the code below will not work inside a for loop? If I tell my image to be drawn outside of a loop statement it works just fine. However, I need it in a loop because I want the picture to be drawn repeatedly twenty times in xPos+40 increments.
public void paint(Graphics g){
                   super.paint(g);
                    for(int i=0;i<20;i++){
                         g.drawImage(dot, xPos, yPos, this);
                         xPos=xPos+40;
             }//close paint

Your code worked fine. Which makes me wonder if perhaps my problem lies outside of the code snipet that I gave. Could you look at this and see you can find any errors?
package dots;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Dots{
     //Variables
     private static DotsPanel dPanel;
     private static Image dot;
     private static Image vLine;
     private static Image hLine;
     private static int xPos;
     private static int yPos;
     private static class DotsPanel extends JPanel{
          public DotsPanel(){
               //call to the parent constructor
            super();
            dot = Toolkit.getDefaultToolkit().getImage("dot.gif");
            vLine = Toolkit.getDefaultToolkit().getImage("vertical.gif");
            hLine = Toolkit.getDefaultToolkit().getImage("horizontal.gif");
            xPos=10;
            yPos=10;
          }//close DotsPanel
             public void paint(Graphics g){
                   super.paint(g);
                    for(int i=0;i<20;i++){
                         g.drawImage(dot, xPos, yPos, this);
                         xPos=xPos+40;
             }//close paint
     }//close DotsPanel
     public static void main(String []args){
             JFrame dFrame = new JFrame("Dots");
                Container cont = dFrame.getContentPane();
                dPanel = new DotsPanel();
                //dPanel.setBackground(Color.black);
                dFrame.setSize(400, 400);
                dFrame.setResizable(false);
                dFrame.setLocationRelativeTo(null);
                dFrame.setDefaultCloseOperation(dFrame.EXIT_ON_CLOSE);
                cont.add(dPanel);
                dFrame.setVisible(true);
     }//close main
}//close Dots

Similar Messages

  • Blackjack drawing multiple images problem

    Hi. Im making a blackjack game and im having some trouble drawing the images.
    The drawing is fine. But the problem is when to draw new cards. I dont know how to draw a new card without the old one dissapearing. I understand why it dissapears as the code is now, but i dont know how to fix it. Somehow i have to make each card beeing able to paint itself on the board? The filenames of the images to be drawn is fetched by the getCard() in the card class. Since blackjack doesnt use that many cards in play at the same time its possible to simply make more image variables and some if statements deciding which to paint, but that sollution isnt very nice, and i want to make more advanced cardgames after this, so if someone could help me with this it would truly be great.
    Thanks.
    Image displaying board after first new card is dealed, and third one
    http://www.wannerskog.com/newcards.jpg
    Card Class
    public class Card {
         private int value;
         private String color;
         public Card(String incolor,int invalue) {
              value = invalue;
              color = incolor;
         public String getCard() {
              return value+color;
         public int getValue() {
              return value;
    Deck
    import java.util.*;
    //Creates a deck of cards
    public class Deck {
         Card card;
         private Set deck = new HashSet();
         List deck2;
         public void createDeck() {
              for(int i=2; i<=14; i++) {
                   card = new Card("s",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("h",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("c",i);
                   deck.add(card);
              for(int i=2; i<=14; i++) {
                   card = new Card("d",i);
                   deck.add(card);
              deck2 = new Vector(deck);
         public void shuffleDeck() {
              Collections.shuffle(deck2);
         public List getDeck() {
              return deck2;
    Dealer Class
    import java.util.*;
    public class Deal {
         Deck deck = new Deck();
         private String card1;
         private String card2;
         public Deal() {
              deck.createDeck();
              deck.shuffleDeck();
         public void dealCards(int j) {
              deck.shuffleDeck();
              List d = (List)deck.getDeck();
              Card card;
              Iterator it = d.iterator();
              String card1 = "";
              String card2 = "";
              for(int i=1; i<=j; i++) {
                   card = (Card)it.next();
                   if(i==1) card1 = card.getCard();
                   if(i==2) card2 = card.getCard();
              this.card1 = card1;
              this.card2 = card2;
         public String getCard1() {
              return card1;
         public String getCard2() {
              return card2;
    Jpanel displaying the buttons
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Controll extends JPanel {
         JButton deal = new JButton("Deal");
         JButton newcard = new JButton("New card");
         JButton stay = new JButton("Stay");
         JButton exit = new JButton("Exit");
         public Controll(View view) {
         final Deal d = new Deal();
         final View v = view;
              class ChoiceListener implements ActionListener
                   int i=0;
                   public void actionPerformed(ActionEvent event) {
                        if("deal".equals(event.getActionCommand()))
                             d.dealCards(2);
                             stay.setEnabled(true);
                             newcard.setEnabled(true);
                             deal.setEnabled(false);
                             v.dealCards(d.getCard1(),d.getCard2());
                             v.resetNew();
                             v.repaint();
                             i=0;
                        if("exit".equals(event.getActionCommand()))
                             System.exit(0);
                        if("newcard".equals(event.getActionCommand()))
                             if(i != 3) {
                                  d.dealCards(1);
                                  v.newCard(d.getCard1(),20);
                                  v.repaint();
                                  i++;
                             if(i == 3) {
                                  newcard.setEnabled(false);
                                  stay.setEnabled(false);
                                  deal.setEnabled(true);
                        if("stay".equals(event.getActionCommand()))
                             deal.setEnabled(true);
                             stay.setEnabled(false);
                             newcard.setEnabled(false);
              Color c = new Color(0, 0, 100);
              setPreferredSize(new Dimension(400, 40));
              setBackground(c);
              ActionListener listener = new ChoiceListener();
              deal.setActionCommand("deal");
              exit.setActionCommand("exit");
              newcard.setActionCommand("newcard");
              stay.setActionCommand("stay");
              exit.addActionListener(listener);
              deal.addActionListener(listener);
              newcard.addActionListener(listener);
              stay.addActionListener(listener);
              add(deal);
              add(newcard);
              add(stay);
              add(exit);
              stay.setEnabled(false);
              newcard.setEnabled(false);
    JPanel displaying the board with cards
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class View extends JPanel {
         String dealcard1;
         String dealcard2;
         String newcard;
         int i;
         private Image cardimage1 = null;
         private Image cardimage2 = null;
         private Image cardimage3 = null;
         public View() {
              Color c = new Color(0, 100, 0);
              setPreferredSize(new Dimension(400, 300));
              setBackground(c);
         public void dealCards(String incard1, String incard2) {
              dealcard1 = incard1;
              dealcard2 = incard2;
         public void newCard(String incard3,int j){
              newcard = incard3;
              i = i+j;
         public void resetNew() {
              i=0;
              newcard = "";
         public void paint(Graphics g) {
              super.paint(g);
              Toolkit kit = Toolkit.getDefaultToolkit();
              cardimage1 = kit.getImage("CardImages/"+dealcard1+".gif");
              cardimage2 = kit.getImage("CardImages/"+dealcard2+".gif");
              cardimage3 = kit.getImage("CardImages/"+newcard+".gif");
              g.drawImage(cardimage1,80,200,this);
              g.drawImage(cardimage2,100,200,this);
              g.drawImage(cardimage3,180+i,200,this);
    Main
    import javax.swing.*;
    import java.awt.*;
    public class Main
         public static void main(String[] args)
                   JFrame frame = new JFrame("card");
                   View v = new View();
                   Controll c = new Controll(v);
                   frame.getContentPane().add(v, BorderLayout.NORTH);
                   frame.getContentPane().add(c, BorderLayout.SOUTH);
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.pack();
                   frame.show();
    }

    Actually, your app looks okay. Since you asked for some ideas I made some changes, including changing the name of some classes, variables and the image folder. I put all the files in one because I'm lazy. Score is the only class without changes. And nice images.
    Some suggestions:
    1 � try to keep the responsibilities of the View/CardTable class limited to rendering images. You only need to load an image once; continual loading makes for slow performance. If you are using j2se 1.4+ you can use the ImageIo read methods and could then load the images in the Deck class, eliminating the need to pass the images to Deck from View/CardTable (which is an ImageObserver needed for the MediaTracker).
    2 � let the classes do more of the work, eg, Deal/Dealer can add the new cards to the View/CardTable. This will simplify the event code. The ChoiceListener class could be an inner named/nested class and will be easier to follow/maintain if removed from the class constructor.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class CardGame
        public static void main(String[] args)
            JFrame frame = new JFrame("card");
            CardTable table = new CardTable();
            Controller control = new Controller(table);
            frame.getContentPane().add(table, BorderLayout.NORTH);
            frame.getContentPane().add(control, BorderLayout.SOUTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
    class CardTable extends JPanel {
        Image[] images;
        Image cardBack;
        private String score;
        List player, house;
        public CardTable() {
            loadImages();
            score = "0";
            player = new ArrayList();
            house = new ArrayList();
            Color c = new Color(0, 100, 0);
            setPreferredSize(new Dimension(400, 300));
            setBackground(c);
        public void setScore(int score) {
            this.score = String.valueOf(score);
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            int x = 80, y = 50;
            Card card;
            for(int j = 0; j < house.size(); j++) {
                card = (Card)house.get(j);
                if(j == 0)
                    g.drawImage(cardBack, x, y, this);
                else
                    g.drawImage(card.getImage(), x, y, this);
                x += 20;
            x = 80; y = 200;
            for(int j = 0; j < player.size(); j++)
                card = (Card)player.get(j);
                g.drawImage(card.getImage(), x, y, this);
                x += 20;
            g.setColor(Color.white);
            g.drawString("Score: " + score, 345, 15);
        public void reset() {
            player.clear();
            house.clear();
            repaint();
        public void addCard(Card card)
            player.add(card);
            repaint();
        public void addDealerCard(Card card)
            house.add(card);
            repaint();
        private void loadImages() {
            String[] suits = { "c", "h", "s", "d" };
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            MediaTracker tracker = new MediaTracker(this);
            cardBack = toolkit.getImage("cards/00w.gif");
            tracker.addImage(cardBack, 0);
            images = new Image[suits.length * 13];
            int index = 0;
            for(int j = 0; j < suits.length; j++)
                for(int k = 2; k < 15; k++)
                    String fileName = "cards/" + k + suits[j] + ".gif";
                    images[index] = toolkit.getImage(fileName);
                    tracker.addImage(images[index], 0);
                    index++;
            try
                tracker.waitForAll();
            catch(InterruptedException ie)
                System.out.println("Image loading in CardTable interrupted: " +
                                    ie.getMessage());
    class Controller extends JPanel {
        CardTable table;
        Dealer d;
        JButton deal, newcard, stay, exit;
        public Controller(CardTable ct) {
            table = ct;
            d = new Dealer(table, table.images);
            Color c = new Color(0, 0, 100);
            setPreferredSize(new Dimension(400, 40));
            setBackground(c);
            deal = new JButton("Deal");
            newcard = new JButton("New card");
            stay = new JButton("Stay");
            exit = new JButton("Exit");
            deal.setActionCommand("deal");
            exit.setActionCommand("exit");
            newcard.setActionCommand("newcard");
            stay.setActionCommand("stay");
            ActionListener listener = new ChoiceListener();
            exit.addActionListener(listener);
            deal.addActionListener(listener);
            newcard.addActionListener(listener);
            stay.addActionListener(listener);
            add(deal);
            add(newcard);
            add(stay);
            add(exit);
            stay.setEnabled(false);
            newcard.setEnabled(false);
        private class ChoiceListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                String ac = event.getActionCommand();
                if(ac.equals("deal")) {
                    d.prepareDeck();
                    table.reset();
                    d.dealCards(2);
                    d.dealDealerCards(2);
                    stay.setEnabled(true);
                    newcard.setEnabled(true);
                    deal.setEnabled(false);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
                if(ac.equals("exit"))
                    System.exit(0);
                if(ac.equals("newcard"))
                    d.dealCards(1);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
                    if(s.getScore() > 21) {
                        stay.setEnabled(false);
                        newcard.setEnabled(false);
                        deal.setEnabled(true);
                        s.resetScore();
                if(ac.equals("stay"))
                    deal.setEnabled(true);
                    stay.setEnabled(false);
                    newcard.setEnabled(false);
                    Score s = d.getScore();
                    table.setScore(s.getScore());
    class Dealer {
        CardTable table;
        Deck deck;
        Iterator it;
        private int score;
        private int dealerScore;
        Score s;
        public Dealer(CardTable ct, Image[] images) {
            table = ct;
            deck = new Deck(images);
            score = 0;
            dealerScore = 0;
            s = new Score();
        public void dealCards(int j) {
            Card card;
            for(int i = 0; i < j; i++) {
                card = (Card)it.next();
                table.addCard(card);
                if(card.getValue() > 10)
                    score += 10;
                else
                    score += card.getValue();
            s.setScore(score);
            score = 0;
        public void dealDealerCards(int j) {
            Card card;
            for(int i = 0; i < j; i++) {
                card = (Card)it.next();
                table.addDealerCard(card);
                if(card.getValue() > 10)
                    dealerScore += 10;
                else
                    dealerScore += card.getValue();
            s.setDealerScore(dealerScore);
            dealerScore = 0;
        public void prepareDeck() {
            deck.shuffle();
            it = deck.getCards().iterator();
        public Score getScore() {
            return s;
    class Score {
        private int score;
        public void setScore(int s) {
            score = score + s;
        public void resetScore() {
            score = 0;
        public int getScore() {
            return score;
        private int dealerScore;
        public void setDealerScore(int s) {
            dealerScore = dealerScore + s;
            System.out.println("DEALER: " + dealerScore);
        public void resetDealerScore() {
            dealerScore = 0;
        public int getDealerScore() {
            return dealerScore;
    class Deck {
        List cards;
        public Deck(Image[] images) {
            cards = new ArrayList();
            createDeck(images);
        private void createDeck(Image[] images) {
            for(int j = 0; j < images.length; j++)
                int value = j % 13 + 2;
                cards.add(new Card(images[j], value));
        public void shuffle() {
            for(int j = 0; j < 4; j++)
                Collections.shuffle(cards);
        public List getCards() {
            return cards;
    class Card {
        private Image image;
        private int value;
        public Card(Image image, int value) {
            this.image = image;
            this.value = value;
        public Image getImage() {
            return image;
        public int getValue() {
            return value;
    }

  • To convert multiple image files to pdf using pdfsharp in C#

    Hey guys I have this C# code to convert any image file to .pdf using pdfsharp.dll. But I want to select multiple images for conversion please help. here's my code (plz note enable pdfsharp.dll in the reference)
    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Linq;
    usingSystem.Text;
    usingSystem.Threading.Tasks;
    usingPdfSharp.Pdf;
    usingPdfSharp.Drawing;
    usingSystem.IO;
    namespaceConsoleApplication1
    classProgram
    staticvoidMain(string[]
    args)
    PdfDocumentdoc =
    newPdfDocument();
    doc.Pages.Add(newPdfPage());
    XGraphicsxgr =
    XGraphics.FromPdfPage(doc.Pages[0]);
    XImageimg =
    XImage.FromFile(source
    path...);
    xgr.DrawImage(img,0,0);
    doc.Save(destination path...);
    doc.Close();

    try this one
    public string CreatePDF(System.Collections.Generic.List<byte[]> images)
    dynamic PDFGeneratePath = Server.MapPath("../images/pdfimages/");
    dynamic FileName = "attachmentpdf-" + DateTime.Now.Ticks + ".pdf";
    if (images.Count >= 1) {
    Document document = new Document(PageSize.LETTER);
    try {
    // Create pdfimages directory in images folder.
    if ((!Directory.Exists(PDFGeneratePath))) {
    Directory.CreateDirectory(PDFGeneratePath);
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.GetInstance(document, new FileStream(PDFGeneratePath + FileName, FileMode.Create));
    // opens up the document
    document.Open();
    // Add metadata to the document. This information is visible when viewing the
    // Set images in table
    PdfPTable imageTable = new PdfPTable(2);
    imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
    imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
    for (int ImageIndex = 0; ImageIndex <= images.Count - 1; ImageIndex++) {
    if ((images(ImageIndex) != null) && (images(ImageIndex).Length > 0)) {
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(SRS.Utility.Utils.ByteArrayToImage(images(ImageIndex)), System.Drawing.Imaging.ImageFormat.Jpeg);
    // Setting image resolution
    if (pic.Height > pic.Width) {
    float percentage = 0f;
    percentage = 400 / pic.Height;
    pic.ScalePercent(percentage * 100);
    } else {
    float percentage = 0f;
    percentage = 240 / pic.Width;
    pic.ScalePercent(percentage * 100);
    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    imageTable.AddCell(pic);
    if (((ImageIndex + 1) % 6 == 0)) {
    document.Add(imageTable);
    document.NewPage();
    imageTable = new PdfPTable(2);
    imageTable.DefaultCell.Border = Rectangle.NO_BORDER;
    imageTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
    if ((ImageIndex == (images.Count - 1))) {
    imageTable.AddCell(string.Empty);
    document.Add(imageTable);
    document.NewPage();
    } catch (Exception ex) {
    throw ex;
    } finally {
    // Close the document object
    // Clean up
    document.Close();
    document = null;
    return PDFGeneratePath + FileName;

  • Multiple images in pscs5 when importing from bridge

    Hi Guys
    Hope someone can throw some light on my problem?
    When I bring an image from bridge into photoshop CS5 the image sometimes (more than I would like) breaks up into multiple images in the same window. (see attached example). It was suggested that my video driver may need updating but on checking I have the latest drivers!
    This problem has only been happening for about a month and  everthing was working fine before that. Im running win7pro 64 bit and am running photoshop from my ssd drive. The display driver is a Nvidia Geforce 240 which again has been fine previously. Would it be worth unistalling/reinstalling the program, just a thought!
    Any help from you guys would be more than welcome.
    Thanks trev

    Chris and Noel
    Thank you both for your advice. Chris I tried the update driver from Nvidias web site and it also said that my driver was uptodate 'do you want install anyway' which i did! It made a slight difference but still the problem showed up, so I disabled the Open gl drawing box in preferences menu and then reset it changing the advanced setting to normal in the advanced menu. This seemed (not holding my breath) to have done the trick! and Noel I saw the option for what you have said but I didnt have the confidence to go manual, that'll be my plan B.
    Thanks again guys, I'll be back for more advice
    Trev

  • Multiple Images Dragged on a JPanel

    I am trying to add multiple BufferedImages to a JPanel. I can get one BufferedImage on there fine by creating my own class which overrides JPanel, and then in the paintComponent(Graphics g) method, I have a method with g.drawImage(image, npx, npy, null); to draw the image on the panel.
    So that works fine for one image. I have also implemented a MouseMotionAdapter so I can drag the image around. However I am having GREAT difficulty implementing it with multiple images. I cannot workout how to do this. I am aware I need to have an ArrayList containing all the images, but I cannot determine how I am to loop through each one, getting the correct image, then moving that one.
    Please help with some useful code. (I can provide mine if required).
    Kelvin

    803539 wrote:
    Hi pierrot_2,
    I'm not yet. I'm not yet, I was thinking I would just have to loop through the list of images, getting the correct image (by a method unknown yet) and then calling the drawImage() method, passing the selected image as a parameter.Kelvin, take your project one step at a time. The first thing I would do is try painting all four images first. You can do it quickly by having a Point[] array along side of a BufferedImage[] array. Lets's say the images are w=200, h=160 for now.
    BufferedImage[] images = new BufferedImage[4];
    Point[] locations = new Point[4];
    locations[0] = new Point(0, 0);
    locations[1] = new Point(200, 0);
    locations[2] = new Point(0, 160);
    locations[3] = new Point(200, 160);
    // paintComponent
    for(int i = 0; i < images.length; i++)}
      BufferedImage bi = images;
    Point p = locations[i];
    g.drawImage(bi, p.x. p.y, null);
    }Use something like the code above to get you started. Kelvin, there are much better ways to do this, but for now see if you can paint all your images on the JPanel first, using nothing but <tt> images </tt>and<tt> locations </tt>as described. Later, you may want to switch to Rectangles. See how the FOR loop will call<tt> drawImage() </tt>four times. See how the Point objects are being used to position the image being painted? Do this BEFORE you try to move them around the canvas. Call home if you have troubles.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Multiple image selection.

    Hi java professionals...
    I have a coursework, to write an interface for NIM game.
    My main problem is to select multiple images.
    Basically I need to code something similar to this (http://www.robtex.com/robban/nim1.htm) design, like select several images, press the button and images should disappear.
    Does anybody now how to do multiple selection of images? if it is possible of course..

    You just need to capture mouse presses and do your
    painting (images and such) onto a component.
    You can use this to emulate "selecting images".
    It would work something like this.
    Paint your image somewhere in the component.
    On a mouse click check if an image resides at that location on the
    screen. If so set a virtual "selected" flag and draw whatever is
    necessary to present it as such.
    Good luck.

  • Movement of multiple images in Applet

    Hello all
    I am working on this application in which there is a background image and foreground image.now user can move the front image with mouse.intially i was working with single image movement and it worked great.but i changed the code for multiple image movement , its not working. I have used the paint component method of the panel for the drawing. Can any one could give me the idea of doing it in a better way
    Thanx

    I have done it , If any body needs help Please do ask
    thanx

  • Preview won't open multiple images

    When I open one image in preview, it opens fine. If I open a second image, the first image disappears. If I try and open multiple images at once, the drawer slides out, but it's empty, and again, only one image will show up. Any ideas?

    Hello, if you cannot figure out how to fix the issue I have a nice PDF combiner and exporter, you can write in any application, Text Edit, Pages, Word, and export to PDF, combine with this tool.
    <<http://www.monkeybreadsoftware.de/>
    Download the new version if you like it.
    Ray

  • Super Complicated Multiple Images Question

    OK. I'm stuck. I'll give you my situation and what I've tried (and what's worked):
    I've got a JPanel size (5700,5700) inside a JscrollPane size (700,500).
    On this JPanel, I need to be able to draw a graphic with a click of the mouse button, and rotate the graphic with a right click. Clicking a JButton will "lock" the graphic in place, and then call up the next image for drawing. On top of all this(literally) I have several other graphics to be moved and displayed.
    I've got the GUI done, and added the mouseListeners.
    In a previous test I've gotten the image to display on click and rotate on right click. I'm stuck on how best to display the other graphics at the same time. Any tips? I haven't found any threads in here that specifically address any of this and it's driving me crazy.
    Thanks in advance.

    I am trying to use multiple images in a panel, yes, with an enforced hierarchy. But all the reading I've done suggests you can't put a JLayeredPane inside a JScrollPane and thus I've tried everything but that (aside from a few minimalist efforts).

  • Trying to create a surface  with multiple images with mouse events

    novice programmer (for a applet program)
    hi trying to create a surface i.e jpanel, canvas, that allows multiple images to be created.
    Each object is to contain a image(icon) and a name associated with that particular image. Then each image+label has a mouse event that allows the item to be dragged around the screen.
    I have tried creating own class that contains a image and string but I having problems.
    I know i can create a labels with icons but having major problems adding mouse events to allow each newly created label object to moved by the users mouse?
    if any one has any tips of how to acheive this it would be much appreciated. Thanks in advance.
    fraser.

    This should set you on the right track:- import java.awt.*;
        import java.awt.event.*;
        import javax.swing.*;
        public class DragTwoSquares extends JApplet implements MouseListener, MouseMotionListener {  
           int x1, y1;   // Coords of top-left corner of the red square.
           int x2, y2;   // Coords of top-left corner of the blue square.
           /* Some variables used during dragging */
           boolean dragging;      // Set to true when a drag is in progress.
           boolean dragRedSquare; // True if red square is being dragged, false                              //    if blue square is being dragged.                            
           int offsetX, offsetY;  // Offset of mouse-click coordinates from
                                  //   top-left corner of the square that was                           //   clicked.
           JPanel drawSurface;    // This is the panel on which the actual
                                  // drawing is done.  It is used as the
                                  // content pane of the applet.  It actually                      // belongs to an anonymous class which is
                                  // defined in place in the init() method.
            public void init() {
                 // Initialize the applet by putting the squares in a
                 // starting position and creating the drawing surface
                 // and installing it as the content pane of the applet.
              x1 = 10;  // Set up initial positions of the squares.
              y1 = 10;
              x2 = 50;
              y2 = 10;
              drawSurface = new JPanel() {
                        // This anonymous inner class defines the drawing
                        // surface for the applet.
                    public void paintComponent(Graphics g) {
                           // Draw the two squares and a black frame
                           // around the panel.
                       super.paintComponent(g);  // Fill with background color.
                       g.setColor(Color.red);
                       g.fillRect(x1, y1, 30, 30);
                       g.setColor(Color.blue);
                       g.fillRect(x2, y2, 30, 30);
                       g.setColor(Color.black);
                       g.drawRect(0,0,getSize().width-1,getSize().height-1);
              drawSurface.setBackground(Color.white);
              drawSurface.addMouseListener(this);
              drawSurface.addMouseMotionListener(this);
              setContentPane(drawSurface);
           } // end init();
           public void mousePressed(MouseEvent evt) {
                  // Respond when the user presses the mouse on the panel.
                  // Check which square the user clicked, if any, and start
                  // dragging that square.
              if (dragging)  // Exit if a drag is already in progress.
                 return;           
              int x = evt.getX();  // Location where user clicked.
              int y = evt.getY();        
              if (x >= x2 && x < x2+30 && y >= y2 && y < y2+30) {
                     // It's the blue square (which should be checked first,
                     // since it's in front of the red square.)
                 dragging = true;
                 dragRedSquare = false;
                 offsetX = x - x2;  // Distance from corner of square to (x,y).
                 offsetY = y - y2;
              else if (x >= x1 && x < x1+30 && y >= y1 && y < y1+30) {
                     // It's the red square.
                 dragging = true;
                 dragRedSquare = true;
                 offsetX = x - x1;  // Distance from corner of square to (x,y).
                 offsetY = y - y1;
           public void mouseReleased(MouseEvent evt) {
                  // Dragging stops when user releases the mouse button.
               dragging = false;
           public void mouseDragged(MouseEvent evt) {
                   // Respond when the user drags the mouse.  If a square is
                   // not being dragged, then exit. Otherwise, change the position
                   // of the square that is being dragged to match the position
                   // of the mouse.  Note that the corner of the square is placed
                   // in the same position with respect to the mouse that it had
                   // when the user started dragging it.
               if (dragging == false)
                 return;
               int x = evt.getX();
               int y = evt.getY();
               if (dragRedSquare) {  // Move the red square.
                  x1 = x - offsetX;
                  y1 = y - offsetY;
               else {   // Move the blue square.
                  x2 = x - offsetX;
                  y2 = y - offsetY;
               drawSurface.repaint();
           public void mouseMoved(MouseEvent evt) { }
           public void mouseClicked(MouseEvent evt) { }
           public void mouseEntered(MouseEvent evt) { }
           public void mouseExited(MouseEvent evt) { }  
        } // end class

  • Drawing multiple shape

    I am working on a small program to draw multiple shape, I am having problem because I can not draw more than one shape on the screen at the same time . can you help me pls
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.applet.Applet;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.geom.Rectangle2D;
    import java.awt.Color;
    public class BoxClickApplet extends Applet
    int x1,y1;
    int click=-1;
              class MyMouseListener implements MouseListener
              public void mousePressed(MouseEvent event){}
              public void mouseReleased(MouseEvent event){}
              public void mouseClicked(MouseEvent event)
                   click++;
    if (click==0)
                                  x1=getWidth()/2-20;
                                  y1=getHeight()-40;
                                  repaint();
                                  ((Graphics2D)g).fill(r);
                   if (click==1)
                                  x1=getWidth()/2-20;
                                  y1=getHeight()/2-20;
                                  repaint();
                   if (click==2)
                                  x1=getWidth()/2-20;
                                  y1=0;
                                  repaint();
    if (click==3)
                             x1=getWidth()/2-20;
                             y1=getHeight()/2;
                             repaint();
                             x1=getWidth()/2-20;
                             click=-1;
    public void mouseEntered(MouseEvent event){}
              public void mouseExited(MouseEvent event){}
    MyMouseListener listener = new MyMouseListener();
    addMouseListener(listener);
    public void paint(Graphics g)
         g.setColor(Color.GREEN);
         Rectangle2D.Double r = new Rectangle2D.Double (x1,y1,40,40);
    ((Graphics2D)g).fill(r);

    //  <applet code="BCA" width="400" height="400"></applet>
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    public class BCA extends Applet
        BufferedImage image;
        int width = 40;
        int height = 40;
        public void init()
            addMouseListener(new MyMouseListener());
        public void paint(Graphics g)
            if(image == null)
                initImage();
            g.drawImage(image, 0, 0, this);
        private void initImage()
            int w = getWidth();
            int h = getHeight();
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            g2.setBackground(getBackground());
            g2.clearRect(0,0,w,h);
            g2.dispose();
        private void addRectangle(Point p)
            Graphics2D g2 = (Graphics2D)image.getGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.GREEN);
            g2.fill(new Rectangle(p.x-width/2, p.y-height/2, width, height));
            g2.dispose();
        private void clearImage()
            Graphics g = image.getGraphics();
            g.setColor(getBackground());
            g.fillRect(0, 0, image.getWidth(), image.getHeight());
            g.dispose();
        class MyMouseListener extends MouseAdapter
            public void mousePressed(MouseEvent event)
                if(event.getClickCount() == 2)
                    clearImage();
                else
                    addRectangle(event.getPoint());
                repaint();
    }

  • How do I stop iWeb outputting multiple image files? It makes my site slow!

    I'm a professional web designer (but don't let that put you off) who uses Dreamweaver and also handcodes HTML & CSS websites at work on a PC, but having got a new Mac for home use I thought I'd give iWeb a go for a personal site hosted on .Mac, showcasing my music and film efforts, that I didn't want to have to think about coding.
    I've built a short little site using the attractive 'Travel' theme, just 5 or 6 pages so far, and have not yet added any multimedia content. However, it seemed to take ages to upload it when I published it to .Mac. So then I went to view it, and it was soooo sloooow to download each page, even on my 4mb cable connection. I know it's a fairly graphically-rich theme, but still!
    I noticed that it was redrawing the navigation menu each time... and upon close inspection of the HTML code using Safari's 'View Source' to my horror I found out that that each page has a seperate '_files' folder that contains multiple versions of files that are also used in other pages - including navigation buttons and background images. I also saw that every element has styling applied to it 'inline' in the code, rather than in a single seperate style-sheet.
    To confirm this I published it to a folder on my hard drive and checked it all out. What a mess!
    As a WYSIWYG web page editor iWeb is great but it's an undisputable fact that the HTML markup and CSS code it produces is absolutely appaling. What's worse though is that it also renders whole swaithes of text as images and that it does create seperate folders for each pages content including images, CSS code and navigation buttons - so even though the same images and code are used throughout the site for the background and buttons and layout, they are written out as seperate files and have to be reloaded with every page!!!
    This means that the .Mac server must be getting hammered and webpages are very slow to download and slow to render in Safari - it's almost like dialup when I'm viewing my iWebsite, and like I said, I've got a 4mb cable connection!
    Looking at the code iWeb produces, it is good to see that tables are not used for layout, and that's one thing in its favour. But surely the whole point of providing 'themed' templates for users is that the same content is used across the site and therefore doesn't need to be created multiple times - one of the benefits of using CSS stylesheets. Why doesn't iWeb create a single stylesheet and make efficient use of repeated images instead of creating multiple instances of the same file for each page?
    Perhaps there is a setting somewhere I've missed. If so, let me know someone!
    It is a great WYSIWYG editor, but behind the scenes it's not efficient, it's not clean and simple and it's certainly not attractive - and I'm surprised at that coming from Apple! I know iWeb is a great tool for beginners and I'm a picky professional, but if I was Joe Public First Time Web Designer I'd be very annoyed by this.
    Clean it up and sort it out Mr Jobs!
    PS: Also, where does iWeb store the website whilst it's in production? I can't find it anywhere?

    Your iWeb Site is stored not on your iDisk, but on a file named Domain.sites in your ~/Home/Library/Application Support/iWeb/ Folder.
    If , for whatever reason, you wipe your HD and/or lose this file (Get a new computer, Re-Install your OS, Stolen Laptop, Crashed HD, Etc.) without backing-up your Domain.sites file then you will have to re-build your iWeb sites from scratch again.
    Of course you can edit your Published HTML files in a different program such as Dreamweaver or even Text Edit. You just can't edit Published HTML files in iWeb. Not at this time at least.
    Use iWebBackup to backup your Domain file to a Blank CD or DVD. Backing up your Domain file to another folder on your computer is not fully backing it up. If your computer gets stolen you still lost the file but if you have your Domain file burned onto a CD you have a backup!
    Download iWebBackup Here
    You can use iWebExtender to automatically consolidate your files into one folder and delete multiple images.
    http://iWebFAQ.com

  • Can you edit multiple images from a PDF in photoshop?

    I scan a lot of old publications with images and drawings. The images are in greyscale, but my scanner produces better results set to color. As such, I have to convert the images to greyscale in Photoshop from Acrobat. I have several PS actions that make this process easier, but I wish there was a way to select multiple images from a page or PDF file and run the actions on them (a batch) instead of one at a time. Is there? Or perhaps another method than what I am doing?

    I recommend that you scan first, save as TIFF, do any desired correction, and only then make PDFs. Scanning direct to PDFs is great for simple uncomplicated workflows, but a liability when correction is needed.

  • Is there a way to add multiple images at the same time to Keynote 6.0?

    I just brought keynote after searching online about adding multiple images to a presentation all in one go - I couldn't do this on the powerpoint version I was using but there were multiple references on google to being able to do this on keynote. I purchased it and now can't get it to work! Any ideas anyone? Thanks

    Do you mean like dragging in multiple images and having one image go on each slide? If so, you just drag the images into the Slide List on the left instead of onto the slide. From this prior post.
    https://discussions.apple.com/message/9068283#9068283

  • Js-error while executing Multiple Image Upload wizard

    If i want to save the configured window of Multiple Image Upload with Save to Database wizard i get this js-error: "While executing onClick in MIUploadWSaveWizard.htm, a JavaScript error occured".
    can someone help?
    thanx
    peter

    That again would be more of a question for the Cold Fusion group.
    Try http://forums.adobe.com/community/coldfusion/coldfusion_administration
    Those people will be able to help you out more.
    Brad Lawryk
    Adobe Community Expert, Dreamweaver
    Adobe Usergroup Manager, Northern British Columbia Adobe User Group

Maybe you are looking for

  • Java.security.cert.CertificateException: Untrusted Cert Chain

    Hi all, While sending transaction to our supplier I am facing below error, Actually Our trading partner has given .p7b cert, I converted it into base 64 and i m using in b2b server. I am doing the same with all the suppliers but I am facing issue wit

  • Xorg-server 1.6 and Intel GM965 video card[SOLVED]

    Hi, Because of gtk2/libxi upgrade issue / keyboard layout issue I had to upgrade to xorg-server 1.6 from testing. It won't configure: "Missing output drivers. Configuration failed". Any ideas? Last edited by Llama (2009-04-02 05:21:07)

  • How to get ITResource to Adapter?

    I have written an adapter that I want to get visibility to a database ITResource and I have set an adapter variable to ITResource. But how do I pass\map the ITResource into the Adapter? I have tried to map it via the "Map Adapters" of the Data Object

  • MIGO and MIRO

    HI All, Can you please tell me in third party sales can we do MIRO with out MIGO, if so please tell the process, and wat are all positives and negatives that we will have if we do the same. Thanks in Advance.. Ramki

  • Any way to seperate duplicates so both aren't deleted

    I have loaded a lot of duplicates and when you display them how can you delete just one of the duplicate so you still have one left? ie two of the same song if you highlight or delete all you don't have a copy left. It is further complicated by the f