弱弱的问问......
老师要我们自学绘图组件.....就是要做一个会动的小球.....但我希望小球能来回滚动,或Z字型滚动.........怎么改都不行呢.....
还有能不能在滚动的过程中变色呢?
这是小球会往下掉的代码,高手看看怎么改下,能来回动呢?感激感激~~
package cha7;
import javax.swing.*;
import java.awt.*;
public class Canvas {
private JFrame frame;
private JPanel canvas;
private Graphics2D graphic;
private Color backgroundColour;
private Image canvasImage;
Canvas(String title,int width,int height,Color bgColour)
{frame=new JFrame();
canvas =new JPanel();
frame.setTitle(title);
canvas.setPreferredSize(new Dimension(width,height));
backgroundColour=bgColour;
frame.pack();
}
Canvas()
{
frame=new JFrame();
canvas=new CanvasPane();
frame.setContentPane(canvas);
frame.setTitle("Demo Canvas");
canvas.setPreferredSize(new Dimension(600,600));
backgroundColour=Color.blue;
frame.pack();
setVisible(true);
}
public void setVisible(boolean visible)
{
if(graphic==null){
Dimension size=canvas.getSize();
canvasImage=canvas.createImage(size.width,size.height);
graphic=(Graphics2D)canvasImage.getGraphics();
graphic.setColor(backgroundColour);
graphic.fillRect(0, 0,size.width,size.height);
graphic.setColor(Color.white);
}
frame.setVisible(visible);
}
public void draw(Shape shape)
{
graphic.draw(shape);
canvas.repaint();
}
public void fill(Shape shape)
{
graphic.fill(shape);
canvas.repaint();
}
public void erase(Shape shape)
{
Color original=graphic.getColor();
graphic.setColor(backgroundColour);
graphic.fill(shape);
graphic.setColor(original);
canvas.repaint();
}
private class CanvasPane extends JPanel
{
public void paint(Graphics g)
{
g.drawImage(canvasImage,0,0,null);
}
}
}
package cha7;
import java.awt.*;
import java.awt.geom.*;
public class Circles {
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private Canvas canvas;
public Circles()
{
diameter=10;
xPosition=20;
yPosition=60;
color="blue";
canvas=new Canvas();
draw();
}
public void moveDown()
{
erase();
yPosition +=10;
xPosition +=2;
draw();
}
private void draw()
{
canvas.fill(new Ellipse2D.Double(xPosition,yPosition,diameter,diameter));
}
public void erase()
{canvas.erase(new Ellipse2D.Double(xPosition,yPosition,diameter,diameter));
}
public static void main(String args[])throws Exception{
Circles c=new Circles();
long i=40,j=10,k=0;
while (i>0){
c.moveDown();
for(j=10;j<9000000;j++){k++;}
i=i-1;
}
c.erase();
c.canvas.fill(new Ellipse2D.Double(20,60,10,10));
}
}