|
Тема |
криво лево работещо решение [re: jensen-110062] |
|
Автор |
jensen-110062 (рекордьор) |
|
Публикувано | 24.09.11 19:49 |
|
|
import java.awt.*;
import javax.swing.*;
public class BouncingBalls extends JFrame{
public BouncingBalls () {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setForeground(Color.WHITE);
Pan1 panel1=new Pan1(Color.RED);
Pan1 panel2=new Pan1(Color.BLUE);
Pan1 panel3=new Pan1(Color.YELLOW);
panel2.add(panel3, BorderLayout.CENTER);
panel1.add(panel2, BorderLayout.CENTER);
getContentPane().add(panel1);
setVisible(true);
Thread t1=new Thread(panel1);
Thread t2=new Thread(panel2);
Thread t3=new Thread(panel3);
t1.start();
t2.start();
t3.start();
}
public static void main(String[] args)
{
new BouncingBalls();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Pan1 extends JPanel implements ActionListener, Runnable{
private int DIAMETER = 40;
private int ballX =0;
private int ballY =0;
private double ballSpeedX = Math.random()*20; // Ball's speed for x and y
private double ballSpeedY = Math.random()*20;
private int rightBound; // Maximum permissible x, y values.
private int bottomBound;
Timer time;
Color color;
public Pan1(Color color) {
setOpaque(false);
this.color=color;
//setBackground(Color.WHITE);
setLayout(new BorderLayout());
time=new Timer(20, this);
time.start();
}
public void setBounds(int width, int height) {
rightBound = width - DIAMETER;
bottomBound = height - DIAMETER;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(ballX, ballY, DIAMETER, DIAMETER);
}
public void move() {
ballX += ballSpeedX;
ballY += ballSpeedY;
if (ballX < 0) {
ballX = 0;
ballSpeedX = -ballSpeedX;
} else if (ballX > rightBound) {
ballX = rightBound;
ballSpeedX = -ballSpeedX;
}
if (ballY < 0) {
ballY = 0;
ballSpeedY = -ballSpeedY;
} else if (ballY > bottomBound) {
ballY = bottomBound;
ballSpeedY = -ballSpeedY;
}
}
public void actionPerformed (ActionEvent event) {
setBounds(getWidth(), getHeight());
move();
repaint();
}
public void run() {
try {
Thread.sleep( 20);
}
catch ( InterruptedException exception ) {
System.err.println( exception.toString() );
}
time.start();
}
}
|
| |
|
|
|