Hallo,
ich habe eine kleine Simulation die mit einem Button gestartet wird und dies funktioniert, aber ich bekomme es einfach nicht hin mit dem gleichen Button die Simulation anzuhalten um sie bei erneunten druecken wieder fortzufuehren.
Was mache ich falch?
Viele Gruesse
ich habe eine kleine Simulation die mit einem Button gestartet wird und dies funktioniert, aber ich bekomme es einfach nicht hin mit dem gleichen Button die Simulation anzuhalten um sie bei erneunten druecken wieder fortzufuehren.
Code:
import java.awt.*;
import java.awt.Button;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class BallRoom extends JApplet implements ActionListener, Runnable {
private final int WIDTH = 350;
private final int HEIGHT = 300;
private PaintSurface canvas;
private JButton controlSimulation;
boolean doSuspend = false;
Thread th;
public void init() {
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
controlSimulation = new JButton("Start");
controlSimulation.addActionListener(this);
this.add(controlSimulation, BorderLayout.SOUTH);
}
public void run() {
while (true){
repaint();
try {
Thread.sleep(100);
}
catch (InterruptedException ex){
if (doSuspend) {
doSuspend = false;
controlSimulation.setText("Start");//setText("Start");
System.out.println("Displayer suspended");
th.suspend();
}
}
}
}
public void update(Graphics g) {
paint(g);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == controlSimulation){
if (th == null) {
th = new Thread(this);
th.start();
controlSimulation.setText("Stop");
}
//else th.resume();
//controlSimulation.setLabel("Stop");
else if (th != null) {
doSuspend = true;
}
}
}
}
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
class PaintSurface extends JComponent {
int ball1_x_pos = 0; // the starting X position
int ball1_y_pos = 150; // the starting Y position
int ball2_x_pos = 60; // the starting X position
int ball2_y_pos = 150; // the starting Y position
int d = 20; // the diameter of the ball
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball1_x_pos++; // move ball1 right one pixel
ball2_x_pos--; // move ball1 left one pixel
Shape ball1 = new Ellipse2D.Float(ball1_x_pos, ball1_y_pos, d, d);
Shape ball2 = new Ellipse2D.Float(ball2_x_pos, ball2_y_pos, d, d);
g2.setColor(Color.RED);
g2.fill(ball1);
g2.fill(ball2);
}
}
Was mache ich falch?
Viele Gruesse