ActionListener on an Image

I have a few Images moving around on a Canvas.
The Images are of class Image
I have 2 buttons, turn left and turn right which when clicked make one of the Images turn left or right.
The buttons have actionListeners attached to them.
How could I make it so when one of the images is clicked the buttons would cause the clicked on image to move accordingly?
at the moment I'm simply doing this in the button actionPerformed method:
images.get(0).travelX = 5;
where images is an arraylist containg all Images
The actual contents is more complicated, but you get the idea.
Is it possible to do what I want??

It's just the way I've written the code - I have a list of names of the images that are shown on the canvas.
Each name is in it's own jpanel.
The names are retrieved from a variable stored in each Plane instance - this instance is where the image is created.
The code is very long so I can't post, and I'm finding it hard to explain, as various classes are interacting with each other.
Basically when the name in the jpanel is clicked, the mouselistener checks the name against each instance of Plane (which contains the Image) if it matches, an int variable is changed accordingly to the ArrayList element that contains the Plane.
This integer is then used to decide which element of the ArrayList of Planes is chosen - e.g. 3
So, i do planeArray.get(3)
now I have certain image selected, when the turn right button is pressed, the movement values of the plane stored at 3 are changed from within the actionlistener.

Similar Messages

  • Loading Images into Applets

    I've been having problems loading an image into an Applet. I've found that when the getImage() call is put into the init() method it loads the image fine, also implementing an imageUpdate call. However, now I'm trying to expand on this by putting it into a button click, it hangs indefinitely while waiting for the image to load.
    Another interesting point I've noticed is that the Canvas subclass ImageSegmentSelector uses a PixelGrabber in its constructor to put the Image into a buffer - when this class is created from the imageUpdate() call, NOT the init() call, the grabPixels() call hangs indefinitely too!!
    Any feedback, please,
    Jonathan Pendrous
    import java.applet.*;
    import java.net.*;
    import jmpendrous.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class XplaneGlobalSceneryDownloader extends Applet implements ActionListener{
    ImageSegmentSelector worldMap;
    Image img;
    URL url;
    int longtitude = 36;
    int latitude = 18;
    boolean imageLoaded;
    TextField t1, t2,t3;
    Label l1,l2,l3;
    Button b1;
    Applet a1;
    public void init() {
    a1 = this;
    l1 = (Label) add(new Label("Number of horizontal sections: "));
    t1 = (TextField) add(new TextField("45",3));
    l2 = (Label) add(new Label("Number of vertical sections: "));
    t2 = (TextField) add(new TextField("45",3));
    l3 = (Label) add(new Label("URL of image file: "));
    t3 = (TextField) add(new TextField("file:///C:/java/work/xplane_project/source/world-landuse.GIF",60));
    b1 = (Button) add(new Button("Load image"));
    b1.addActionListener(this);
    validate();
    // THIS CODE WORKS FINE ...
    /*try { url = new URL("file:///C:/java/work/xplane_project/source/world-landuse.GIF"); }
    catch(MalformedURLException e) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false) { try { Thread.sleep(1000);   } catch(InterruptedException e) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();*/
    //repaint();
    //worldMap = new ImageSegmentSelector(this, img, longtitude, latitude);
    //repaint();
    public void actionPerformed(ActionEvent e) {
    try { longtitude = Integer.parseInt(t1.getText()); } catch (NumberFormatException ex) {System.exit(0); }
    try { latitude = Integer.parseInt(t2.getText()); } catch (NumberFormatException e2) {System.exit(0); }
    try { url = new URL(t3.getText()); }
    catch(MalformedURLException e3) { System.exit(0);   }
    img = getImage(url);
    //int w=img.getWidth(this);
    while(imageLoaded==false)
    { try { Thread.sleep(1000);   } //KEEPS ON LOOPING
    catch(InterruptedException e4) {System.exit(0);    } }
    worldMap = new ImageSegmentSelector(a1, img, longtitude, latitude);
    add(worldMap);
    //resize(worldMap.getWidth(), worldMap.getHeight());
    validate();
    public boolean imageUpdate(Image i, int flags, int x, int y, int w, int h){
    // THIS NEVER GETS CALLED AT ALL //
    if (((flags & ImageObserver.WIDTH) != 0) && ((flags & ImageObserver.HEIGHT) != 0)) {
    //worldMap = new ImageSegmentSelector(this, i, longtitude, latitude);
    //add(worldMap);
    //validate();
    //repaint();
    imageLoaded = true;
    return false;
    return true;
    }

    Sorry, thought this had been lost.
    You can load a file if the applet itself is run from the local filesystem - it loads it fine from the init(), but not otherwise. But I haven't got the applet to run from a browser yet without crashing (it's OK in the IDE debugger), so that's the next step.

  • Image on the panel

    Hi Experts,
    I am in the midst of getting an image onto a frame hence have some difficulty, I seek your assistance to place an image on the left of the message. The code is append for your advice, please.
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    public class Help implements ActionListener {
    Frame frame = new Frame ("Help");
    Button okButton = new Button ("Ok");
    public Help() {
    Panel buttonPanel = new Panel ();
    buttonPanel.add (okButton);
    okButton.addActionListener (this);
    frame.setLayout(new BorderLayout());
    Panel messagePanel = new Panel();
    messagePanel.setLayout(new GridLayout(14,1));
    messagePanel.add(new Label("Sentence 1 - I want to put an image on my left"));
    messagePanel.add(new Label("Sentence 2 - I want to put an image on my left"));
    messagePanel.add(new Label("Sentence 3- I want to put an image on my left"));
    frame.add("North", messagePanel);
    frame.add("South", buttonPanel);
    frame.pack();
    frame.setVisible(true);
         public static void main(String args[])
         new Help();
         public void actionPerformed (ActionEvent a)
              if (a.getActionCommand().equals("Ok"))
                   frame.dispose();
    }

    Hi there,
    Here is your program with 3 images on the left and 3 labels on their right. Let me know if you have any questions.
    Berk Can Celebisoy
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    public class ForumTest extends Frame implements ActionListener { 
      Button okButton;
      Image image1, image2, image3;
      Toolkit toolkit;
      public ForumTest() {     
         toolkit = Toolkit.getDefaultToolkit();
         image1 = toolkit.getImage("redButton.gif");      
         image2 = toolkit.getImage("greenButton.gif");      
         image3 = toolkit.getImage("blueButton.gif");      
            okButton = new Button ("Ok");     
             okButton.addActionListener (this);     
         ImagePanel imagePanel1 = new ImagePanel(image1);
         ImagePanel imagePanel2 = new ImagePanel(image2);
         ImagePanel imagePanel3 = new ImagePanel(image3);
         Panel buttonPanel = new Panel ();
          buttonPanel.add (okButton);
         Panel messagePanel = new Panel();
          messagePanel.setLayout(new GridLayout(3, 3));
          messagePanel.add(imagePanel1);
          messagePanel.add(new Label("Red button"));
          messagePanel.add(imagePanel2);
          messagePanel.add(new Label("Green button"));
          messagePanel.add(imagePanel3);
          messagePanel.add(new Label("Blue button"));
            this.setLayout(new BorderLayout());     
            this.add("North", messagePanel);
         this.add("South", buttonPanel);     
         this.pack();
         this.setVisible(true);
      public static void main(String args[]) {
        ForumTest forumTest = new ForumTest();
      public void actionPerformed (ActionEvent a) {
        if (a.getActionCommand().equals("Ok"))
          this.dispose();   
    class ImagePanel extends Panel {
      Image img;
      ImagePanel(Image img) {
        this.img = img;
      public void paint(Graphics g) {
         g.drawImage(img, 0, 0, this);
    }

  • Small Image flipping(like a screensaver) app...have easy ? about expansion

    Working on code from:
    http://www.rscc.cc.tn.us/faculty/bell/Cst218/jhtp16.html
    have included it below, just created a directory named images
    and copy/past 8 images into that directory, and rename them bug#.gif, starting at bug0, bug1, bug2...up until bug7.gif
    Run app, it works, fine, it flips through the images
    HOWEVER, of course, while learning/doing I found it inconvenient to have to rename all of the images, and thought of screensaver programs that flips images for you, and was trying to figure out what I'd have to do to make it possible to just load an arbitrary amount/named image files to be able to flip them.
    I figure some kind of JFileChooser would have to be integrated, and then somehow, each file would have to be imported into an Array or Vector set.....
    See...that's an entirely different program....but would be interested in the above, and how I could change the code to allow ANY named image, not just images named "bug" , be apart of the array.
    Somehow, read the entire directory, and import each image into the Array, or a Vector/whatever.....
    While I understand this program ..my "programming brain" /skills are not developed enough to implement the system..hence posting :)
    Thank you for your time...
    //http://www.rscc.cc.tn.us/faculty/bell/Cst218/jhtp16.html
    // LogoAnimator.java
    // Animation a series of images
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LogoAnimator extends JPanel
                              implements ActionListener {
       protected ImageIcon images[];
       protected int totalImages = 8,   //changed from 30 to 8
                     currentImage = 0,
                     animationDelay = 1500; // 50 millisecond delay
       protected Timer animationTimer;
       public LogoAnimator()
          setSize( getPreferredSize() );
          images = new ImageIcon[ totalImages ];
          for ( int i = 0; i < images.length; ++i )
             images[ i ] =
                new ImageIcon( "images/bug" + i + ".gif" );  //?!?! here, in this program, each file would have to be named "bug#"
          startAnimation();
       public void paintComponent( Graphics g )
          super.paintComponent( g );
          if ( images[ currentImage ].getImageLoadStatus() ==
               MediaTracker.COMPLETE ) {
             images[ currentImage ].paintIcon( this, g, 0, 0 );
             currentImage = ( currentImage + 1 ) % totalImages;
       public void actionPerformed( ActionEvent e )
          repaint();
       public void startAnimation()
          if ( animationTimer == null ) {
             currentImage = 0;
             animationTimer = new Timer( animationDelay, this );
             animationTimer.start();
          else  // continue from last image displayed
             if ( ! animationTimer.isRunning() )
                animationTimer.restart();
       public void stopAnimation()
          animationTimer.stop();
       public Dimension getMinimumSize()
          return getPreferredSize();
       public Dimension getPreferredSize()
          return new Dimension( 160, 80 );
       public static void main( String args[] )
          LogoAnimator anim = new LogoAnimator();
          JFrame app = new JFrame( "Animator test" );
          app.getContentPane().add( anim, BorderLayout.CENTER );
          app.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                   System.exit( 0 );
          // The constants 10 and 30 are used below to size the
          // window 10 pixels wider than the animation and
          // 30 pixels taller than the animation.
          app.setSize( anim.getPreferredSize().width + 10,
                       anim.getPreferredSize().height + 30 );
          app.show();
    }

    This is set up to compile and run in j2se 1.4
    You can swap the comments in three marked areas to compile and run in j2se 1.5
    If using earlier versions than j2se 1.4 you'll need to replace the image loading code (2 lines, marked)
    with earlier code, such as ImageIcon (j2se 1.2) or the earlier Toolkit methods with MediaTracker.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.List;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.FileImageInputStream;
    import javax.swing.*;
    public class SlideShow
        SlidePanel slidePanel;
        JFileChooser fileChooser;
        JComboBox slides;
        JFrame f;
        public SlideShow()
            slidePanel = new SlidePanel();
            f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getSlidePanel(), "North");
            f.getContentPane().add(slidePanel);
            f.getContentPane().add(getControlPanel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private JPanel getSlidePanel()
            fileChooser = new JFileChooser("images/");
            slides = new JComboBox();
            Dimension d = slides.getPreferredSize();
            d.width = 125;
            slides.setPreferredSize(d);
            final JButton
                open   = new JButton("open"),
                remove = new JButton("remove");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showDialog();
                    if(button == remove)
                        removeSlide();
            open.addActionListener(l);
            remove.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(slides);
            panel.add(remove);
            return panel;
        private JPanel getControlPanel()
            final JButton
                start = new JButton("start"),
                stop  = new JButton("stop");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == start)
                        slidePanel.start();
                    if(button == stop)
                        slidePanel.stop();
            start.addActionListener(l);
            stop.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(start);
            panel.add(stop);
            return panel;
        private void showDialog()
            if(fileChooser.showOpenDialog(f) == JFileChooser.APPROVE_OPTION)
                File file = fileChooser.getSelectedFile();
                if(hasValidExtension(file))
                    Slide slide = new Slide(file);
                    slides.addItem(slide);
                    slides.setSelectedItem(slide);
                    slidePanel.addImage(slide.getFile());
        private boolean hasValidExtension(File file)
            String[] okayExtensions = { "gif", "jpg", "png" };
            String path = file.getPath();
            String ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
            for(int j = 0; j < okayExtensions.length; j++)
                if(ext.equals(okayExtensions[j]))
                    return true;
            return false;
        private void removeSlide()
            Slide slide = (Slide)slides.getSelectedItem();
            int index = slides.getSelectedIndex();
            slides.removeItem(slide);
            slidePanel.removeImage(index);
        public static void main(String[] args)
            new SlideShow();
    class Slide
        File file;
        public Slide(File file)
            this.file = file;
        public File getFile()
            return file;
        public String toString()
            return file.getName();
    class SlidePanel extends JPanel
        //List<BufferedImage> images;  // j2se 1.5
        List images;                   // j2se 1.4
        int count;
        boolean keepRunning;
        Thread animator;
        public SlidePanel()
            //images = Collections.synchronizedList(new ArrayList<BufferedImage>());  // 1.5
            images = Collections.synchronizedList(new ArrayList());  // j2se 1.4
            count = 0;
            keepRunning = false;
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            if(images.size() > 0)
                //BufferedImage image = images.get(count);               // j2se 1.5
                BufferedImage image = (BufferedImage)images.get(count);  // j2se 1.4
                int imageWidth = image.getWidth();
                int imageHeight = image.getHeight();
                int x = (w - imageWidth)/2;
                int y = (h - imageHeight)/2;
                g.drawImage(image, x, y, this);
        private Runnable animate = new Runnable()
            public void run()
                while(keepRunning)
                    if(images.size() == 0)
                        stop();
                        break;
                    count = (count + 1) % images.size();
                    repaint();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("animate interrupt: " + ie.getMessage());
                repaint();
        public void start()
            if(!keepRunning)
                keepRunning = true;
                animator = new Thread(animate);
                animator.start();
        public void stop()
            if(keepRunning)
                keepRunning = false;
                animator = null;
        public void addImage(File file)
            try
                FileImageInputStream fiis = new FileImageInputStream(file);  // j2se 1.4+
                images.add(ImageIO.read(fiis));                              //    "
            catch(FileNotFoundException fnfe)
                System.err.println("file: " + fnfe.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
        public void removeImage(int index)
            images.remove(index);
    }

  • Image-link totally displaced....

    Hi there,
    I am including a header.jsp file. this file contains a menu bar, which is made up of images in a table row. I was first working with <a href="# dummies, and now put in the commandButton tags and specified the image to display with the image attribute. it, works, but the image shows up in the uper left corner and not there where it should be (there were the tag is....) how can I fix this?
    <tr>
    <td><img name="layout_r2_c1" src="/pixxi/pages/images/layout_r2_c1.gif" width="97" height="25" border="0" alt=""></td>
    <td>
    <h:commandLink id="de" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_de}"/>
    <!-- should be here -->
    </td>

    I solved the problem now, but I am not quite satisfied with the solution (technically):
    the included file now only contains the pure jsf tags, no html at all. this was possible, because all the images were in a line. so i took out the td's and so on and placed the surroundign td colspan="5" in the base jsp page.
    the inlcuded page contains only these tags:
    <h:form>
         <h:commandButton id="de" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_de}"/>
         <h:commandButton id="en" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_en}"/>
         <h:commandButton id="a1" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_register}"/>
         <h:commandButton id="a2" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_about}"/>
         <h:commandButton id="a3" actionListener="#{methodsBean.chooseLocale}" image="#{messages.image_spam}"/>     
    </h:form>
    I am not satisfied, because I don't understand why the imageButton was not rendered where he should be. there might not always be the possibility to render the things simply without the html....
    any comments?

  • Rolling Images for poker Game

    Hello everybody,
    i m trying to make poker game in java. it is some what like this, there will three labels which will show continuos scrolling images or numbers. there will a button "HIT" button to stop moving images.after that those images will stop one by one.if all images are same then he will get message of congratulation. first of all i m trying to show numbers in labels. but it should look like it is rolling. with settext method it is directly printing the number. can anybody suggest me how to print number in Jlabel with rolling effect? . Thanks in advance

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class SpinningGeeks extends JPanel implements ActionListener,
                                                         Runnable {
        BufferedImage image;
        Rectangle[] rects;
        int[] yPos;
        int dy = 3;
        Random seed = new Random();
        boolean[] runs = new boolean[3];
        Thread thread;
        long delay = 25;
        boolean stopping = false;
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("START"))
                start();
            if(ac.equals("STOP"))
                stopping = true;
        public void run() {
            int[] ds = new int[yPos.length];
            for(int j = 0; j < yPos.length; j++) {
                ds[j] = dy -1 + seed.nextInt(3);
            int runIndex = 0;
            boolean countingDown = false;
            long time = 0;
            while(runs[runs.length-1]) {
                try {
                    Thread.sleep(delay);
                } catch(InterruptedException e) {
                    break;
                if(stopping && !countingDown) {
                    int remainder = yPos[runIndex] % rects[runIndex].height;
                    boolean atEdge = remainder < ds[runIndex]/2;
                    if(atEdge) {
                        // Stop here, start waiting 2 seconds before
                        // moving on to stop the next image.
                        countingDown = true;
                        time = 0;
                        runs[runIndex] = false;
                        runIndex++;
                        if(runIndex > runs.length-1) {
                            continue;
                } else if(countingDown) {
                    // Wait 2 seconds before stopping the next image.
                    time += delay;
                    if(time > 2000) {
                        countingDown = false;
                // Advance all images that have not been stopped.
                for(int j = 0; j < yPos.length; j++) {
                    if(runs[j]) {
                        yPos[j] += ds[j];
                        if(yPos[j] > image.getHeight()) {
                            yPos[j] = 0;
                repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            int pad = 5;
            int x = (getWidth() - (3*rects[0].width + 2*pad))/2;
            int y = (getHeight() - rects[0].height)/2;
            for(int j = 0; j < rects.length; j++) {
                rects[j].setLocation(x, y);
                x += rects[j].width + pad;
            Shape origClip = g2.getClip();
            for(int j = 0; j < yPos.length; j++) {
                x = rects[j].x;
                y = rects[j].y - yPos[j];
                // Comment-out next line to see what's going on.
                g2.setClip(rects[j]);
                g2.drawImage(image, x, y, this);
                if(yPos[j] > image.getHeight() - rects[j].height) {
                    y += image.getHeight();
                    g2.drawImage(image, x, y, this);
            g2.setClip(origClip);
            g2.setPaint(Color.red);
            for(int j = 0; j < rects.length; j++) {
                g2.draw(rects[j]);
        private void start() {
            if(!runs[runs.length-1]) {
                Arrays.fill(runs, true);
                stopping = false;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
        private void stop() {
            runs[runs.length-1] = false;
            if(thread != null) {
                thread.interrupt();
            thread = null;
        private JPanel getContent(BufferedImage[] images) {
            // Make a film strip assuming all images have same size.
            int w = images[0].getWidth();
            int h = images.length*images[0].getHeight();
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w, h, type);
            Graphics2D g2 = image.createGraphics();
            int y = 0;
            for(int j = 0; j < images.length; j++) {
                g2.drawImage(images[j], 0, y, this);
                y += images[j].getHeight();
            g2.dispose();
            // Initialize clipping rectangles.
            rects = new Rectangle[3];
            for(int j = 0; j < rects.length; j++) {
                rects[j] = new Rectangle(w, images[0].getHeight());
            // Initialize yPos array.
            yPos = new int[rects.length];
            for(int j = 0; j < yPos.length; j++) {
                yPos[j] = 2*j*images[0].getHeight();
            return this;
        private JPanel getControls() {
            String[] ids = { "start", "stop" };
            JPanel panel = new JPanel();
            for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setActionCommand(ids[j].toUpperCase());
                button.addActionListener(this);
                panel.add(button);
            return panel;
        public static void main(String[] args) throws IOException {
            String[] ids = { "-c---", "--g--", "---h-", "----t", "-cght" };
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++) {
                String path = "images/geek/geek" + ids[j] + ".gif";
                images[j] = javax.imageio.ImageIO.read(new File(path));
            SpinningGeeks test = new SpinningGeeks();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getContent(images));
            f.add(test.getControls(), "Last");
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    }geek images from [Using Swing Components Examples|http://java.sun.com/docs/books/tutorial/uiswing/examples/components/index.html]

  • I can't get my Button to work?

    Hello everyone,
    I been trying to get my Button working, but I don't understand what's wrong. I've tried a bunch of stuff, each with failure. Can any of you guys help me out here? I know that it's a little bit of a mess, but for some reason, it gives me a NullPointerException when I execute it. If I comment out 4 lines of code, about the getContentPane, it works without making a button. Problem is, I want to keep the Button in there. What should I do?
    Thanks
    import com.brackeen.javagamebook.graphics.ScreenManager;
    import com.brackeen.javagamebook.graphics.ScreenManager;
    import com.brackeen.javagamebook.sound.SoundManager;
    import com.brackeen.javagamebook.graphics.NullRepaintManager;
    import com.brackeen.javagamebook.input.*;
    import com.brackeen.javagamebook.input.GameAction;
    import com.brackeen.javagamebook.graphics.*;
    import com.brackeen.javagamebook.sound.*;
    import com.brackeen.javagamebook.test.GameCore;
    import java.util.List;
    import java.util.ArrayList;
    import javax.swing.border.Border;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.io.File;
    import java.awt.event.KeyListener;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.midi.Sequence;
    import java.applet.AudioClip;
    import javax.sound.midi.Sequencer;
    import java.awt.image.BufferStrategy;
    import java.awt.image.BufferedImage;
    import java.lang.reflect.InvocationTargetException;
    public class Graphic2 implements ActionListener
         public static void main(String[] args)
    new Graphic2().run();
    private JPanel startButtonSpace;
    private static final long DEMO_TIME = 30000;
    private static final String EXIT = "Exit";
    private ScreenManager screen;
    private ActionListener action;
    private Image Background, Title, Start;
    private boolean isRunning;
    private Sequence music;
    private SoundManager soundManager = new SoundManager(PLAYBACK_FORMAT);
    private MidiPlayer midiPlayer;
    private Sound titleMusic;
    //Uncompressed, 44100Hz, 16-bit, Sterio, Signed, Little-Endian
    private static final AudioFormat PLAYBACK_FORMAT =
    new AudioFormat(44100, 16, 2, true, false);
    protected InputManager inputManager;
    protected GameAction configAction;
    protected GameAction exit;
    private JButton startButton;
    private static final DisplayMode POSSIBLE_MODES[] = {
    new DisplayMode(1024, 768, 32, 0),
    new DisplayMode(1024, 768, 24, 0),
    new DisplayMode(1024, 768, 16, 0),
    new DisplayMode(800, 600, 32, 0),
    new DisplayMode(800, 600, 24, 0),
    new DisplayMode(800, 600, 16, 0)
    public void loadImages()
    // load images
    Background = loadImage("Title Screen.jpg");
    Title = loadImage("Title.gif");
    Start = loadImage("Start.gif");
    public Image loadImage(String fileName)
    return new ImageIcon(fileName).getImage();
    public void animationLoop()
    long startTime = System.currentTimeMillis();
    long currTime = startTime;
    while (isRunning)
    long elapsedTime = System.currentTimeMillis() - currTime;
    currTime += elapsedTime;
    // draw and update screen
    Graphics2D g = screen.getGraphics();
    draw(g);
    g.dispose();
    screen.update();
    // take a nap
    try
    Thread.sleep(20);
    catch (InterruptedException ex) { }
    public void initSounds()
    //midiPlayer = new MidiPlayer();
    titleMusic = soundManager.getSound("movie02.wav");
    //music = midiPlayer.getSequence("potc.mid");
    public void run()
         NullRepaintManager.install();
         isRunning = true;
         initSounds();
         NullRepaintManager.install();
         screen = new ScreenManager();
         JFrame frame = screen.getFullScreenWindow();
    // create buttons
    startButton = createButton("Start.gif");
    startButton.setLocation(460, 500);
    //frame.getContentPane().setLayout(new FlowLayout());
    //frame.getContentPane().add(startButton);
    try
    DisplayMode displayMode =
    screen.findFirstCompatibleMode(POSSIBLE_MODES);
    screen.setFullScreen(displayMode);
    loadImages();
    soundManager.play(titleMusic);
    //if (frame.getContentPane() instanceof JComponent)
         //((JComponent)frame.getContentPane()).setOpaque(false);
    animationLoop();
    finally
    screen.restoreScreen();
    soundManager.stop();
    frame.validate();
    Window window = screen.getFullScreenWindow();
         public void draw(Graphics2D g)
    // draw background
    g.drawImage(Background, 0, 0, null);
    // draw image
    g.drawImage(Title, 342, 244, null);
    //g.drawImage(Start, 460, 500, null);
    public void actionPerformed(ActionEvent e)
    Object src = e.getSource();
    if (src == startButton)
    exit.tap();
    public void checkSystemInput()
    if (exit.isPressed())
    stop();
    public void stop()
    isRunning = false;
    public void createGameActions()
    exit = new GameAction("exit",
    GameAction.DETECT_INITAL_PRESS_ONLY);
    inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
    public JButton createButton(String name)
    // load the image
    String imagePath = name;
    ImageIcon iconRollover = new ImageIcon(imagePath);
    int w = iconRollover.getIconWidth();
    int h = iconRollover.getIconHeight();
    // get the cursor for this button
    Cursor cursor =
    Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
    // make translucent default image
    /*Image image = screen.createCompatibleImage(w, h);*/
    Graphics2D g = screen.getGraphics();
    /*g.drawImage(iconRollover.getImage(), 0, 0, null);*/
    // create the button
    JButton button = new JButton();
    button.addActionListener(this);
    button.setIgnoreRepaint(true);
    button.setFocusable(false);
    button.setBorder(null);
    button.setContentAreaFilled(false);
    button.setCursor(cursor);
    button.setIcon(iconRollover);
    button.setRolloverIcon(iconRollover);
    button.setPressedIcon(iconRollover);
    return button;
    }

    1) Swing related questions should be posted in the Swing forum
    2) Use the "code" formatting tags when posting code so the code is readable.
    3) Post [url http://www.physci.org/codes/sscce.jsp]Simple, Executable Sample that shows your problem. The code you posted uses non-standard API's so we can't execute your code to see the incorrect behaviour.
    4) Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]How to Use Buttons. Or maybe the section on "How to Use Layout Managers" will solve your problem. Either way read the tutorial.

  • Help needed in creating a simple paint application

    I want to create a simple paint application using swings in java, i am able to draw different shapes using mouse but the problem is when i select some other shape it simply replaces the already drawn object with the new one but i want the already drawn object also, like appending, what should be done for this, any logic missing here or i should use some other approach?
    Please help me
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class bmp extends JFrame implements MouseListener, MouseMotionListener,
              ActionListener {
         int w, h;
         int xstart, ystart, xend, yend;
         JButton elipse = new JButton("--Elipse--");
         JButton rect = new JButton  ("Rectangle");
         JPanel mainframe = new JPanel();
         JPanel buttons = new JPanel();
         String selected="no";
         public void init() {
              //super("Bitmap Functions");
              // display.setLayout(new FlowLayout());
              buttons.setLayout(new BoxLayout(buttons,BoxLayout.Y_AXIS));
              buttons.add(Box.createRigidArea(new Dimension(15,15)));
              buttons.add(elipse);
              buttons.add(Box.createRigidArea(new Dimension(0,15)));
              buttons.add(rect);
              Container contentpane = getContentPane();
              contentpane.add(buttons, BorderLayout.WEST);
              //getContentPane().add(display, BorderLayout.WEST);
              addMouseListener(this); // listens for own mouse and
              addMouseMotionListener(this); // mouse-motion events
              setSize(1152, 834);
              elipse.addActionListener(this);
              rect.addActionListener(this);
              setVisible(true);
         public void mousePressed(MouseEvent event) {
              xstart = event.getX();
              ystart = event.getY();
         public void mouseReleased(MouseEvent event) {
              xend = event.getX();
              yend = event.getY();
              repaint();
         public void mouseEntered(MouseEvent event) {
              //repaint();
         public void mouseExited(MouseEvent event) {
              //repaint();
         public void mouseDragged(MouseEvent event) {
              xend = event.getX();
              yend = event.getY();
              repaint();
         public void mouseMoved(MouseEvent event) {
              //repaint();
         public static void main(String args[]) {
              bmp application = new bmp();
              application.init();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public void mouseClicked(MouseEvent arg0) {
         public void actionPerformed(ActionEvent event) {
              if (event.getSource() == elipse) {
                   selected = "elipse";
                   repaint();
              else if(event.getSource() == rect)
                   selected = "rectangle";
                   repaint();
         public void paint(Graphics g) {
              System.out.println(selected);
              super.paint(g); // clear the frame surface
              bmp b=new bmp();
              if (selected.equals("elipse"))
                   w = xend - xstart;
                   h = yend - ystart;
                   if (w < 0)
                        w = w * -1;
                   if (h < 0)
                        h = h * -1;
                   g.drawOval(xstart, ystart, w, h);
              if (selected.equals("rectangle"))
                   w = xend - xstart;
              h = yend - ystart;
              if (w < 0)
                   w = w * -1;
              if (h < 0)
                   h = h * -1;
              g.drawRect(xstart, ystart, w, h);
    }

    bvivek wrote:
    ..With this code, when i draw an elipse or line the image doesnt start from the point where i click the mouse. It added the MouseListener to the wrong thing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener
           static BufferedImage image;
           Color color;
           Point start=new Point();
           Point end =new Point();
           JButton elipse=new JButton("Elipse");
           JButton rectangle=new JButton("Rectangle");
           JButton line=new JButton("Line");
           String selected;
           public test_bmp()
                   color = Color.black;
                   setBorder(BorderFactory.createLineBorder(Color.black));
           public void paintComponent(Graphics g)
                   //super.paintComponent(g);
                   g.drawImage(image, 0, 0, this);
                   Graphics2D g2 = (Graphics2D)g;
                   g2.setPaint(Color.black);
           if(selected=="elipse")
                   g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
                   System.out.println("paintComponent() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
                   System.out.println("Start : "+start.x+","+start.y);
                   System.out.println("End   : "+end.x+","+end.y);
           if(selected=="line")
                   g2.drawLine(start.x,start.y,end.x,end.y);
           //Draw on Buffered image
           public void draw()
           Graphics2D g2 = image.createGraphics();
           g2.setPaint(color);
                   System.out.println("draw");
           if(selected=="line")
                   g2.drawLine(start.x, start.y, end.x, end.y);
           if(selected=="elipse")
                   g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
                   System.out.println("draw() "+start.getX()+","+start.getY()+","+(end.getX()-start.getX())+","+(end.getY()-start.getY()));
                   System.out.println("Start : "+start.x+","+start.y);
                   System.out.println("End   : "+end.x+","+end.y);
           repaint();
           g2.dispose();
           public JPanel addButtons()
                   JPanel buttonpanel=new JPanel();
                   buttonpanel.setBackground(color.lightGray);
                   buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
                   elipse.addActionListener(this);
                   rectangle.addActionListener(this);
                   line.addActionListener(this);
                   buttonpanel.add(elipse);
                   buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
                   buttonpanel.add(rectangle);
                   buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
                   buttonpanel.add(line);
                   return buttonpanel;
           public static void main(String args[])
                    test_bmp application=new test_bmp();
                    //Main window
                    JFrame frame=new JFrame("Whiteboard");
                    frame.setLayout(new BorderLayout());
                    frame.add(application.addButtons(),BorderLayout.WEST);
                    frame.add(application);
                    application.addMouseListener(application);
                    application.addMouseMotionListener(application);
                    //size of the window
                    frame.setSize(600,400);
                    frame.setLocation(0,0);
                    frame.setVisible(true);
                    int w = frame.getWidth();
                int h = frame.getHeight();
                image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = image.createGraphics();
                g2.setPaint(Color.white);
                g2.fillRect(0,0,w,h);
                g2.dispose();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           @Override
           public void mouseClicked(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mouseEntered(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mouseExited(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void mousePressed(MouseEvent event)
                   start = event.getPoint();
           @Override
           public void mouseReleased(MouseEvent event)
                   end = event.getPoint();
                   draw();
           @Override
           public void mouseDragged(MouseEvent e)
                   end=e.getPoint();
                   repaint();
           @Override
           public void mouseMoved(MouseEvent arg0) {
                   // TODO Auto-generated method stub
           @Override
           public void actionPerformed(ActionEvent e)
                   if(e.getSource()==elipse)
                           selected="elipse";
                   if(e.getSource()==line)
                           selected="line";
                   draw();
    }

  • JPG or GIF on GUI

    Hello!
    Does anyone know how i could show an image in a java.awt frame? (no swing)
    Thank you very much!!!

    Hi,
    a very strange thing happened, i found a way to do it, based on a combination of both of your answers, and it worked... at least, 3 times it did. Now my getGraphics() method returns null!!???
    and it doesn't draw anything anymore ofcourse :(
    class GUI extends Frame implements ActionListener, TextListener
            protected Image PICTURE = null;
            public GUI()
                PictureViewer("1.JPG",50,600);
            public void PictureViewer(String strFilename, int x, int y)
              if(strFilename.length() < 1)
                   System.out.println("USAGE: java PictureViewer <filename>");
              try
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                   PICTURE = toolkit.getImage(strFilename);
                   Graphics g = this.getGraphics();
                   System.out.println("graphics = " +g);
                   paint(g,x,y);
              catch(Exception e){System.out.println("Error at drawing picture");e.printStackTrace();}
         public void paint(Graphics g,int x, int y)
              if(g != null && PICTURE != null)
                   g.drawImage(PICTURE,x,y,this);
    }Is there something wrong?
    Thanks allready!

  • Extra quote is generated for "footer" facet in data_table

    I put the following into data_table in result-set.jsp:
    <f:facet name="footer">
      <h:output_text  value="Footer"/>
    </f:facet>Extra quote is generated before "Footer". Here is the generated HTML fragment:
    <tfoot><tr><td colspan="4">"
    Footer</td></tr></tfoot>

    Strange, I use a footer facet in my data_table, but I do not see this bug
    This is my data_table:
    <h:data_table id="items"
    value="#{ShoppingCartController.shoppingCart.lineItems}" var="item"
    styleClass="tablePanel" footerClass="tableFooter" headerClass="tableHeader"
    columnClasses="nameColumn,priceColumn,descriptionColumn,quantityColumn,priceColumn,buttonColumn,buttonColumn"
    rendered="#{ShoppingCartController.shoppingCart.isCartNotEmpty}">
    <h:column>
    <f:facet name="header">
    <h:output_text value="Name"/>
    </f:facet>
    <h:output_text value="#{item.name}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:output_text value="Price"/>
    </f:facet>
    <h:output_text value="#{item.price}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:output_text value="Description"/>
    </f:facet>
    <h:output_text value="#{item.description}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:output_text value="Quantity"/>
    </f:facet>
    <h:input_text id="quantityField" value="#{item.quantity}" size="5" maxlength="4"/>
    <f:facet name="footer">
    <h:output_text value="CartTotal"/>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:output_text value="Total"/>
    </f:facet>
    <h:output_text value="#{item.total}"/>
    <f:facet name="footer">
    <h:output_text value="#{ShoppingCartController.shoppingCart.cartTotal}"/>
    </f:facet>
    </h:column>
    <h:column>
    <h:command_button actionListener="#{ShoppingCartController.updateItemInCart}"
    image="images/updateicon.gif"
    immediate="true"/>
    </h:column>
    <h:column>
    <h:command_button actionListener="#{ShoppingCartController.removeItemFromCart}"
    image="images/deleteicon.gif"
    immediate="true"/>
    </h:column>
    </h:data_table>

  • Trouble creating random ovals

    Hello all, as much as I hate having to look really stupid, I am a nooby and I am stuck. I am trying to create randomly placed ovals by pressing my jbutton to seem as though the image is being erased. I have tried different scenarios and have read my text many times. My courses are via online and I am more of a hands on learner. I am not looking for anybody to do my work for me, I would just like to be pointed in the right direction please. I keep getting an error message in my action performed methd (cannot find symbol g (in g.filloval)). Can someone point me to a tutorial for this or point out my mistakes please, any help is greatly appreciated. Thank!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JEraseImage extends JApplet implements ActionListener
    private ImageIcon image = new ImageIcon ("pins.jpg");
    private int Width, Height;
    Container con = getContentPane();
    JLabel greeting = new JLabel ("If you don't like what you see");
    Font headlineFont = new Font ("Helvetica", Font.BOLD, 20);
    JButton eraseMe = new JButton ("Erase Me");
    Image pins;
          public void init() 
         greeting.setFont (headlineFont);
            con.add(greeting);
         con.add(eraseMe);
         con.setLayout(new FlowLayout());      
         pins = getImage(getCodeBase(),"pins.jpg");
            eraseMe.addActionListener(this);      
         public void paint (Graphics g)
         g.drawImage(pins, 0, 30, this);
         g.setColor(Color.WHITE);
         g.fillOval(70, 30, 100, 60);
         for(int count = 0; count < 20; ++count)
            int x = (int) (Math.random() * Width) + 0;
            int y = (int) (Math.random() * Height) + 30;
            g.fillOval(x, y, 10, 10);
         eraseMe.repaint();
         public void actionPerformed(ActionEvent eraseMe)
         g.filloval.repaint(); //also tried eraseMe.repaint();
    }Edited by: stillearning on Nov 20, 2007 7:03 PM

    I have the latest version, at least as a month ago anyways. The eraseMe is supposed to create the filled ovals when the jbutton is clicked so it will seem to erase the imageicon already in place. I tried changing to lower case o in filloval and it didn't compile but it did when I kept them uppercase. I managed to place one oval over the image in the paint method but that's as far as I seem to get. I'm guessing I went wrong somewhere in the for loop? I tested a string event in the action performed event and that worked just fine so I know my jbutton is active.
    Here is the adjusted code:
    public void paint (Graphics g)
         g.drawImage(pins, 0, 30, this);
         g.setColor(Color.WHITE);
         g.fillOval(70, 30, 100, 60);
         for(int count = 0; count < 20; ++count)
            int x = (int) (Math.random() * Width) + 0;
            int y = (int) (Math.random() * Height) + 30;
            g.fillOval(x, y, 10, 10);
         public void actionPerformed(ActionEvent eraseMe)
         repaint();
    }

  • First,last next previous,save, delete,execute,find.

    experts,
    am using jdev 11.1.1.4.0
    in jdeveloper has buttons like such as first,last next previous,save, delete,execute,find.
    what my question is?
    is it possible to do this?
    i don't want these buttons,
    instead of the buttons -- i needed icons. for doing same operation.
    for explaination,
    let us, take an eg:
    In jdeveloper we do some changes in designing or may coding part.
    after then, our hand moves to save these changes.so press save icons to save all of them.
    this is my point.
    when the user make all entry in my ui.he want to save the datas by not pressing buttons. by pressing save icons. (i.e) floppy disk icons. in our tool bar
    i want that save icons instead of save button doing same operation.
    like wise
    i want these operation undo ,redo,first,last,next.previous. not in button. only icons. do these operations.
    if it's possible can one show the way.
    r else paste link
    how to do this?
    Edited by: subu123 on Jul 25, 2011 2:40 AM
    Edited by: subu123 on Jul 25, 2011 2:48 AM

    Hi,
    In our application we use the "af:commandToolbarButton" component but instead of the "text" property you use the "icon" and "disabledIcon" properties.
    <af:commandToolbarButton shortDesc="the tooltip"
                                         id="button
                                         actionListener="#{yourAction}"
                                         icon="/images/yourIcon.png"
                                         disabledIcon="/images/yourDisabledIcon.png"/>
    </af:commandToolbarButton>Gabriel.

  • Componet visibility

    Hi
    I need to get a new frame with different components on it. I've added a JButton and a JLabel to the new frame. It seems like the JLabel lies upon the JButton and makes the JButton not visible for the user. The button is shown when I moves the mouse over it. I have tried to twist the code around so that the JLabel is drawn first and afterwards the button. But that doesn't help. Any sugestions?
    package box;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.sql.*;
    public class graphForm extends JFrame implements Runnable, ActionListener {
      BufferedImage bufferedImage;
    //  Image buffer; //Picturebuffer
    //  Graphics bufferGfx; //Reference to the picturebuffers drawingtool
      dbInterface db;
      Connection dbConn;
      int h = 200;
      int w = 400;
      public graphForm() {
        // Super calls the parent constructor to set the frames name
        super("Temperature");
        jbInit();
        db = new dbInterface();
        dbConn = db.dbConnect();
      private void jbInit() {
        JButton jButtonClose = new JButton("Close window");
        jButtonClose.addActionListener(this);
        // Close this frame when parent closes
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setLayout(new XYLayout());
        // Adds a empty label to the frame to give the frame a size
        JLabel emptyLabel = new JLabel("");
        emptyLabel.setPreferredSize(new Dimension(w, h));
        // Put the components on the contentpane
        contentPane.add(emptyLabel, BorderLayout.CENTER);
        contentPane.add(jButtonClose, new XYConstraints(20, 160, 140, 20));
        //Display the window
        this.pack();
        // Set the window in middle of the screen
        this.setLocationRelativeTo(null);
        this.setVisible(true);
      public void run() {
        System.out.println("graphForm thread started");
        while(true) {
          try {
            Thread.currentThread().sleep(1000);
          catch (InterruptedException ex) {
          // Get new data values
          upDataGraph();
       * upDataGraph
      private void upDataGraph() {
        repaint();
      public void paint(Graphics g) {
        System.out.println("paint");
        int offsetX = 4;
        int offsetY = 30;
        Graphics2D graphics2D = (Graphics2D) g;
        bufferedImage = new BufferedImage(w + offsetX, h + offsetY, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setPaint(Color.LIGHT_GRAY);
        graphics.fillRect(offsetX, offsetY, w, h);
        graphics.dispose();
        g.drawImage(bufferedImage, 0, 0, this);
      public void actionPerformed(ActionEvent e) {
        // When ButtonClose is pressed close the window and release ressources
        setVisible(false);
        dispose();
    }

    You are thinking on the lines of If I take a sheet of paper, and put it on the table, and then take a smaller sheet of paper, and place that over the small sheet of paper, what do I see. In my exprence, Java does not work like this.
    Its zordering is screwy. And by screwy I mean borked (this was in 1.4), you would need to use GlassPane. In 1.5 I understand it has been fixed (but I have not used it) using Container.setComponentZOrder.

  • Rotate dragged shape on button click

    Hi guys,
    I need help here. I want to do a drawing application where user can resize and rotate a shape. I have created a shape which I can drag around but how to make it rotate upon clicking on button?? Let say when I select the shape and click on 'rotate' button my shape will be rotate by 90 degree. After that the rotated shape can still be drag. Any help would be appreciated.

    Hi Darryl.Burke,
    Thanks for your reply, yes I use AffineTransform methods to rotate the shape. Is there any different with other rotation method?? Ok when I use setToRotation, the shape indeed rotate to the correct position but when I click the shape return back to its original and other weird things happen. Below is the code. Can you please point out the part that I done it wrong please. Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.border.CompoundBorder;
    import java.io.*;
    public class RotateShape
         private static void createAndShowGUI() {
            //Create and set up the window.
           JFrame.setDefaultLookAndFeelDecorated(true);      
           Viewer frame = new Viewer();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setVisible(true);
        public static void main(String[] args)
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
    class Viewer extends JFrame implements ActionListener
         JMenuBar menuBar;
         drawRect buildDesign;
        public Viewer()
           Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int screenHeight = screenSize.height;
            int screenWidth = screenSize.width;
            // center frame in screen
              setSize(700, 600);
              setLocation(screenWidth / 4, screenHeight / 4);
              setResizable(false);
            buildDesign = new drawRect();
            buildDesign.setBorder(BorderFactory.createEmptyBorder(0, 2, 3, 3));
            JTabbedPane tabbed = new JTabbedPane();
            tabbed.addTab("Design", buildDesign);
            //tabbed.addTab("Viewer", buildViewer());
            tabbed.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                tabbed.getBorder()));
            //------------------------End of Tabbed Pane----------------------------------------------------//
          JPanel pane = new JPanel();
          Button rectButton = new Button("Rect");
          rectButton.addActionListener(this);
          pane.add(rectButton);
          Button deleteButton = new Button("Delete");
          deleteButton.addActionListener(this);
          pane.add(deleteButton);
          Button rotateButton = new Button("Rotate");
          rotateButton.addActionListener(this);
          pane.add(rotateButton);
          JScrollPane scroller = new JScrollPane(pane);
          scroller.setOpaque(false);
          scroller.getViewport().setOpaque(false);
          scroller.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                  scroller.getBorder()));
               //------------------------End of Build Item list----------------------------------------------//
          JPanel content = new JPanel(new BorderLayout());
          content.setOpaque(false);
          content.add(tabbed, BorderLayout.CENTER);
          content.add(scroller, BorderLayout.WEST);
          add (content, BorderLayout.CENTER);
          //------------------------End of add content----------------------------------------------//
              public void actionPerformed(ActionEvent evt) {
               // Respond to a command from one of the window's menu.
          String command = evt.getActionCommand();
          if (command.equals("Rect"))
             buildDesign.addShape(new RectShape());
          else if (command.equals("Delete"))
             buildDesign.delete();
          else if (command.equals("Rotate"))
             buildDesign.rotate();
    class drawRect extends JPanel implements ActionListener, MouseListener, MouseMotionListener
             Image offScreenCanvas = null;   // off-screen image used for double buffering
                 Graphics offScreenGraphics;     // graphics context for drawing to offScreenCanvas
                 Vector shapes = new Vector();   // holds a list of the shapes that are displayed on the canvas
                 Color currentColor = Color.black; // current color; when a shape is created, this is its color
                 float alpha;
            drawRect() {
            // Constructor: set background color to white set up listeners to respond to mouse actions
          setBackground(Color.white);
          addMouseListener(this);
          addMouseMotionListener(this);
       synchronized public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            // In the paint method, everything is drawn to an off-screen canvas, and then
            // that canvas is copied onto the screen.
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
          makeOffScreenCanvas();
          g2.drawImage(offScreenCanvas,0,0,this); 
          AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OUT,alpha);
              g2.setComposite(composite);
          g2.setColor(Color.GRAY);
          drawGrid(g, 20); 
       public void update(Graphics g) {
            // Update method is called when canvas is to be redrawn.
            // Just call the paint method.
          super.paintComponent(g);
       void makeOffScreenCanvas() {
             // Erase the off-screen canvas and redraw all the shapes in the list.
             // (First, if canvas has not yet been created, then create it.)
          if (offScreenCanvas == null) {
             offScreenCanvas = createImage(getSize().width,getSize().height);
             offScreenGraphics = offScreenCanvas.getGraphics();
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
          int top = shapes.size();
          for (int i = 0; i < top; i++) {
             Shape s = (Shape)shapes.elementAt(i);
             s.draw(offScreenGraphics);
            private void drawGrid(Graphics g, int gridSpace) {
          Insets insets = getInsets();
          int firstX = insets.left;
          int firstY = insets.top;
          int lastX = getWidth() - insets.right;
          int lastY = getHeight() - insets.bottom;
          //Draw vertical lines.
          int x = firstX;
          while (x < lastX) {
            g.drawLine(x, firstY, x, lastY);
            x += gridSpace;
          //Draw horizontal lines.
          int y = firstY;
          while (y < lastY) {
            g.drawLine(firstX, y, lastX, y);
            y += gridSpace;
        public void actionPerformed(ActionEvent evt)
         synchronized void addShape(Shape shape) {
              // Add the shape to the canvas, and set its size/position and color.
              // The shape is added at the top-left corner, with size 50-by-30.
              // Then redraw the canvas to show the newly added shape.
          shape.setColor(Color.red);
          shape.setColor(currentColor);
           shape.reshape(3,3,70,10);
          shapes.addElement(shape);
          repaint();
         void clear() {
             // remove all shapes
           shapes.setSize(0);
           repaint();
        void delete() {
             // remove selected shapes
                  shapes.removeElement(selectedShape);
                   repaint();
       void rotate() {     
                     //shapes.addElement(selectedShape);
                  selectedShape.setToRotate(true);
                  //shapes.removeElement(selectedShape);
                   repaint();
       Shape selectedShape = null;
       Shape shapeBeingDragged = null;  // This is null unless a shape is being dragged.
                                        // A non-null value is used as a signal that dragging
                                        // is in progress, as well as indicating which shape
                                        // is being dragged.
       int prevDragX;  // During dragging, these record the x and y coordinates of the
       int prevDragY;  //    previous position of the mouse.
        Shape clickedShape(int x, int y) {
             // Find the frontmost shape at coordinates (x,y); return null if there is none.
          for ( int i = shapes.size() - 1; i >= 0; i-- ) {  // check shapes from front to back
             Shape s = (Shape)shapes.elementAt(i);
             if (s.containsPoint(x,y))
                  s.tickSelected(true);
                  selectedShape = s;
                return s;
                else
                s.tickSelected(false);
                repaint();
          return null;
       synchronized public void mousePressed(MouseEvent evt) {
             // User has pressed the mouse.  Find the shape that the user has clicked on, if
             // any.  If there is a shape at the position when the mouse was clicked, then
             // start dragging it.  If the user was holding down the shift key, then bring
             // the dragged shape to the front, in front of all the other shapes.
          int x = evt.getX();  // x-coordinate of point where mouse was clicked
          int y = evt.getY();  // y-coordinate of point                                  
             shapeBeingDragged = clickedShape(x,y);
             if (shapeBeingDragged != null) {
                prevDragX = x;
                prevDragY = y;
                if (evt.isShiftDown()) {                 // Bring the shape to the front by moving it to
                   shapes.removeElement(shapeBeingDragged);  //       the end of the list of shapes.
                   shapes.addElement(shapeBeingDragged);
                   repaint();  // repaint canvas to show shape in front of other shapes
       synchronized public void mouseDragged(MouseEvent evt) {
              // User has moved the mouse.  Move the dragged shape by the same amount.
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
       synchronized public void mouseReleased(MouseEvent evt) {
              // User has released the mouse.  Move the dragged shape, then set
              // shapeBeingDragged to null to indicate that dragging is over.
              // If the shape lies completely outside the canvas, remove it
              // from the list of shapes (since there is no way to ever move
              // it back onscreen).
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
                     shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
                     shapeBeingDragged.top + shapeBeingDragged.height < 0 ) {  // shape is off-screen
                shapes.removeElement(shapeBeingDragged);  // remove shape from list of shapes
             shapeBeingDragged = null;
             repaint();
       public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
       public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
       public void mouseMoved(MouseEvent evt) { }
       public void mouseClicked(MouseEvent evt) { }
       abstract class Shape implements Serializable{
          // A class representing shapes that can be displayed on a ShapeCanvas.
          // The subclasses of this class represent particular types of shapes.
          // When a shape is first constucted, it has height and width zero
          // and a default color of white.
       int left, top;      // Position of top left corner of rectangle that bounds this shape.
       int width, height;  // Size of the bounding rectangle.
       Color color = Color.white;  // Color of this shape.
       boolean isSelected;
       boolean isRotate;
       AffineTransform t;
       AffineTransform origTransform;
       void reshape(int left, int top, int width, int height) {
             // Set the position and size of this shape.
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
       void moveTo(int x, int y) {
              // Move upper left corner to the point (x,y)
          this.left = x;
          this.top = y;
       void moveBy(int dx, int dy) {
              // Move the shape by dx pixels horizontally and dy pixels veritcally
              // (by changing the position of the top-left corner of the shape).
          left += dx;
          top += dy;
       void setColor(Color color) {
              // Set the color of this shape
          this.color = color;
       void tickSelected (boolean draw) {
                 // If true, a red outline is drawn around this shape.
             isSelected = draw;
       void setToRotate (boolean draw) {
                 // If true, the shape will rotate 90 deg
             isRotate = draw;
       boolean containsPoint(int x, int y) {
             // Check whether the shape contains the point (x,y).
             // By default, this just checks whether (x,y) is inside the
             // rectangle that bounds the shape.  This method should be
             // overridden by a subclass if the default behaviour is not
             // appropriate for the subclass.
          if (x >= left && x < left+width && y >= top && y < top+height)
             return true;
          else
                      return false;
       abstract void draw(Graphics g); 
             // Draw the shape in the graphics context g.
             // This must be overriden in any concrete subclass.
         }  // end of class Shape
    class RectShape extends Shape {
          // This class represents rectangle shapes.
       void draw(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            Rectangle2D wall = new Rectangle2D.Double(left,top,width,height);
            Rectangle2D border = new Rectangle2D.Double(left-2,top-2,width+3,height+3);
            origTransform = g2.getTransform();
            if ((isRotate) && (isSelected))
                   t = new AffineTransform();
                      t.setToRotation ((Math.toRadians (90)),(left+width/2) , (top+height/2) );
                      g2.transform(t);
                      g2.setColor(color);
                   g2.fill(wall);
                   g2.setColor(Color.red);
                    g2.draw(border);
                    g2.setTransform( origTransform );
                    return;
            else
                 g2.setColor(color);
              g2.fill(wall);
            if ((isSelected)&& !(isRotate))
                         g2.setColor(Color.red);
                         g2.draw(border);
                              else
                                   g2.setColor(Color.black);
                                   g2.draw(wall);
    }

  • HELP!!! save position of the components!!!

    Hi!
    I have a JLayeredPane where I insert some images. I move this images. BUT when I press a button (that invoke a ActionListener) all the images return at initial position!!!
    THE PROGRAM:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.text.*; //per StyledDocument
    import javax.swing.BorderFactory;
    import javax.imageio.*;
    public class mio implements ActionListener,MouseMotionListener,MouseListener{
    JTextArea statusInfo; //info da passare a PROGRAMMA TODO
    JTextArea PASpar; // PARAMETRI X TODO
    JTextArea PASimage; //IMMAGINI X TODO
    Color whitex = new Color(255,255,255);
    Color bluex = new Color(100,105,170);
    Color bluexx = new Color(100,150,170);
    Color redx = new Color(255,0,0);
    JFrame frame; //contiene tutto
    JFrame frameP;
    JMenuBar menu;
    JMenu fileMenu;
    JMenuItem nuovo;
    JMenuItem apriimgf;
    JMenuItem aprimosf;
    JMenuItem salva;
    JMenuItem stampa;
    JMenuItem esci;
    JMenu modMenu;
    JMenuItem annulla;
    JMenu helpMenu;
    JMenuItem help;
    JPanel panel; //contiene oggetti entro menu
    JPanel panel2;
    JPanel panel3; //xbottoni
    JLayeredPane pane;
    JTextArea spiega;
    JTextArea dico2;
    JLayeredPane panelpane; //dove carico img
    JButton apriimg;
    JButton chiudi;
    JButton aprimos;
    JButton ok;
    JButton mosaica;
    JButton superR;
    JButton salvab;
    JButton migliora;
    JButton nuovob;
    int _dragFromX = 0;    // pressed this far inside ball's
    int _dragFromY = 0;
    boolean _canDrag  = false;
    int i;
    int px;
    int py;
    int mousex;
    int mousey;
    int rifno;//x img d riferimento
    int scelta; //1 = immagini 2=mosaico
    int Nimg; // NUMERO IMG KE INSERISCO <= 12
    JLabel image;
    ImageIcon icon;
    int ximg, yimg; //posizione img in panel
    int xgrid,ygrid; //griglia panel
    int[] ximgs,yimgs; //x,y img
    JLabel[] images;
    int hicon,wicon; //h w img
    int[] wimgs,himgs;
    int muovi; //img da muovere nell'array
         public final static int ONE_SECOND = 500; ////
         private JProgressBar progressBar;
         private javax.swing.Timer timer;
         private JButton startButton;
         private LongTask task;
         private JTextArea taskOutput;
    static private String newline = "\n";
    // =================== MAIN
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    mio m = new mio();
    /*public static void main(String argv[]){
         mio m = new mio();
    // ================ COSTRUTTORE
    public mio(){
         rifno = 0;//no img d rif
         Nimg = 0;
         frame = new JFrame("interfaccia");
         PASpar = new JTextArea();
         PASimage = new JTextArea();
         menu = new JMenuBar();
         menu.setOpaque(true);
         menu.setBackground(bluex);
         // ********* Menu file *********
         fileMenu = new JMenu("File");
         fileMenu.setMnemonic(KeyEvent.VK_F);
         nuovo = new JMenuItem("Nuovo");
         nuovo.setMnemonic(KeyEvent.VK_N);
         apriimgf = new JMenuItem("Apri immagini");
    apriimgf.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK)); //alt+1
         aprimosf = new JMenuItem("Apri mosaico");
    salva = new JMenuItem("Salva");
         salva.setMnemonic(KeyEvent.VK_S);
         esci = new JMenuItem("Esci");
         esci.setMnemonic(KeyEvent.VK_E);
         //********* Menu Modifica ***********
         modMenu = new JMenu("Modifica");
         modMenu.setMnemonic(KeyEvent.VK_M);
         annulla = new JMenuItem("Annulla");
         annulla.setMnemonic(KeyEvent.VK_A);
         // ********* Help Menu *************
         helpMenu = new JMenu("HELP");
         help = new JMenuItem("Help");
         menu.add(fileMenu);
         fileMenu.add(nuovo);
         fileMenu.add(apriimgf);
         fileMenu.add(aprimosf);
         fileMenu.add(salva);
         fileMenu.addSeparator();
         fileMenu.addSeparator();
         fileMenu.add(esci);
         menu.add(modMenu);
         modMenu.add(annulla);
         menu.add(helpMenu);
         helpMenu.add(help);
         // ActionListener x ogni voce d menu
         nuovo.addActionListener(this);
         apriimgf.addActionListener(this);
         aprimosf.addActionListener(this);
         salva.addActionListener(this);
         esci.addActionListener(this);
         annulla.addActionListener(this);
         help.addActionListener(this);
         frame.setJMenuBar(menu);//in frame menu
         panel=new JPanel(new BorderLayout(2,2));
         frame.getContentPane().add(panel);
         spiega = new JTextArea(" 1. Aprire TUTTE le immagini da mosaicare"+ newline +" Oppure il mosaico da migliorare"+newline,3,40);
         spiega.setEditable(false);
         spiega.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
         spiega.setBackground(bluex);
         panelpane = new JLayeredPane();
         panelpane.setPreferredSize(new Dimension(900,550));
         panelpane.setBackground(whitex);
         panelpane.setLayout(new GridLayout(0,4)); //max 12 img e occupano tutto subito
         panelpane.setBorder(BorderFactory.createLineBorder(Color.black));
         panelpane.addMouseListener(this);
         panelpane.addMouseMotionListener(this);
         xgrid = 225;
         ygrid =183;
         ximg = 0;
         yimg = 0;
         images = new JLabel[12];//immagini
         ximgs = new int[12];
         yimgs = new int[12];
         wimgs = new int[12];
         himgs = new int[12];
         panel3= new JPanel();
         panel3.setBackground(bluex);
         panel3.setLayout(new BoxLayout(panel3, BoxLayout.Y_AXIS));
         panel3.setBorder(BorderFactory.createLineBorder(Color.black));
         chiudi = new JButton("Chiudi applicazione");
         chiudi.addActionListener(this);
         chiudi.setBackground(bluex);
         // ******* 1 FRAME
         apriimg = new JButton("Apri immagine");
         apriimg.addActionListener(this);
         apriimg.setBackground(bluex);
         aprimos = new JButton("Apri mosaico");
         aprimos.addActionListener(this);
         aprimos.setBackground(bluex);
         ok = new JButton("Prosegui");
         ok.addActionListener(this);
         ok.setBackground(bluex);
         ok.setEnabled(false); //disabilito
         //****** 2 frame
         mosaica = new JButton(" Mosaica ");
         mosaica.addActionListener(this);
         mosaica.setBackground(bluex);
         mosaica.setVisible(false);
         superR = new JButton("Super-Risoluzione");
         superR.addActionListener(this);
         superR.setBackground(bluex);
         superR.setVisible(false);
         // ********* 3 frame
         salvab = new JButton(" Salva mosaico ");
         salvab.addActionListener(this);
         salvab.setBackground(bluex);
         salvab.setVisible(false);
         migliora = new JButton(" Migliora mosaico ");
         migliora.addActionListener(this);
         migliora.setBackground(bluex);
         migliora.setVisible(false);
         nuovob = new JButton(" Nuovo progetto ");
         nuovob.addActionListener(this);
         nuovob.setBackground(bluex);
         nuovob.setVisible(false);
         statusInfo = new JTextArea(3,40);
         statusInfo.setBorder(BorderFactory.createLineBorder(Color.black));
         statusInfo.setBackground(bluex);
         JScrollPane scrollArea = new JScrollPane(statusInfo);
         panel.add((spiega), BorderLayout.NORTH);
         panel.add((panelpane), BorderLayout.CENTER);
         panel.add((panel3), BorderLayout.EAST);
         panel.add((scrollArea), BorderLayout.SOUTH);
         panel3.add(apriimg);
         panel3.add(salvab);//3 frame
         panel3.add(new JSeparator(JSeparator.HORIZONTAL));
         panel3.add(aprimos);
         panel3.add(mosaica); // 2 frame
         panel3.add(migliora);
         panel3.add(new JSeparator(JSeparator.HORIZONTAL));
         panel3.add(ok);
         panel3.add(superR); // 2 frame
         panel3.add(nuovob); // 3 frame
         panel3.add(new JSeparator(JSeparator.HORIZONTAL));
         panel3.add(chiudi);
         frame.pack();
         frame.setVisible(true);
         frame.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                   System.exit(0);
    }// chiude costruttore
    // ================ metti mosaico
         public void mettiMosaico(){
              panelpane.removeAll();
              ImageIcon img1 = new ImageIcon("mosaico.jpg");
              Image imgesize1 = resize2Icon("mosaico.jpg"); // resize
              img1 = new ImageIcon(imgesize1);
              JLabel image1 = new JLabel(img1);
              image1.setLocation(200,10);
              panelpane.add(image1);
              panelpane.repaint();
    // ================= RESIZE MOSAICO
         public Image resize2Icon(String image){
         Image img;
              Image inImage = new ImageIcon(image).getImage();
              int maxDim = 500;
              double scale = (double) maxDim / (double) inImage.getHeight(null);
              if (inImage.getWidth(null) > inImage.getHeight(null))
                   scale = (double) maxDim / (double) inImage.getWidth(null);
              // Determine size of new image.
              //One of them
              // should equal maxDim.
              int scaledW = (int) (scale * inImage.getWidth(null));
              int scaledH = (int) (scale * inImage.getHeight(null));
              System.out.println(">> "
                   + inImage.getSource().getClass()
                   + " aspect ratio = "
                   + scaledW + " , " + scaledH);
              img = inImage.getScaledInstance(scaledW , scaledH, Image.SCALE_SMOOTH);
         return img;
    // ================= RESIZE IMAGES
    public Image resizeIcon(String image){
         Image img;
              Image inImage = new ImageIcon(image).getImage();
              int maxDim = 180;
              double scale = (double) maxDim / (double) inImage.getHeight(null);
              if (inImage.getWidth(null) > inImage.getHeight(null))
                   scale = (double) maxDim / (double) inImage.getWidth(null);
              // Determine size of new image.
              //One of them
              // should equal maxDim.
              int scaledW = (int) (scale * inImage.getWidth(null));
              int scaledH = (int) (scale * inImage.getHeight(null));
              System.out.println(">> "
                   + inImage.getSource().getClass()
                   + " aspect ratio = "
                   + scaledW + " , " + scaledH);
              img = inImage.getScaledInstance(scaledW , scaledH, Image.SCALE_SMOOTH);
              return img;
    // ================== img RIFERIMENTO
         public void imgRif(){
              frameP.setVisible(false);//tolgo frame
              rifno=1;
              spiega.setText (" Con il mouse indicare l'immagine di riferimento"+newline);
         }//fine imgRif
    // ================== BARRA PROGRESS
         public void barraP(){
              final JFrame framePb = new JFrame("ELABORAZIONE in corso");
              framePb.setSize(300,1000);
              framePb.setBackground(bluex);
              statusInfo.append(" Elaborazione in corso... "+newline);
              JPanel panelPb=new JPanel(new BorderLayout());
              panelPb.setBackground(bluex);
              panelPb.setBorder(BorderFactory.createLineBorder(Color.black));
              panelPb.setPreferredSize(new Dimension(300,100));
              framePb.getContentPane().add(panelPb);
         task = new LongTask();
              progressBar = new JProgressBar(0, task.getLengthOfTask());
         progressBar.setValue(0);
         progressBar.setStringPainted(true);
         panelPb.add(progressBar);
         //Create a timer.
         timer = new javax.swing.Timer(ONE_SECOND, new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
              progressBar.setValue(task.getCurrent());
              String s = task.getMessage();
              if (task.isDone()) {
                   Toolkit.getDefaultToolkit().beep();
                   timer.stop();
                             statusInfo.append(" Eseguita elaborazione "+newline);
                             spiega.setText (" 4. Migliora, Salva, Nuovo progetto o Esci"+newline);
                             superR.setVisible(false);
                             mosaica.setVisible(false);
                             salvab.setVisible(true);
                             migliora.setVisible(true);
                             nuovob.setVisible(true);
                             framePb.setVisible(false);
                   framePb.setCursor(null); //turn off the wait cursor
                   progressBar.setValue(progressBar.getMinimum());
                             //panelpane.removeAll();
                             //inserisco mosaico creato
              framePb.pack();
              framePb.setVisible(true);
              framePb.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
         task.go();
         timer.start();
              framePb.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
    // ===================================================================================== EVENTI
    public void actionPerformed(ActionEvent e) {
         Object source = e.getSource(); //chi ha invocato evento
    // ====================================================================================== NUOVO
         if((source == nuovo)||(source == nuovob)){
              System.out.println("Nuovo");
              mio m = new mio();
    // ====================================================================================== HELP
         if(source == help){
              System.out.println("Help");
              final JFrame framePh = new JFrame(" - H E L P - ");
              framePh.setSize(300,1000);
              JTextArea help=new JTextArea(" Help per utente! "+newline,5,40);
              help.setEditable(false);
              help.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              //help.setBackground(bluex);
              JButton escih = new JButton(" Esci ");
              escih.setBackground(bluex);
              escih.addActionListener(new ActionListener(){ //quando premo esci
              public void actionPerformed(ActionEvent e){
                             framePh.setVisible(false); // SQUALLIDO! esci meglio!
              framePh.getContentPane().add(help);
              framePh.pack();
              framePh.setVisible(true);
    // ======================================================================================== APRI
         if((source == apriimgf) || (source == apriimg)){ //apri + img
              System.out.println("Apri");
              scelta=1; //immagini
              Image imgresize;
              JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new ImageFilter());//filtro
              fileChooser.setAcceptAllFileFilterUsed(false);
              fileChooser.setAccessory(new ImagePreview(fileChooser));//anteprima
              fileChooser.setCurrentDirectory(new File("."));
         fileChooser.setMultiSelectionEnabled(true);
         int status = fileChooser.showOpenDialog(null);
              if (status == JFileChooser.APPROVE_OPTION) {
         File selectedFiles[] = fileChooser.getSelectedFiles();
                   if (selectedFiles.length>12){
                        System.out.println("selezionati piu' di 12 img");
                        return;
                   if (Nimg>12){
                        System.out.println("Ho piu' di 12 img");
                        return;
                   //int imgora = Nimg + selectedFiles.length; //immagini totali caricate fin'ora
                   int imgPrima = Nimg; //img prima di inserire le selezionate
                   int imgIns = selectedFiles.length; //immagini inserite ora.
              for (int im=0,n=selectedFiles.length; im<n; im++) {
                        icon = new ImageIcon(selectedFiles[im].getAbsolutePath());
                        statusInfo.append(" Inserito: " + selectedFiles[im].getName() + newline);
                        int hicon = icon.getIconHeight();
                        int wicon = icon.getIconWidth();
                        if ((hicon>183)||(wicon>225)){
                             imgresize = resizeIcon(selectedFiles[im].getAbsolutePath()); // resize
                             icon = new ImageIcon(imgresize);
                        if (ximg>675){
                             if (yimg>366){
                                  System.out.println(" TROPPE IMG!!! ");
                             else{
                             ximg=0;
                             yimg=yimg+ygrid;
                        image = new JLabel(icon);
                        image.setBounds(ximg,yimg,hicon,wicon);
                        //aggiorno dati IMMAGINI
                        yimgs[im+imgPrima]=yimg;
                        ximgs[im+imgPrima]=ximg;
                        images[im+imgPrima] = image;
                        himgs[im+imgPrima] = hicon;
                        wimgs[im+imgPrima] = wicon;
                        statusInfo.append("");
                        panelpane.add(images[im+imgPrima], new Integer(0),12-(im+imgPrima)); //ULTIMA SOPRA
                        //images[im+imgPrima].setLocation(ximgs[im+imgPrima],yimgs[im+imgPrima]);
                        ximg = ximg + xgrid;
                        Nimg=Nimg+1; //n img totale
                        ok.setEnabled(true); //abilito
                        aprimos.setEnabled(false); //abilito
                        spiega.setText (" 2.Con il mouse spostare le immagini creando un 'mosaico'"+newline);
    // ============================================================================= apri mosaico
         if((source == aprimos)||(source == aprimosf)){
              System.out.println("Apri mosaico");
              scelta=2; //mosaico
              JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new ImageFilter());//filtro
              fileChooser.setAcceptAllFileFilterUsed(false);
              fileChooser.setAccessory(new ImagePreview(fileChooser));//anteprima
              fileChooser.setCurrentDirectory(new File("."));
         fileChooser.setMultiSelectionEnabled(false);
         int status = fileChooser.showOpenDialog(null);
         if (status == JFileChooser.APPROVE_OPTION) {
         File selectedFile = fileChooser.getSelectedFile();
                   icon = new ImageIcon(selectedFile.getAbsolutePath());
                        int hicon = icon.getIconHeight();
                        int wicon = icon.getIconWidth();
                        image = new JLabel(icon);
                        image.setBounds(ximg,yimg,hicon,wicon);
                        statusInfo.append("");
                        panelpane.add(image,new Integer(1),1);//dopo sopra
                        ok.setEnabled(true); //abilito
                        apriimg.setEnabled(false); //abilito
                        aprimos.setEnabled(false); //abilito
                        spiega.setText (" 2. Proseguire"+newline);
    // =============================================================================== SALVA
         if(source == salva){
              System.out.println("Salva");
              try {
              FileOutputStream fos = new FileOutputStream ("info.doc"); //doc.ser
              ObjectOutputStream oos = new ObjectOutputStream (fos);
              String infoo = statusInfo.getText(); // NON E' GIUSTO!!!
              oos.writeObject(infoo);
              oos.flush();
              oos.close();
              statusInfo.append(" Salvato il progetto in: info.doc"+newline);
              } catch (IOException e1) {
                   statusInfo.setText (" Unable to save");
                   e1.printStackTrace(); //scrivo eccezione
    // =============================================================================== PROSEGUI
         if(source == ok){
              System.out.println("Prosegui");
              apriimg.setVisible(false);
              aprimos.setVisible(false);
              ok.setVisible(false);
              mosaica.setVisible(true);
              panelpane.removeMouseMotionListener(this);
              if (scelta==1){
                   superR.setVisible(true);
                   panelpane.revalidate ();
                   spiega.setText (" 3. Scegliere Mosaicatura o Super-Risoluzione"+newline);
              }else{
                   panelpane.revalidate ();
                   spiega.setText (" 3. Eseguire Mosaicatura"+newline);
    // ================================================================================= ESCI
         if((source == esci)||(source==chiudi)){
              System.out.println("Esci");
              System.exit(0);
    // =================================================================================== ANNULLA
         if(source == annulla){
              System.out.println("Annulla");
    // ======================================================================================== MOSAICA
         if(source == mosaica){
              System.out.println("Mosaica");
              frameP = new JFrame("Parametri di Mosaicatura");
              frameP.setSize(800,800);
              frameP.setBackground(bluex);
              JPanel panelP=new JPanel(new GridLayout(1,0));
              panelP.setBackground(bluex);
              panelP.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.setPreferredSize(new Dimension(500,500));
              frameP.getContentPane().add(panelP);
              JPanel panelP0 = new JPanel(new FlowLayout()); //avvia
              panelP0.setBackground(bluex);
              panelP0.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.add(panelP0);
              JPanel panelP1 = new JPanel(new FlowLayout());//parametri
              panelP1.setBackground(bluex);
              //panelP1.setLayout(new BoxLayout(panelP1, BoxLayout.Y_AXIS));
              panelP1.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.add(panelP1);
              JPanel panelP2=new JPanel(new FlowLayout());
              panelP2.setBackground(bluex);
              panelP2.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.add(panelP2);
              //**************** panel 1 : PARAMETRI
              JTextArea dico3 = new JTextArea(" Parametri di miscelazione",10,40);
              dico3.setEditable(false);
              dico3.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              JRadioButton primo = new JRadioButton("First frame");
              primo.setActionCommand("first");
              primo.setSelected(true);
              primo.setBackground(bluex);
              JRadioButton secondo = new JRadioButton("Last frame");
              secondo.setActionCommand("last");
              secondo.setBackground(bluex);
              JRadioButton terzo = new JRadioButton("Average");
              terzo.setActionCommand("average");
              terzo.setBackground(bluex);
              JRadioButton quarto = new JRadioButton("Median");
              quarto.setActionCommand("median");
              quarto.setBackground(bluex);
              JRadioButton quinto = new JRadioButton("Feathering");
              quinto.setActionCommand("feathering");
              quinto.setBackground(bluex);
              final ButtonGroup group = new ButtonGroup(); //raggruppo x fare esclusione
              group.add(primo);
              group.add(secondo);
              group.add(terzo);
              group.add(quarto);
              group.add(quinto);
              // ******** panel 0 : avvia
              JTextArea dico = new JTextArea(" Se si vuole avviare la mosaicatura premere 'Avvia'" newline" in tal caso se non sono stati settati parametri verranno utilizzati quelli di default",10,40);
              dico.setEditable(false);
              dico.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              JButton ok1 = new JButton("Avvia");
              ok1.setBackground(bluex);
              ok1.addActionListener(new ActionListener(){ //quando premo ok ...
              public void actionPerformed(ActionEvent e){
                        String command = group.getSelection().getActionCommand();
                   statusInfo.append(" Parametri di mosaicatura, miscelazione: "+command + newline);
                        frameP.setVisible(false); // SQUALLIDO! esci meglio!
                        barraP();
                        mettiMosaico();
              // ******** panel 2 : IMG RIFERIMENTO
              dico2 = new JTextArea(" Per impostare l'immagine di riferimento" newline " premere 'Imposta' e selezionare l'immagine "+newline,10,40);
              dico2.setEditable(false);
              dico2.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              JButton imposta = new JButton("Imposta");
              imposta.setBackground(bluex);
              imposta.addActionListener(new ActionListener(){ //quando premo ok ...
         public void actionPerformed(ActionEvent e){
                        String command = group.getSelection().getActionCommand();
                        imgRif();
              panelP1.add(dico3);
              panelP1.add(primo);
              panelP1.add(secondo);
              panelP1.add(terzo);
              panelP1.add(quarto);
              panelP1.add(quinto);
              panelP0.add(dico);
              panelP0.add(ok1);
              panelP2.add(dico2);
              panelP2.add(imposta);
              primo.addActionListener(this);
              secondo.addActionListener(this);
              JTabbedPane tabbedPane = new JTabbedPane(); //a schedario
              tabbedPane.setBackground(bluex);
              tabbedPane.addTab("Avvia Mosaicatura", null, panelP0, null);
              tabbedPane.addTab("Parametri", null, panelP1, null);
              tabbedPane.addTab("Img Riferimento", null, panelP2, null);
              tabbedPane.setSelectedIndex(0);
              panelP.add(tabbedPane);
              frameP.pack();
              frameP.setVisible(true);
    // ========================================================================== super risoluzione
         if(source == superR){
              System.out.println("Super-risoluzione");
              final JFrame frameP = new JFrame("Parametri di Super-risoluzione");
              frameP.setSize(800,800);
              frameP.setBackground(bluex);
              JPanel panelP = new JPanel(new GridLayout(1,0));
              panelP.setBackground(bluex);
              panelP.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.setPreferredSize(new Dimension(500,500));
              frameP.getContentPane().add(panelP);
              JPanel panelP0 = new JPanel(new FlowLayout()); //avvia
              panelP0.setBackground(bluex);
              panelP0.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.add(panelP0);
              JPanel panelP1 = new JPanel(new FlowLayout());//parametri
              panelP1.setBackground(bluex);
              panelP1.setBorder(BorderFactory.createLineBorder(Color.black));
              panelP.add(panelP1);
              //**************** panel 1 : PARAMETRI
              JTextArea dico3 = new JTextArea(" Parametri di super-risoluzione",10,40);
              dico3.setEditable(false);
              dico3.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              JRadioButton primo = new JRadioButton("Nearest");
              primo.setActionCommand("nearest");
              primo.setSelected(true);
              primo.setBackground(bluex);
              JRadioButton secondo = new JRadioButton("Weighted");
              secondo.setActionCommand("weighted");
              secondo.setBackground(bluex);
              final ButtonGroup group = new ButtonGroup(); //raggruppo x fare esclusione
              group.add(primo);
              group.add(secondo);
              // ******** panel 0 : avvia
              JTextArea dico = new JTextArea(" Se si vuole avviare la super-risoluzione premere 'Avvia'" newline" in tal caso se non sono stati settati parametri verranno utilizzati quelli di default",10,40);
              dico.setEditable(false);
              dico.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
              JButton ok1 = new JButton("Avvia");
              ok1.setBackground(bluex);
              ok1.addActionListener(new ActionListener(){ //quando premo ok ...
              public void actionPerformed(ActionEvent e){
                        String command = group.getSelection().getActionCommand();
                   statusInfo.append(" Parametri super-risoluzione: "+command + newline);
                        frameP.setVisible(false); // SQUALLIDO! esci meglio!
                        barraP();
              panelP1.add(dico3);
              panelP1.add(primo);
              panelP1.add(secondo);
              panelP0.add(dico);
              panelP0.add(ok1);
              primo.addActionListener(this);
              secondo.addActionListener(this);
              JTabbedPane tabbedPane = new JTabbedPane(); //a schedario
              tabbedPane.setBackground(bluex);
              tabbedPane.addTab(" Avvia super-risoluzione", null, panelP0, null);
              tabbedPane.addTab(" Parametri", null, panelP1, null);
              tabbedPane.setSelectedIndex(0);
              panelP.add(tabbedPane);
              frameP.pack();
              frameP.setVisible(true);
              mettiMosaico();
    // ===================================================== Mouse Event
    public void mousePressed(MouseEvent e) {
         mousex = e.getX(); // Save the x coord of the click
    mousey = e.getY(); // Save the y coord of the click
         for (int m=0; m<Nimg; m++){
              Point p = images[m].getLocation(); //posizione img[m] in panel
              px = (int)p.getX();
              py = (int)p.getY();
              if (mousex >= px && mousex <= (px+images[muovi].getWidth())
    && mousey >= py && mousey <= (py+images[muovi].getHeight())) {//se mouse dentro img
                   _canDrag = true;
              _dragFromX = mousex-px;  // how far from left
              _dragFromY = mousey-py;  // how far from top
                   muovi = m; //setto immagine da muovere!!!!
                   if (rifno==0){panelpane.moveToFront(images[muovi]);}//davanti img ke muovo
                   //se =1 nn mi muove img
         }//chiudo FOR
         if (rifno==1){
              statusInfo.append(" Immagine di riferimento: "+ muovi + newline);
              frameP.setVisible(true);
              dico2.append(" Immagine di riferimento impostata :"+muovi + newline);
              rifno=0;
    public void mouseDragged(MouseEvent e) {
         if (_canDrag) {   // True only if button was pressed inside ball.
    //--- Ball pos from mouse and original click displacement
    int ballX = e.getX() - dragFromX;
    int ballY = e.getY() - dragFromY;
         images[muovi].setLocation(_ballX,_ballY);
    //--- Don't move the ball off the screen sides
    ballX = Math.max(ballX, 0);
    ballX = Math.min(ballX, panelpane.getWidth() - images[muovi].getWidth());
    //--- Don't move the ball off top or bottom
    ballY = Math.max(ballY, 0);
    ballY = Math.min(ballY, panelpane.getHeight() - images[muovi].getHeight());
         Point p = images[muovi].getLocationOnScreen();
         int px = (int)p.getX();
         int py = (int)p.getY();
    //panelpane.repaint(); // Repaint because position changed.
         public void mouseExited(MouseEvent e) {
         _canDrag = false;
         }//end mouseExited
    public void mouseEntered (MouseEvent e) {} // ignore these events
    public void mouseClicked (MouseEvent e) {
    public void mouseReleased(MouseEvent e) {
              //e.consume();
    } // ignore these events
    public void mouseMoved(MouseEvent e) {}
    }// chiude classe

    please reuse the threads you've already started on this topic
    http://forum.java.sun.com/thread.jspa?threadID=573384&tstart=50
    and also, use the [url http://forum.java.sun.com/help.jspa?sec=formatting]formatting tags when posting code.
    keep in mind, this is an awful lot of code, and few will have the time to read through all of it, so if at all possible, make a smaller example case for your problem when you can so that we don't have to try to sort through hundreds of lines of code to find what you want to do.

Maybe you are looking for