Code Ball
package BounceBall;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Ball extends JPanel {
private int delay = 10;
protected Timer timer = new Timer(delay, new TimerListener());
public int x = 0; private int y = 0;
private int radius = 5;
private int dx = 10;
private int dy = 10;
public Ball() {
timer.start();
}
private class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
if (x < radius) dx = Math.abs(dx);
if (x > getWidth() - radius) dx = -Math.abs(dx);
if (y < radius) dy = Math.abs(dy);
if (y > getHeight() - radius) dy = -Math.abs(dy);
x += dx;
y += dy;
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
Polygon anu = new Polygon();
anu.addPoint(0,0);
anu.addPoint( x - radius, y - radius);
g.drawPolygon(anu);
}
public void suspend() {
timer.stop();
}
public void resume() {
timer.start();
}
public void setDelay(int delay) {
this.delay = delay;
timer.setDelay(delay);
}
}
Code BallControl
package BounceBall;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class BallControl extends JPanel {
private Ball ball = new Ball();
private JButton jbtSuspend = new JButton("Stop");
private JButton jbtResume = new JButton("Lanjutkan");
private JScrollBar jsbDelay = new JScrollBar();
public BallControl() {
JPanel panel = new JPanel();
panel.add(jbtSuspend);
panel.add(jbtResume);
ball.setBorder(new javax.swing.border.LineBorder(Color.red));
jsbDelay.setOrientation(JScrollBar.HORIZONTAL);
ball.setDelay(jsbDelay.getMaximum());
setLayout(new BorderLayout());
add(jsbDelay, BorderLayout.NORTH);
add(ball, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
jbtSuspend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ball.suspend();
}
});
jbtResume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ball.resume();
}
});
jsbDelay.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
ball.setDelay(jsbDelay.getMaximum() - e.getValue());
}
});
}
Code BounceBallApp
package BounceBall;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class BounceBallApp extends JApplet {
public BounceBallApp() {
add(new BallControl());
}
}
Hasil:
Senin, 13 Oktober 2014
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar