当前位置: 代码迷 >> Java相关 >> [求助]JAVA高级问题!!----怕就不要来啦!
  详细解决方案

[求助]JAVA高级问题!!----怕就不要来啦!

热度:260   发布时间:2004-12-23 13:16:00.0
[求助]JAVA高级问题!!----怕就不要来啦!

JAVa问题???

<画一个正方型和一个圆

圆在那个正方形中运动

而且要设置那个圆和那个正方形的色彩??????>

搜索更多相关的解决方案: JAVA  高级  

----------------解决方案--------------------------------------------------------

呵呵,我写了一个,楼主可以参考一下,其实这种题目不难的。

/** * This is a simple Java2D program. * @author jellen */

import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import javax.swing.*;

class Ball { private int x = (int)(390 * Math.random()) + 21; private int y = (int)(390 * Math.random()) + 21; private static final int w = 30; private static final int h = 30; private int dx = 3; private int dy = 3; public void draw(Graphics2D g) { g.fill(new Ellipse2D.Double(x, y, w, h)); }

public void move() { x += dx; y += dy;

if(x < 20) { x = 20; dx = -dx; }

if(y < 20) { y = 20; dy = -dy; }

if(x + w >= 420) { x = 420 - w; dx = -dx; }

if(y + h >= 420) { y = 420 - h; dy = -dy; } } }

class MyPanel extends JPanel implements Runnable { private Rectangle2D rect = new Rectangle2D.Double(20, 20, 400, 400); private Ball ball = new Ball();

public MyPanel() { Thread t = new Thread(this); t.start(); } public void paintComponent(Graphics g) { super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.BLUE); g2.fill(rect);

g2.setColor(Color.RED); ball.draw(g2); }

public void run() { while(true) { try { ball.move(); Thread.sleep(5); repaint(); } catch(InterruptedException e) { } } } }

public class Move { public static void main(String[] args) { JFrame me = new JFrame("Move Test"); me.setSize(450, 470); me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); me.setResizable(false); me.getContentPane().add(new MyPanel()); me.setVisible(true); } }


----------------解决方案--------------------------------------------------------
  相关解决方案