好吧,所以我有一个名为Ball的类,我在构造函数中放置了一些参数。这里我有初始位置,大小和速度,但我还需要能够在参数中设置窗口(JFrame)的大小,以便在我调用例如ball(xpos,ypos,size,speed,windowx,windowy)它将根据我在windowx和windowy中放置的内容设置JFrame的大小。
现在我只是尝试像无头鸡一样的东西而不知道我在做什么:P,所以如果有人能指出我正确的方向,我将非常感激!
package com.company;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Main extends JPanel {
static Ball[] balls = new Ball[20];
Random rand = new Random();
Main() {
for(int i = 0; i<20;i++){
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
balls[i] = new Ball(Ball.randInt(100, 500),Ball.randInt(100, 500),Ball.randInt(10, 50),rand.nextInt(6-1)+1,randomColor,600,600);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(int i=0;i<20;i++) {
balls[i].draw(g);
}
}
public static void main(String[] args) throws InterruptedException{
Main m = new Main();
JFrame frame = new JFrame("Title"); //create a new window and set title on window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the window to close when the cross in the corner is pressed
frame.setSize(600,600);
frame.add(m); //add the content of the game object to the window
frame.setVisible(true); //make the window visible
while(true){
Thread.sleep(10);
for(int i= 0;i<balls.length;i++){
balls[i].update();
}
m.repaint();
}
}
}
球类:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created by John on 25/02/2015.
*/
public class Ball extends JPanel{
float _speedX;
float _speedY;
int _size;
float _x;
float _y;
float _speed;
Color _color;
int _windowX;
int _windowY;
Ball(int x, int y, int sz, float speed, Color c, int windowX, int windowY){
_x = x;
_y = y;
_speed=speed;
_speedX = speed;
_speedY = speed;
_size = sz;
_color = c;
_windowX = windowX;
_windowY = windowY;
}
public void update(){
_x += _speedX;
_y += _speedY;
if (_x+_size<0 || _x+_size>_windowX-_size){
_speedX*=-1;
}
if (_y+_size<0 || _y+_size>_windowY-_size){
_speedY*=-1;
}
this.repaint();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void draw(Graphics g) {
g.setColor(_color);
g.fillOval((int)_x,(int) _y, _size, _size);
}
public void setPreferredSize(int wX, int wY) {
_windowX=wX;
_windowY=wY;
setPreferredSize(new Dimension(_windowX,_windowY));
}
}