Threads und Layout

Status
Nicht offen für weitere Antworten.

skizZ

Aktives Mitglied
Hallo zusammen,

vor knapp 2 Wochen habe ich bereits hier mit etwas Hilfe das Programm hinbekommen, welches ich nun erweitern muss.

Es sollen Buttons über, links und rechts von dem Applet sein, die beim anklicken den entsprechenden Thread anhalten und bei erneutem klicken wieder weiterlaufen lassen.

Kurze erklärung zum bisherigen Applet:

4 Bilder laufen als Animation
- von oben nach unten
- von links nach rechts
- von links oben nach rechts unten
- von rechts oben nach links unten

Dies hatte auch funktioniert, allerdings mit nur einem Thread.

Wir sollen mit suspend() und resume() arbeiten.
Nun erstelle ich erstmal für jedes Bild einen eigenen Thread. Dies scheint schonmal nicht zu funktionieren.

Desweiteren versuche ich mit einem Layoutmanager die buttons entsprechend zu positionieren. Die obere Leiste ist schonmal vorhanden, allerdings wird dann im eigentlichen Appletbereich (Center) kein Bild mehr angezeigt im Moment.

Habe es mal folgendermaßen versucht:

Java:
import java.awt.*;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;


public class Animation extends JApplet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Button north;
	int index = 0;
	

	public void init() {
		this.setSize(800, 600);
		Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER, 50, 10));
		north = new Button();
		north.setBackground(Color.RED);
		north.setLabel("STOP !");
		TextField northText = new TextField();
		northText.setText("MITTE");
		northText.setEditable(false);
		panel.add(northText);
		panel.add(north);
		
		Panel jC = new Panel();
		jC.setLayout(null);
		
		
		int i;
		Bilder[] b = new Bilder[4];
		getContentPane().setLayout(null);
	    MediaTracker tracker = new MediaTracker(this);
	   
				b[0]=new Bilder(-100,-150,"new-1.gif",((double) this.getSize().width+100)/((double) this.getSize().height+150),1);
			
				b[1]=new Bilder(this.getSize().width,-150,"new-2.gif",-((double) this.getSize().width+100)/((double) this.getSize().height+150),1);
			
				b[2]=new Bilder(this.getSize().width/2-50,-150,"new-4.gif",0,1);
			
				b[3]=new Bilder(-100,this.getSize().height/2-100,"new-3.gif",3,0);
				
				Malen m1 = new Malen(b[0]);
				Malen m2 = new Malen(b[1]);
				Malen m3 = new Malen(b[2]);
				Malen m4 = new Malen(b[3]);
				m1.setBounds(new Rectangle(0,0,0,0));
				m2.setBounds(new Rectangle(0,0,0,0));
				m3.setBounds(new Rectangle(0,0,0,0));
				m4.setBounds(new Rectangle(0,0,0,0));
			for(i=0; i<b.length;i++)
			{
			tracker.addImage(b[i].img, i);
			try
			{
				tracker.waitForID(i);
			}
			catch(InterruptedException e) {}
		}
		if (tracker.statusID(b.length-1, true) == MediaTracker.COMPLETE)
			setLayout(new BorderLayout());
		jC.add(m1);
      	jC.add(m2);
      	jC.add(m3);
      	jC.add(m4);
	      	add("North", panel);
	      	add("Center", jC);
	      	
	      	
	      	
	            
	}
	

	

public class Malen extends JComponent implements Runnable{
	Thread[] t = new Thread[4];
	Thread thread;
	private List<Bilder> picList =
        Collections.synchronizedList(new ArrayList<Bilder>());
	Bilder[] bilder = new Bilder[4];
	Bilder[] b = new Bilder[4];
	Image m_ImgBuffer;

	public Malen(Bilder bild){
		
		t[index] = new Thread(this);
		t[index].start();
		
			addPicture(bild);
			index++;
	}
	
	public void addPicture(Bilder bild)
    {
        picList.add(bild);
        b[index] = bild;
    }

	public void paint(Graphics g){
		if(this.b[3].x == this.getSize().width)
		{
			this.b[3].runs += 1;
		}
		if((this.b[3].runs % 2) == 1)
		{
			g.setColor(Color.orange);
			g.fillRect(0,0,this.getSize().width,this.getSize().height);
		} else { 
			g.setColor(Color.green);
		    g.fillRect(0,0,this.getSize().width,this.getSize().height);
		}
		for (Bilder b : picList)
        {
            g.drawImage(b.img, (int)b.x,(int)b.y,this);
        }
	}
	
	public final void suspend(){
		b[0].xVer = 0;
		b[0].yVer = 0;
	}
		
	public void run(){
		int h,w;
		
		north.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				 Thread.currentThread().suspend();	
				}
			}
		);
		
		
		h = getContentPane().getSize().height;
		w = getContentPane().getSize().width;
		//b[0].xVer = ((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
		//b[1].xVer = -((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
		while(true) {
			
			try {
        	for (Bilder bi : picList) {
        		if(bi.x <= this.getSize().width && bi.y <= this.getSize().height) 
        		{
        			
        			bi.x += bi.xVer;
        			bi.y += bi.yVer;
        			bi.x1 += bi.xVer;
            		bi.y1 += bi.yVer;
            		      			
        		} 
        		else{
        			bi.x = bi.xStd;
        			bi.y = bi.yStd;
        			bi.x1 = 0;
        			bi.y1 = 0;
        			if(bi.equals(b[0]))
        			b[0].xVer = ((double) this.getSize().width+100)/((double) this.getSize().height+150);
        			if(bi.equals(b[1]))
        			b[1].xVer = -((double) this.getSize().width+100)/((double) this.getSize().height+150);
        			}   
        		
        	if(h != getContentPane().getSize().height || w != getContentPane().getSize().width)
        	{
        		h = getContentPane().getSize().height; w = getContentPane().getSize().width;
        		//b[1].x = this.getSize().width+b[1].x1;
            	b[2].x = this.getSize().width/2-50;
            	b[3].y = this.getSize().height/2-100;
            	System.out.println("TEST");
            	b[0].xVer = ((double) this.getSize().width-b[0].x)/((double) this.getSize().height-b[0].y);
            	b[1].xVer = -((double) 100+b[1].x)/((double) this.getSize().height-b[1].y);
        	}
        		
        	}
        	//b[1].xStd = this.getSize().width;
        	//b[2].xStd = this.getSize().width/2-50;
        	//b[3].yStd = this.getSize().height/2-100;
		
        	repaint();
            Thread.sleep(10);
        }  
        catch (InterruptedException e){}
    }
		
	}
	
}


public class Bilder extends JComponent{
	Image img;
	double x;
	double y;
	double xVer;
	double yVer;
	double xStd;
	double yStd;
	int runs;
	double x1, y1;
	public Bilder(double x, double y, String str, double xVer, double yVer){
		this.x=x;
		this.y=y;
		this.img=getImage(getDocumentBase(),str);
		this.xVer=xVer;
		this.yVer=yVer;
		this.xStd = x;
		this.yStd = y;
		this.runs = 1;
		this.x1 = 0;
		this.y1 = 0;
	}
}}


Vielen Dank für Tipps
 

skizZ

Aktives Mitglied
Hi,

ich weiß, habe ich auch schon gelesen. Das kommt von meinem Prof.

Benutzen Sie zum Anhalten bzw. Weiterlaufen eines Threads die “deprecated“ Methoden suspend( ) bzw. resume( ) aus java.lang.Thread.


Ist das denn nun möglich bei meiner Animation mit nur einem Thread? Weil ansonsten muss ich das alles umbauen und habe gerade keinen blassen schimmer wie xD
 

Marco13

Top Contributor
Hmja, ist schon chaotisch...

Man sollte nicht Swing und AWT mischen. Statt Button, Panel, TextField usw solltest du JButton und JPanel usw. verwenden...

Warum das "Malen"-Objekt platz für 4 Threads und Bilder bietet, leuchtet nicht ganz ein... Das solltest du mal aufräumen. Bei einem ersten Test flog eine NullPointerException, kannst ja mal schauen...
 

skizZ

Aktives Mitglied
Hi,

also ich gehe mal davon aus, dass ich für jedes Bild einen neuen Thread machen muss und somit das komplette Programm neu schreiben darf, oder?

Habe mal bisschen was verändert, der Button "WEST" funktioniert auch. Hält halt bis jetzt alles an

Java:
import java.awt.*;
 
import javax.swing.*;
 
import java.awt.*;
import java.awt.event.*;
 
import javax.swing.*;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;



public class Animation extends JApplet implements Runnable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	Button north, west, east;
	Thread picthread, picthread2;
	
	public void run(){
		
			
		west.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(west.getLabel().equals("STOP !")){
					picthread.suspend();
					west.setLabel("GO !");
					west.setBackground(Color.GREEN);
				}
				else{
					picthread.resume();
					west.setLabel("STOP !");
					west.setBackground(Color.RED);
				}
				
				}
			});
	}
	

	public void init() {
		Panel panel = new Panel(new GridLayout(1,2));
        north = new Button();
        north.setBackground(Color.RED);
        north.setLabel("STOP !");
        TextField northText = new TextField();
        northText.setText("MITTE");
        northText.setEditable(false);
        panel.add(northText);
        panel.add(north);
        
        Panel panel2 = new Panel(new GridLayout(2,1));
        west = new Button();
        west.setBackground(Color.RED);
        west.setLabel("STOP !");
        TextField westText = new TextField();
        westText.setText("LINKS");
        westText.setEditable(false);
        panel2.add(westText);
        panel2.add(west);
        
        Panel panel3 = new Panel(new GridLayout(2,1));
        east = new Button();
        east.setBackground(Color.RED);
        east.setLabel("STOP !");
        TextField eastText = new TextField();
        eastText.setText("RECHTS");
        eastText.setEditable(false);
        panel3.add(eastText);
        panel3.add(east);

		this.setSize(800, 600);
		int i;
		Bilder[] b = new Bilder[4];
	    MediaTracker tracker = new MediaTracker(this);
	   
				b[0]=new Bilder(-100,-150,"new-1.gif",((double) this.getSize().width+100)/((double) this.getSize().height+150),1);
			
				b[1]=new Bilder(1000,-150,"new-2.gif",-((double) this.getSize().width+100)/((double) this.getSize().height+150),1);
			
				b[2]=new Bilder(this.getSize().width/2-50,-150,"new-4.gif",0,1);
			
				b[3]=new Bilder(-100,this.getSize().height/2-100,"new-3.gif",3,0);
			for(i=0; i<b.length;i++)
			{
			tracker.addImage(b[i].img, i);
			try
			{
				tracker.waitForID(i);
			}
			catch(InterruptedException e) {}
		}
		if (tracker.statusID(b.length-1, true) == MediaTracker.COMPLETE)
			new Thread(this).start();
			setLayout(new BorderLayout());
            add("North", panel);
            add("West", panel2);
            add("Center", new Malen(b));
            add("East", panel3);

	}

public class Malen extends Component implements Runnable{
	private List<Bilder> picList =
        Collections.synchronizedList(new ArrayList<Bilder>());
	Bilder[] b;
	Image m_ImgBuffer;

	public Malen(Bilder[] b){
		this.b=b;
		picthread = new Thread(this);
		picthread.start();
		for(int i=0; i < this.b.length; i++)
			addPicture(b[i]);
	}
	
	public void addPicture(Bilder b)
    {
        picList.add(b);
    }

	public void paint(Graphics g){
		if(this.b[3].x == this.getSize().width)
		{
			this.b[3].runs += 1;
		}
		if((this.b[3].runs % 2) == 1)
		{
			g.setColor(Color.orange);
			g.fillRect(0,0,this.getSize().width,this.getSize().height);
		} else { 
			g.setColor(Color.green);
		    g.fillRect(0,0,this.getSize().width,this.getSize().height);
		}
		for (Bilder b : picList)
        {
            g.drawImage(b.img, (int)b.x,(int)b.y,this);
        }
	}
	
		
	public void run(){
		
		
		int h,w;
		h = getContentPane().getSize().height;
		w = getContentPane().getSize().width;
		b[0].xVer = ((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
		b[1].xVer = -((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
		while(true) {
			this.b[1].xStd = this.getSize().width;
        try {
        	for (Bilder bi : picList) {
        		if(bi.x <= this.getSize().width && bi.y <= this.getSize().height) 
        		{
        			bi.x += bi.xVer;
        			bi.y += bi.yVer;
        			bi.x1 += bi.xVer;
            		bi.y1 += bi.yVer;     			
        		} 
        		else{
        			bi.x = bi.xStd;
        			bi.y = bi.yStd;
        			bi.x1 = 0;
        			bi.y1 = 0;
        			if(bi.equals(b[0]))
        			b[0].xVer = ((double) this.getSize().width+100)/((double) this.getSize().height+150);
        			if(bi.equals(b[1]))
        			b[1].xVer = -((double) this.getSize().width+100)/((double) this.getSize().height+150);
        			}   
        		
        	if(h != getContentPane().getSize().height || w != getContentPane().getSize().width)
        	{
        		h = getContentPane().getSize().height; w = getContentPane().getSize().width;
        		//b[1].x = this.getSize().width+b[1].x1;
            	b[2].x = this.getSize().width/2-50;
            	b[3].y = this.getSize().height/2-100;
            	System.out.println("TEST");
            	b[0].xVer = ((double) this.getSize().width-b[0].x)/((double) this.getSize().height-b[0].y);
            	b[1].xVer = -((double) 100+b[1].x)/((double) this.getSize().height-b[1].y);
        	}
        		
        	}
        	b[1].xStd = this.getSize().width;
        	b[2].xStd = this.getSize().width/2-50;
        	b[3].yStd = this.getSize().height/2-100;
		
        	repaint();
            Thread.sleep(10);
        }  
        catch (InterruptedException e){}
    }
	}
}

public class Bilder extends JComponent{
	Image img;
	double x;
	double y;
	double xVer;
	double yVer;
	double xStd;
	double yStd;
	double xVerStd;
	double yVerStd;
	int runs;
	double x1, y1;
	public Bilder(double x, double y, String str, double xVer, double yVer){
		this.x=x;
		this.y=y;
		this.img=getImage(getDocumentBase(),str);
		this.xVer=xVer;
		this.yVer=yVer;
		this.xVerStd=xVer;
		this.yVerStd=yVer;
		this.xStd = x;
		this.yStd = y;
		this.runs = 1;
		this.x1 = 0;
		this.y1 = 0;
	}
}}
 

Marco13

Top Contributor
Hmja scheint doch zu funktionieren...!? (Also, ist total häßlich, aber scheint zu funktionieren :D )
 

skizZ

Aktives Mitglied
Hi,

naja, ich soll ja die Bilder auch einzeln anhalten können :-(

bekomme das gerade nicht gebacken.

Klicke ich links, soll das Bild von oben links nach unten rechts stoppen

Klicke ich rechts soll das Bild von oben rechts nach unten links stoppen

Klicke ich oben soll das Bild von oben nach unten und links nach rechts stoppen.

Im Moment stoppen alle ;-)
 

Marco13

Top Contributor
Ja, das meinte ich mit aufräumen - das ganze ist wirklich sehr chaotisch (In Anlehnung an den Thread von damals...: Dort würde es eben einfach mehrere PictureAnimator-Objekte geben...). Also, die Idee das addActionListener in einer von einem eigenen Thread ausgeführten run-Methode zu machen ist eine Form von Kreativität die... ähm. Naja.

Wenn man versuchen würde, das mit möglichst wenigen Änderungen zum Laufen zu Hacken, würde man wohl sowas machen wie das hier unten, aber um's nochmal zu betonen:

Das nähert sich mit großen Schritten dem beschissenst strukturierten Programm, das ich je gesehen habe (und hier im Forum hab' ich schon einiges gesehen!) :autsch:

Code:
import java.awt.*;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;



public class Animation2 extends JApplet implements Runnable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    Button north, west, east;
    Thread picthreads[] = new Thread[4];

    public void run(){


        west.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(west.getLabel().equals("STOP !")){
                    picthreads[0].suspend();
                    west.setLabel("GO !");
                    west.setBackground(Color.GREEN);
                }
                else{
                    picthreads[0].resume();
                    west.setLabel("STOP !");
                    west.setBackground(Color.RED);
                }

                }
            });
        east.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(east.getLabel().equals("STOP !")){
                    picthreads[1].suspend();
                    east.setLabel("GO !");
                    east.setBackground(Color.GREEN);
                }
                else{
                    picthreads[1].resume();
                    east.setLabel("STOP !");
                    east.setBackground(Color.RED);
                }

                }
            });
    }


    public void init() {
        Panel panel = new Panel(new GridLayout(1,2));
        north = new Button();
        north.setBackground(Color.RED);
        north.setLabel("STOP !");
        TextField northText = new TextField();
        northText.setText("MITTE");
        northText.setEditable(false);
        panel.add(northText);
        panel.add(north);

        Panel panel2 = new Panel(new GridLayout(2,1));
        west = new Button();
        west.setBackground(Color.RED);
        west.setLabel("STOP !");
        TextField westText = new TextField();
        westText.setText("LINKS");
        westText.setEditable(false);
        panel2.add(westText);
        panel2.add(west);

        Panel panel3 = new Panel(new GridLayout(2,1));
        east = new Button();
        east.setBackground(Color.RED);
        east.setLabel("STOP !");
        TextField eastText = new TextField();
        eastText.setText("RECHTS");
        eastText.setEditable(false);
        panel3.add(eastText);
        panel3.add(east);

        this.setSize(800, 600);
        int i;
        Bilder[] b = new Bilder[4];
        MediaTracker tracker = new MediaTracker(this);

                b[0]=new Bilder(-100,-150,"image01.png",((double) this.getSize().width+100)/((double) this.getSize().height+150),1);

                b[1]=new Bilder(1000,-150,"image02.png",-((double) this.getSize().width+100)/((double) this.getSize().height+150),1);

                b[2]=new Bilder(this.getSize().width/2-50,-150,"image03.png",0,1);

                b[3]=new Bilder(-100,this.getSize().height/2-100,"image04.png",3,0);
            for(i=0; i<b.length;i++)
            {
            tracker.addImage(b[i].img, i);
            try
            {
                tracker.waitForID(i);
            }
            catch(InterruptedException e) {}
        }
        if (tracker.statusID(b.length-1, true) == MediaTracker.COMPLETE)
            new Thread(this).start();
            setLayout(new BorderLayout());
            add("North", panel);
            add("West", panel2);
            add("Center", new Malen(b));
            add("East", panel3);

    }

public class Malen extends Component {
    private List<Bilder> picList =
        Collections.synchronizedList(new ArrayList<Bilder>());
    Bilder[] b;
    Image m_ImgBuffer;

    public Malen(Bilder[] b){
        this.b=b;

        for (int i=0; i<b.length; i++)
        {
            MalenAnimator ma = new MalenAnimator();
            ma.picList.add(b[i]);
            picthreads[i] = new Thread(ma);
            picthreads[i].start();
        }

        for(int i=0; i < this.b.length; i++)
            addPicture(b[i]);
    }

    public void addPicture(Bilder b)
    {
        picList.add(b);
    }

    public void paint(Graphics g){
        if(this.b[3].x == this.getSize().width)
        {
            this.b[3].runs += 1;
        }
        if((this.b[3].runs % 2) == 1)
        {
            g.setColor(Color.orange);
            g.fillRect(0,0,this.getSize().width,this.getSize().height);
        } else {
            g.setColor(Color.green);
            g.fillRect(0,0,this.getSize().width,this.getSize().height);
        }
        for (Bilder b : picList)
        {
            g.drawImage(b.img, (int)b.x,(int)b.y,this);
        }
    }



class MalenAnimator implements Runnable
{
    private List<Bilder> picList =
        Collections.synchronizedList(new ArrayList<Bilder>());

    public void run(){


        int h,w;
        h = getContentPane().getSize().height;
        w = getContentPane().getSize().width;
        b[0].xVer = ((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
        b[1].xVer = -((double) getContentPane().getSize().width+100)/((double) getContentPane().getSize().height+150);
        while(true) {
            Malen.this.b[1].xStd = Malen.this.getSize().width;
        try {
            for (Bilder bi : picList) {
                if(bi.x <= Malen.this.getSize().width && bi.y <= Malen.this.getSize().height)
                {
                    bi.x += bi.xVer;
                    bi.y += bi.yVer;
                    bi.x1 += bi.xVer;
                    bi.y1 += bi.yVer;
                }
                else{
                    bi.x = bi.xStd;
                    bi.y = bi.yStd;
                    bi.x1 = 0;
                    bi.y1 = 0;
                    if(bi.equals(b[0]))
                    b[0].xVer = ((double) Malen.this.getSize().width+100)/((double) Malen.this.getSize().height+150);
                    if(bi.equals(b[1]))
                    b[1].xVer = -((double) Malen.this.getSize().width+100)/((double) Malen.this.getSize().height+150);
                    }

            if(h != getContentPane().getSize().height || w != getContentPane().getSize().width)
            {
                h = getContentPane().getSize().height; w = getContentPane().getSize().width;
                //b[1].x = this.getSize().width+b[1].x1;
                b[2].x = Malen.this.getSize().width/2-50;
                b[3].y = Malen.this.getSize().height/2-100;
                System.out.println("TEST");
                b[0].xVer = ((double) Malen.this.getSize().width-b[0].x)/((double) Malen.this.getSize().height-b[0].y);
                b[1].xVer = -((double) 100+b[1].x)/((double) Malen.this.getSize().height-b[1].y);
            }

            }
            b[1].xStd = Malen.this.getSize().width;
            b[2].xStd = Malen.this.getSize().width/2-50;
            b[3].yStd = Malen.this.getSize().height/2-100;

            repaint();
            Thread.sleep(10);
        }
        catch (InterruptedException e){}
    }
    }
}

}




public class Bilder extends JComponent{
    Image img;
    double x;
    double y;
    double xVer;
    double yVer;
    double xStd;
    double yStd;
    double xVerStd;
    double yVerStd;
    int runs;
    double x1, y1;
    public Bilder(double x, double y, String str, double xVer, double yVer){
        this.x=x;
        this.y=y;
        this.img=getImage(getDocumentBase(),str);
        this.xVer=xVer;
        this.yVer=yVer;
        this.xVerStd=xVer;
        this.yVerStd=yVer;
        this.xStd = x;
        this.yStd = y;
        this.runs = 1;
        this.x1 = 0;
        this.y1 = 0;
    }
}}
 

Marco13

Top Contributor
So als Zwischenbemerkung: Im ursprünglichen Thread hatte ich gesagt, dass man die Bilder mit EINEM Thread animieren kann, was auch richtig uns sinnvoll ist. Dass die Bilder unabhängig voneinander bewegt werden sollten, hattest du damals nicht gesagt. Aber selbst DAS könnte man mit einem Thread machen - und zwar problemlos. Auussser natürlich, wenn ein Prof meint, dass das mit 4 Threads und suspend/resume gemacht werden soll :autsch:

Wie auch immer - nochmal der angepasste Code von damals. Die Bilder müssen durchnummeriert vorliegen (also z.B. "image00.png", "image01.png", "image02.png", ...).

Das ist AUCH gehackt, aber ... nicht so schlimm ;)


Java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.awt.*;

import javax.swing.*;
import java.awt.BorderLayout;

public class Animation3 extends JApplet
{
    private PictureComponent pictureComponent;
    private JPanel buttonPanel;

    public void init()
    {
        this.setSize(new Dimension(361, 400));
        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        pictureComponent = new PictureComponent();
        c.add(pictureComponent, BorderLayout.CENTER);

        buttonPanel = new JPanel(new GridLayout(1,0));

        c.add(buttonPanel, BorderLayout.NORTH);

    }



    public void start()
    {
        for (int i=0; i<5; i++)
        {
            initAnimation(i);
        }
    }

    private void initAnimation(int index)
    {
        int x = (int)(Math.random()*getWidth());
        int y = (int)(Math.random()*getHeight());
        int dx = -5 + (int)(Math.random() * 10);
        int dy = -5 + (int)(Math.random() * 10);

        Picture picture = new Picture(getImage(getDocumentBase(),"image0"+index+".png"), x,y,dx,dy);
        PictureAnimator pictureAnimator = new PictureAnimator(pictureComponent);
        pictureAnimator.addPicture(picture);
        Thread thread = new Thread(pictureAnimator);
        thread.start();

        buttonPanel.add(createToggleButton(index, thread));
    }

    private JToggleButton createToggleButton(final int index, final Thread thread)
    {
        final JToggleButton b = new JToggleButton("Toggle "+index);
        b.setSelected(true);
        b.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (b.isSelected())
                {
                    thread.resume();
                }
                else
                {
                    thread.suspend();
                }
            }
        });
        return b;
    }



}


class Picture
{
    private Image image;
    private int x;
    private int y;
    private int dx;
    private int dy;

    public Picture(Image image, int x, int y, int dx, int dy)
    {
        this.image = image;
        this.x = x;
        this.y = y;
        this.dx = dx;
        this.dy = dy;
    }
    public Image getImage()
    {
        return image;
    }
    public int getX()
    {
        return x;
    }
    public int getY()
    {
        return y;
    }
    public void setX(int x)
    {
        this.x = x;
    }
    public void setY(int y)
    {
        this.y = y;
    }
    public int getDX()
    {
        return dx;
    }
    public int getDY()
    {
        return dy;
    }
}


class PictureComponent extends JComponent
{
    private List<Picture> pictures =
        Collections.synchronizedList(new ArrayList<Picture>());

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        synchronized (pictures)
        {
            for (Picture picture : pictures)
            {
                g.drawImage(picture.getImage(), picture.getX(), picture.getY(), this);
            }
        }
    }

    public void addPicture(Picture picture)
    {
        pictures.add(picture);
    }
}


class PictureAnimator implements Runnable
{
    private PictureComponent pictureComponent;

    private List<Picture> pictures =
        Collections.synchronizedList(new ArrayList<Picture>());


    public PictureAnimator(PictureComponent pictureComponent)
    {
        this.pictureComponent = pictureComponent;
    }

    public void addPicture(Picture picture)
    {
        pictures.add(picture);
        pictureComponent.addPicture(picture);
    }

    public void run()
    {
        while (true)
        {
            synchronized (pictures)
            {
                for (Picture picture : pictures)
                {
                    int x = picture.getX();
                    int y = picture.getY();
                    x += picture.getDX();
                    y += picture.getDY();

                    // Should be done on EDT...
                    int w = pictureComponent.getWidth();
                    int h = pictureComponent.getHeight();

                    x %= w;
                    if (x < 0)
                    {
                        x += w;
                    }

                    y %= h;
                    if (y < 0)
                    {
                        y += h;
                    }


                    picture.setX(x);
                    picture.setY(y);
                }
                pictureComponent.repaint();
            }
            try
            {
                Thread.sleep(40);
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
            }

        }
    }


}
 

skizZ

Aktives Mitglied
Ich bedanke mich :D

Naja, dass es in 4 Threads laufen soll wusste ich bisher auch noch nicht.

Ich versuche mir Mühe zu geben und meine Programme besser zu strukturieren ;-)
 
Status
Nicht offen für weitere Antworten.
Ähnliche Java Themen
  Titel Forum Antworten Datum
U FileChooser Layout - Threads? AWT, Swing, JavaFX & SWT 17
frager2345 Threads -> Ereignisbehandlung AWT, Swing, JavaFX & SWT 2
N jFrame löscht am Ende des Threads alles AWT, Swing, JavaFX & SWT 2
J GUI Ausgaben aus Threads AWT, Swing, JavaFX & SWT 13
A Swing ProgressBar über 2 parallel laufende Threads AWT, Swing, JavaFX & SWT 2
N JavaFX Logging des JavaFX Application Threads mit Log4J AWT, Swing, JavaFX & SWT 3
U JAVAFX observer und threads AWT, Swing, JavaFX & SWT 1
J Textlabel verändern mit parallelen Threads AWT, Swing, JavaFX & SWT 7
Sugan Inhalte mit Threads ändern -> java.lang.IllegalStateException AWT, Swing, JavaFX & SWT 6
R Straßenkreuzung - Ampeln mit Threads koordinieren AWT, Swing, JavaFX & SWT 5
C Threads Swing AWT, Swing, JavaFX & SWT 11
Z JavaFX Threads AWT, Swing, JavaFX & SWT 4
T hallo, habe ein Problem mit dem pro. eines Threads AWT, Swing, JavaFX & SWT 4
M Threads - nicht erklärbare Exception AWT, Swing, JavaFX & SWT 6
R Repaint() in Schleifen, Threads AWT, Swing, JavaFX & SWT 13
S Java Swing GUI mit MVC und Threads AWT, Swing, JavaFX & SWT 6
M Frage zu Threads AWT, Swing, JavaFX & SWT 3
C JTextArea scrollt bei append(String) aus Threads nicht ans Ende AWT, Swing, JavaFX & SWT 7
K Threads - Timer - run() mehrfach parallel? AWT, Swing, JavaFX & SWT 2
B GUI mit Threads aufbauen AWT, Swing, JavaFX & SWT 5
E Threads Ausgaben in GUI anzeigen lassen AWT, Swing, JavaFX & SWT 14
P JavaFX 2 (2.1 Beta) Threads AWT, Swing, JavaFX & SWT 7
B Threads in Swing AWT, Swing, JavaFX & SWT 4
M Problem mit Threads AWT, Swing, JavaFX & SWT 64
R Swing Java Swing Gui und nebenläufige Threads AWT, Swing, JavaFX & SWT 4
S Swing Threads Windows 7 64 bit AWT, Swing, JavaFX & SWT 12
J Threads + JFrame AWT, Swing, JavaFX & SWT 4
R Java threads und synchronized AWT, Swing, JavaFX & SWT 15
R Swing Swing und die Threads AWT, Swing, JavaFX & SWT 9
N Swing Threads sollen Tabtitel zur Laufzeit ändern AWT, Swing, JavaFX & SWT 4
S Gui und Aufgaben Threads AWT, Swing, JavaFX & SWT 12
M Zugriff paralleler Threads auf selbes JTextPane AWT, Swing, JavaFX & SWT 6
B Frage zu Swing,Threads, SwingWorker und Socket Communikation AWT, Swing, JavaFX & SWT 4
M Prioritäten bei SwingWorker / Threads AWT, Swing, JavaFX & SWT 9
B Swing GUI und Threads AWT, Swing, JavaFX & SWT 4
R Korrektes manipulieren der GUI aus anderen Threads heraus AWT, Swing, JavaFX & SWT 19
S Threads in einen Frame zeichnen lassen (Paint()?!) AWT, Swing, JavaFX & SWT 5
W GUI in mehreren Threads AWT, Swing, JavaFX & SWT 5
F Swing Anfängerproblem Threads AWT, Swing, JavaFX & SWT 6
S Swing Threads und das Ändern des Hintergrundes ... AWT, Swing, JavaFX & SWT 2
S Zeichnen in Threads AWT, Swing, JavaFX & SWT 4
T Auf Ende von mehreren Threads warten, ohne den EDT zu blockieren AWT, Swing, JavaFX & SWT 1
J SWT SWT und Threads AWT, Swing, JavaFX & SWT 5
borobudur SWT SWT-Framework und Threads AWT, Swing, JavaFX & SWT 12
W Threads nacheinander aufführen AWT, Swing, JavaFX & SWT 5
A Swing und Threads AWT, Swing, JavaFX & SWT 8
B JProgressbar wird nicht aktualisert, trotz Threads AWT, Swing, JavaFX & SWT 6
K Timer und Threads ruckeln für Fotoschwenk AWT, Swing, JavaFX & SWT 3
S JProgressBar und Threads AWT, Swing, JavaFX & SWT 11
G Probleme mit jList und Threads. AWT, Swing, JavaFX & SWT 3
R Swing & Threads AWT, Swing, JavaFX & SWT 4
R 2 Threads nacheinander. Einer terminiert, der andere nicht. AWT, Swing, JavaFX & SWT 9
J Unterschied zwischen SwingWorker und Threads AWT, Swing, JavaFX & SWT 4
P Threads und Swing bzw. AWT AWT, Swing, JavaFX & SWT 15
W Threads und trotzdem keine Nebenläufigkeit AWT, Swing, JavaFX & SWT 13
G Fenster erst nach Stoppen des Threads anzeigen AWT, Swing, JavaFX & SWT 3
N Threads kein neues Fenster erzeugen lassen AWT, Swing, JavaFX & SWT 4
G problem mit threads/repaint ! AWT, Swing, JavaFX & SWT 2
W Swing, 2 JProgressbars und threads geht das? AWT, Swing, JavaFX & SWT 2
A JTextArea und Threads AWT, Swing, JavaFX & SWT 9
B Probleme mit GUI und Threads AWT, Swing, JavaFX & SWT 17
E repaint(), EDT-Warteschlange und Threads AWT, Swing, JavaFX & SWT 26
S Threads in Java AWT, Swing, JavaFX & SWT 22
G AWT + Threads = nicht gut :P AWT, Swing, JavaFX & SWT 6
F Verständis Problem zu Threads AWT, Swing, JavaFX & SWT 2
M Swinganwendung Threads mit JProgressBar AWT, Swing, JavaFX & SWT 7
V Problem mit Aktualisieren von JList mit Threads AWT, Swing, JavaFX & SWT 3
R JProgressBar ohne Threads verwenden AWT, Swing, JavaFX & SWT 6
I JList, AbstractListModel und nebenläufige Threads AWT, Swing, JavaFX & SWT 2
S "Millionen" von Threads? Programm komplett beenden AWT, Swing, JavaFX & SWT 2
M Konsolenprg-Ausgabe in GUI geleitet - Brauche ich Threads? AWT, Swing, JavaFX & SWT 2
K Swing und Threads AWT, Swing, JavaFX & SWT 11
M Threads in Swing? AWT, Swing, JavaFX & SWT 2
C Schweres Problem mit JDialog und Threads! Anzeige blockiert! AWT, Swing, JavaFX & SWT 5
N Netzwerk-Applikation, SWT und Threads AWT, Swing, JavaFX & SWT 4
R createBufferStrategy() und Threads AWT, Swing, JavaFX & SWT 5
D Threads unter JFrame AWT, Swing, JavaFX & SWT 2
G Nochmal Threads und Einfrieren des GUI :( AWT, Swing, JavaFX & SWT 10
V Swing & Threads ??? AWT, Swing, JavaFX & SWT 3
D Problem mit JProgressBar und Threads AWT, Swing, JavaFX & SWT 7
S Welches Java Layout sollte ich verwenden? AWT, Swing, JavaFX & SWT 3
S Layout - Problem AWT, Swing, JavaFX & SWT 1
D Layout einer scene mit ListView Elementen und Zwei Textfeldern AWT, Swing, JavaFX & SWT 1
H Swing , GridLayout, Größenbestimmung der Komponenten im Layout AWT, Swing, JavaFX & SWT 8
melaniemueller Layout wechseln über RadioButtons AWT, Swing, JavaFX & SWT 4
E LayoutManager Welcher Layout-Mix löst mein Problem? AWT, Swing, JavaFX & SWT 3
J Swing Hilfe bei Layout AWT, Swing, JavaFX & SWT 2
R Layered Layout AWT, Swing, JavaFX & SWT 1
E showAndWait is not allowed during animation or layout processing Memory FX AWT, Swing, JavaFX & SWT 2
newJavaGeek Grid-Layout problem AWT, Swing, JavaFX & SWT 7
E Swing Layout während der Laufzeit anpassen AWT, Swing, JavaFX & SWT 3
P JavaFX Zugriff auf Fenster/Layout-Container in eigenen Klassen AWT, Swing, JavaFX & SWT 5
R Layout Manager null und Component wird nicht hinzugefügt AWT, Swing, JavaFX & SWT 3
S Kann javafx.scene.layout.VBoxBuilder nicht importieren AWT, Swing, JavaFX & SWT 3
OSchriever Layout über Radiobuttons ändern AWT, Swing, JavaFX & SWT 4
B Swing Probleme mit dem Layout AWT, Swing, JavaFX & SWT 1
Hatsi09 JButton text layout AWT, Swing, JavaFX & SWT 9
I JavaFX - festes Layout AWT, Swing, JavaFX & SWT 1
S JavaFX TableView einzelne Zelle Layout zuweisen AWT, Swing, JavaFX & SWT 3
DaCrazyJavaExpert Swing Zwei gleichgroße Panels in einem Scrollpane mit Layout AWT, Swing, JavaFX & SWT 9

Ähnliche Java Themen

Neue Themen


Oben