public class proga
{
public static void main(String[] args)
{
Izm_Zveta myapplet=new Izm_Zveta();
myapplet.setVisible(true);
}
}
потоковая программа
Я написала программу которая по идее должна создавать множество потоков (в каждом потоке рисуется мяч и отталкивается от некоторой невидимой области)
Задание классическое, я попробовала сделать как в учебнике (там правда на другом языке было написано), но что-то не так...
Отсюда происходит запуск:
Код:
а вот и сама прога:
Код:
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Calendar;
import java.lang.Object;
import javax.swing.ComboBoxModel;
import javax.swing.text.JTextComponent;
import java.util.ArrayList;
import java.util.*;
public class Izm_Zveta extends JFrame
{
Container p = getContentPane();//я так поняла проблемы в основном из-за вот этого, так как графика в нем (в контейнере) упорно не желает рисоваться
public Izm_Zveta()
{
ActionListener actionListener = new TestActionListener(this);
setSize(600,340);
p.setLayout(new FlowLayout(FlowLayout.RIGHT));
Container c=getContentPane();
JButton btn_exit = new JButton("Exit");
btn_exit.setLayout(new FlowLayout(FlowLayout.RIGHT));
c.add(btn_exit);
btn_exit.addActionListener(actionListener);
btn_exit.setActionCommand("exit");
JButton btn_go = new JButton("go");
btn_go.setLayout(new FlowLayout(FlowLayout.RIGHT));
btn_go.setActionCommand("go");
btn_go.addActionListener(actionListener);
c.add(btn_go);
}
}
class Ball
{
private ArrayList<Ball> balls=new ArrayList<Ball>();
Graphics g;
Graphics2D g2;
double bazeX=0;
double bazeY=0;
double myx=0;
double myy=0;
final int XSIZE=15;
final int YSIZE = 15;
int x = 0;
int y = 0;
private int dx = 2;
private int dy = 2;
double diam=30;
Container c;
public Ball(Container p){c=p;}
public void addBall()
{
Ball b=new Ball(c);
b.paint(g);
adds(b);
}
public void adds(Ball b)
{
balls.add(b);
for(int i=0;i<balls.size();i++)
{
b=(Ball)balls.get(i);
}
}
protected void paint(Graphics g)
{
float redPart=0.75F,greenPart=0.25F,bluePart=0.65F;
int myx=0;
int myy=0;
int diam=30;
try{
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(600,340);
Image image = f.createImage(40, 40);
g =image.getGraphics();
g.setColor(new Color(redPart,greenPart,bluePart));
g.drawOval(myx,myy,diam,diam);
}
catch(NullPointerException e)
{System.out.println("!!!");}
}
public void move ()
{
try{
for(int i=0;i<1000;i++)
{myy+=dy;myx+=dx;
if((myy+diam>=38)||(myy+diam<0))
{myy=-dy;}
if((myx+diam>=38)||(myx+diam<0))
{myx=-dx;}
c.repaint();
}
}
catch(NullPointerException e){System.out.println("tut oshibk");}
}
}
class TestActionListener implements ActionListener
{
Container p; Graphics2D g2;
Ball Shar=new Ball(p);
Izm_Zveta ListenerFrame;
public TestActionListener(Izm_Zveta LF)
{
ListenerFrame = LF;
}
public void actionPerformed(ActionEvent e)
{ try{
if (e.getActionCommand().equals("go"))
{Shar.addBall();}
if (e.getActionCommand().equals("exit"))
{System.exit(0);}
}
catch(NullPointerException ex)
{System.out.println("tut oshibka");}
}
}
class BallThread extends Thread
{ private Ball b;
public BallThread(Ball aBall){b=aBall;}
public void run()
{
try
{
for(int i=0;i<=1000;i++)
{
b.move();
sleep(5);
}
}
catch(InterruptedException exception){}
}
}
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Calendar;
import java.lang.Object;
import javax.swing.ComboBoxModel;
import javax.swing.text.JTextComponent;
import java.util.ArrayList;
import java.util.*;
public class Izm_Zveta extends JFrame
{
Container p = getContentPane();//я так поняла проблемы в основном из-за вот этого, так как графика в нем (в контейнере) упорно не желает рисоваться
public Izm_Zveta()
{
ActionListener actionListener = new TestActionListener(this);
setSize(600,340);
p.setLayout(new FlowLayout(FlowLayout.RIGHT));
Container c=getContentPane();
JButton btn_exit = new JButton("Exit");
btn_exit.setLayout(new FlowLayout(FlowLayout.RIGHT));
c.add(btn_exit);
btn_exit.addActionListener(actionListener);
btn_exit.setActionCommand("exit");
JButton btn_go = new JButton("go");
btn_go.setLayout(new FlowLayout(FlowLayout.RIGHT));
btn_go.setActionCommand("go");
btn_go.addActionListener(actionListener);
c.add(btn_go);
}
}
class Ball
{
private ArrayList<Ball> balls=new ArrayList<Ball>();
Graphics g;
Graphics2D g2;
double bazeX=0;
double bazeY=0;
double myx=0;
double myy=0;
final int XSIZE=15;
final int YSIZE = 15;
int x = 0;
int y = 0;
private int dx = 2;
private int dy = 2;
double diam=30;
Container c;
public Ball(Container p){c=p;}
public void addBall()
{
Ball b=new Ball(c);
b.paint(g);
adds(b);
}
public void adds(Ball b)
{
balls.add(b);
for(int i=0;i<balls.size();i++)
{
b=(Ball)balls.get(i);
}
}
protected void paint(Graphics g)
{
float redPart=0.75F,greenPart=0.25F,bluePart=0.65F;
int myx=0;
int myy=0;
int diam=30;
try{
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(600,340);
Image image = f.createImage(40, 40);
g =image.getGraphics();
g.setColor(new Color(redPart,greenPart,bluePart));
g.drawOval(myx,myy,diam,diam);
}
catch(NullPointerException e)
{System.out.println("!!!");}
}
public void move ()
{
try{
for(int i=0;i<1000;i++)
{myy+=dy;myx+=dx;
if((myy+diam>=38)||(myy+diam<0))
{myy=-dy;}
if((myx+diam>=38)||(myx+diam<0))
{myx=-dx;}
c.repaint();
}
}
catch(NullPointerException e){System.out.println("tut oshibk");}
}
}
class TestActionListener implements ActionListener
{
Container p; Graphics2D g2;
Ball Shar=new Ball(p);
Izm_Zveta ListenerFrame;
public TestActionListener(Izm_Zveta LF)
{
ListenerFrame = LF;
}
public void actionPerformed(ActionEvent e)
{ try{
if (e.getActionCommand().equals("go"))
{Shar.addBall();}
if (e.getActionCommand().equals("exit"))
{System.exit(0);}
}
catch(NullPointerException ex)
{System.out.println("tut oshibka");}
}
}
class BallThread extends Thread
{ private Ball b;
public BallThread(Ball aBall){b=aBall;}
public void run()
{
try
{
for(int i=0;i<=1000;i++)
{
b.move();
sleep(5);
}
}
catch(InterruptedException exception){}
}
}
а если серьёзно, то рисовать надо в методе JFrame/paint() (а не Ball/paint() как у вас), а потоки надо ЗАПУСКАТЬ (у вас не увидел вообще ни одного использования BallThread)
но по моему проще будет переписать этот код с нуля чем пытаться его исправлять
2 - Applet'ы и Swing программы запускаются в Event Dispatch Thread всегда!
3 - читайте книги. не поверите, но там все это написано и даже подробно! меня всегда поражает, когда лезут писать код не имея базовых крепких знаний....
а вот и код:
Код:
import java.awt.geom.*;
/**
A ball that moves and bounces off the edges of a
rectangle
*/
public class Ball
{
/**
Moves the ball to the next position, reversing direction
if it hits one of the edges
*/
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy;
}
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
/**
Gets the shape of the ball at its current position.
*/
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
}
/**
A ball that moves and bounces off the edges of a
rectangle
*/
public class Ball
{
/**
Moves the ball to the next position, reversing direction
if it hits one of the edges
*/
public void move(Rectangle2D bounds)
{
x += dx;
y += dy;
if (x < bounds.getMinX())
{
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX())
{
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y < bounds.getMinY())
{
y = bounds.getMinY();
dy = -dy;
}
if (y + YSIZE >= bounds.getMaxY())
{
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
/**
Gets the shape of the ball at its current position.
*/
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
}
Код:
import java.awt.*;
import java.util.*;
import javax.swing.*;
/**
* The component that draws the balls.
*/
public class BallComponent extends JComponent
{
/**
* Add a ball to the panel.
* @param b the ball to add
*/
public void add(Ball b)
{
balls.add(b);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape());
}
}
private ArrayList<Ball> balls = new ArrayList<Ball>();
}
import java.util.*;
import javax.swing.*;
/**
* The component that draws the balls.
*/
public class BallComponent extends JComponent
{
/**
* Add a ball to the panel.
* @param b the ball to add
*/
public void add(Ball b)
{
balls.add(b);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls)
{
g2.fill(b.getShape());
}
}
private ArrayList<Ball> balls = new ArrayList<Ball>();
}
Код:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Shows animated bouncing balls.
*/
public class BounceThread
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A runnable that animates a bouncing ball.
*/
class BallRunnable implements Runnable
{
/**
* Constructs the runnable.
* @aBall the ball to bounce
* @aPanel the component in which the ball bounces
*/
public BallRunnable(Ball aBall, Component aComponent)
{
ball = aBall;
component = aComponent;
}
public void run()
{
try
{
for (int i = 1; i <= STEPS; i++)
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
private Ball ball;
private Component component;
public static final int STEPS = 1000;
public static final int DELAY = 5;
}
/**
* The frame with panel and buttons.
*/
class BounceFrame extends JFrame
{
/**
* Constructs the frame with the component for showing the bouncing ball and Start and Close
* buttons
*/
public BounceFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("BounceThread");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();
}
});
addButton(buttonPanel, "Close", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Adds a button to a container.
* @param c the container
* @param title the button title
* @param listener the action listener for the button
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
/**
* Adds a bouncing ball to the canvas and starts a thread to make it bounce
*/
public void addBall()
{
Ball b = new Ball();
comp.add(b);
Runnable r = new BallRunnable(b, comp);
Thread t = new Thread(r);
t.start();
}
private BallComponent comp;
public static final int DEFAULT_WIDTH = 450;
public static final int DEFAULT_HEIGHT = 350;
public static final int STEPS = 1000;
public static final int DELAY = 3;
}
import java.awt.event.*;
import javax.swing.*;
/**
* Shows animated bouncing balls.
*/
public class BounceThread
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* A runnable that animates a bouncing ball.
*/
class BallRunnable implements Runnable
{
/**
* Constructs the runnable.
* @aBall the ball to bounce
* @aPanel the component in which the ball bounces
*/
public BallRunnable(Ball aBall, Component aComponent)
{
ball = aBall;
component = aComponent;
}
public void run()
{
try
{
for (int i = 1; i <= STEPS; i++)
{
ball.move(component.getBounds());
component.repaint();
Thread.sleep(DELAY);
}
}
catch (InterruptedException e)
{
}
}
private Ball ball;
private Component component;
public static final int STEPS = 1000;
public static final int DELAY = 5;
}
/**
* The frame with panel and buttons.
*/
class BounceFrame extends JFrame
{
/**
* Constructs the frame with the component for showing the bouncing ball and Start and Close
* buttons
*/
public BounceFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("BounceThread");
comp = new BallComponent();
add(comp, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
addBall();
}
});
addButton(buttonPanel, "Close", new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Adds a button to a container.
* @param c the container
* @param title the button title
* @param listener the action listener for the button
*/
public void addButton(Container c, String title, ActionListener listener)
{
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
/**
* Adds a bouncing ball to the canvas and starts a thread to make it bounce
*/
public void addBall()
{
Ball b = new Ball();
comp.add(b);
Runnable r = new BallRunnable(b, comp);
Thread t = new Thread(r);
t.start();
}
private BallComponent comp;
public static final int DEFAULT_WIDTH = 450;
public static final int DEFAULT_HEIGHT = 350;
public static final int STEPS = 1000;
public static final int DELAY = 3;
}