- Back to Home »
- Thread Dalam Java
Posted by : Unknown
Sabtu, 11 Maret 2017
Class BOLA.
public class BOLA implements Runnable{
Form F;
public BOLA(Form aThis) {
F=aThis;
}
@Override
public void run() {
while (true) F.gambarkanbola();
}
}
Class KOTAK.
public class KOTAK implements Runnable{
Form F;
public KOTAK(Form aThis) {
F=aThis;
}
@Override
public void run() {
while (true) F.gambarkankotak();
}
}
FORM
import java.awt.Color;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Form extends javax.swing.JFrame {
public Form() {
initComponents();
setTitle("Thread & Kotak");
}
private void BolaStartActionPerformed(java.awt.event.ActionEvent evt) {
Ktr1 = new Thread(new BOLA(this));
Ktr1.start();
}
private void BolaStopActionPerformed(java.awt.event.ActionEvent evt) {
Ktr1.stop();
}
private void KotakStartActionPerformed(java.awt.event.ActionEvent evt) {
Ktr2 = new Thread(new KOTAK(this));
Ktr2.start();
}
private void KotakStopActionPerformed(java.awt.event.ActionEvent evt) {
Ktr2.stop();
}
Thread Ktr1;
void gambarkanbola() {
Graphics g = canvas1.getGraphics();
int x = (int) (Math.random() * canvas1.getWidth());
int y = (int) (Math.random() * canvas1.getHeight());
canvas1.update(g);
g.setColor(Color.red);
g.fillOval(x, y, 30, 30);
try {
Ktr1.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thread Ktr2;
void gambarkankotak() {
Graphics g = canvas1.getGraphics();
int x = (int) (Math.random() * canvas1.getWidth());
int y = (int) (Math.random() * canvas1.getHeight());
canvas1.update(g);
g.setColor(Color.blue);
g.fillRect(y, x, 30, 30);
try {
Ktr2.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
RUNNING :