|
-
July 26th, 2010, 07:44 AM
#1
Threads, balls..
Hi, i'm new with threads in java and really need some help right now.
I want the program to add some balls, one after another with 1s interval...
I know that I have to implement Runnable interface in NyPanel.java and the method run ().
In main, do a while loop, create new threads and use Thread.sleep (1000); for the interval.
But how is the code going to look like in method run (); ?
My code for 1 ball:
Main
Code:
public class Main
{
public static void main(String[] args)
{
NyPanel panelen = new NyPanel ();
NyRam ramen = new NyRam ("Bollar");
ramen.add(panelen, "Center");
ramen.add(panelen.getPanelReferens(), "South");
ramen.setVisible(true);
}
}
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import java.util.ArrayList;
public class NyPanel extends JPanel implements ActionListener
{
private Timer timern = new Timer (5, this);
private double x = 0, y = 0, velX = 3, velY = 3;
private Random farg = new Random ();
private Color farger;
private Ellipse2D cirkel;
private ArrayList <Ellipse2D> bollar = new ArrayList <Ellipse2D> ();
private JPanel panelen = new JPanel ();
private JSlider linjalen = new JSlider (0, 80, 40);
public NyPanel ()
{
}
@Override
public void paintComponent (Graphics gr)
{
super.paintComponent (gr);
this.setBackground(Color.BLACK);
Graphics2D g = (Graphics2D) gr;
linjalen.setBackground(Color.BLACK);
panelen.add(linjalen);
panelen.setBackground(Color.BLACK);
int linjalVarde = linjalen.getValue();
cirkel = new Ellipse2D.Double (x, y, linjalVarde, linjalVarde);
g.setColor (farger);
g.fill (cirkel);
timern.start ();
}
public void actionPerformed (ActionEvent e)
{
if (x < 0 || x > 755)
{
velX = -velX;
skiftaFarger ();
}
if (y < 0 || y > 450)
{
velY = -velY;
skiftaFarger ();
}
x += velX;
y += velY;
repaint ();
}
public void skiftaFarger ()
{
int rod = farg.nextInt (256);
int gron = farg.nextInt (256);
int bla = farg.nextInt (256);
farger = new Color (rod, gron, bla);
}
public JPanel getPanelReferens ()
{
return panelen;
}
}
NyRam.java, not showing that class. it is not necessary.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|