-4

In my first program repaint work corectly, but in the second program i have a problem with it.

    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class repaint1 {

        public static void main(String[] args) {
            JFrame win = new JFrame("");
            test1 content = new test1();
            win.setContentPane(content);
            win.setSize(600, 400);
            win.setLocation(100, 100);
            win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            win.setResizable(false);
            win.setVisible(true);
            content.function();

        }

    }

    class test1 extends JPanel {

        private BufferedImage img;

        public int x = 50;
        public int y = 50;

        public test1() {

        }

        public void function() {

            try {

                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            for (int i = 50; i < 150; i++) {
                x = i;
                y = i;

                try {

                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }

                repaint();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            try {
                img = ImageIO.read(new File("images.jpg"));
                g.drawImage(img, x, y, null); 

            } catch (IOException ex) {
                // handle exception...
            }

        }

    }



import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class repaint2 {

    public static void main(String[] args) {

        JFrame f = new JFrame("JFrame");
        test2 content = new test2();
        f.setContentPane(content);
        f.setSize(600, 400);
        f.setLocation(100, 100);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.setVisible(true);

    }

}

class test2 extends JPanel {

    private BufferedImage img;

    public int x = 50;
    public int y = 50;

    public test2() {

        JButton button = new JButton("Start !");
        button.setBounds(458, 24, 122, 23);
        button.setVisible(true);
        add(button);

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // Execute when button is pressed

                function();

            }

        });

    }

    public void function() {

        for (int i = 50; i < 150; i++) {

            x = i;
            y = i;

            repaint();

            try {

                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }

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

        try {
            img = ImageIO.read(new File("images.jpg"));
            g.drawImage(img, x, y, null);

        } catch (IOException ex) {
            // handle exception...
        }

    }

}
camickr
  • 321,443
  • 19
  • 166
  • 288
markus
  • 3
  • 1
  • 2
    Welcome to StackOverflow. Can you please be more specific regarding your problem? What do you want it to do? What is it doing? Refer to [ask] for more information. – Aify Mar 11 '15 at 17:07
  • That is the kind of information that should go in the question, not the comments. Please update your question. – Aify Mar 11 '15 at 17:26
  • Don't read images in a painting method. It is not very efficient to continually read the image. You want the painting code to be as fast as possible. – camickr Mar 11 '15 at 18:07

2 Answers2

1

In the first case the function() method is invoked from the main Thread, so when you invoke sleep() this Thread sleeps, which does not affect painting of the GUI.

In the second case your function() method is invoked from the ActionListener. All code executed from a listener is invoked on the Event Dispatch Thread (EDT), which is responsible for repainting the GUI. When you tell the Thread to sleep() the EDT sleeps, so it can't repaint the GUI until the loop finishes executing.

In your ActionListener code you need to start a separate Thread. One way to do this is to use a SwingWorker.

Read the section from the Swing tutorial on Concurrency for more information.

camickr
  • 321,443
  • 19
  • 166
  • 288
-1

To move your image every time you need to use implements Runnable in your JPanel class. Here this class (MyJPanleClass) will behave like both as JPanel and Thread.

public class MyJPanleClass extends JPanel implements Runnable{

   public MyJPanleClass(){
      //constractor
   }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //do your staff with g
    }

    @Override
    public void run(){
       repaint();
    }

}

To execute it from main class just write this code:

MyJPnaleClass jp=new MyJPanelClass();
Thread t1=new Thread(jp);
t1.start();//this will call run class
try{
t1.join();//running the thread until it finish. 
}catch(Exception ex){}

If you don't have any idea about thread just follow the link to learn it: Thread in java tutorial

  • -1, Yes a separate Thread is required. However, don't use the getGraphics() method to do custom painting. Custom painting is done by overriding the paintComponent() method and by using the Graphics object passed to the method. The run() method should invoke repaint(). – camickr Mar 11 '15 at 17:38
  • I used getGraphics() to paint custom painting in run() method and my program was run/execute finely, and I did not face any problem while doing this. – Md. Nasir Uddin Bhuiyan Mar 11 '15 at 17:53
  • Painting code that is not done in the paintComponent() method is not stable. It may appear to work, until Swing decides it needs to repaint() the component. For example try resizing your frame after the animation is finished. – camickr Mar 11 '15 at 18:09
  • So, I need to do repaint() in run() method and do all staff in paintComponent() method? or use SwingUtilities.invokeLater in my graphics project? which one is better to do? – Md. Nasir Uddin Bhuiyan Mar 11 '15 at 18:13
  • `So, I need to do repaint() in run() method and do all staff in paintComponent() method?` Yes. – camickr Mar 11 '15 at 18:42