我从 Ball 类中制作了 20 个对象,因为我需要 20 个球在屏幕上弹跳,但现在它只显示 1 个球弹跳。 我认为这与添加了 20 个 JPanel 并且它们彼此重叠有关,但我不完全确定。
package com.company;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created by John on 25/02/2015.
*/
public class Ball extends JComponent{
int _speedX;
int _speedY;
int _size;
int _x;
int _y;
Color _color;
int _windowX;
int _windowY;
Ball(int x, int y, int sz, int sX, int sY, Color c, int windowX, int windowY){
_x = x;
_y = y;
_speedX = sX;
_speedY = sY;
_size = sz;
_color = c;
_windowX = windowX;
_windowY = windowY;
setForeground(_color);
}
public void update(){
_x = _x + _speedX;
_y = _y + _speedY;
if (_x<0 || _x>_windowX-_size){
_speedX*=-1;
}
if (_y<=0 || _y>_windowY-_size){
_speedY*=-1;
}
this.repaint();
}
public static int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(_x, _y, _size, _size);
}
public static void main(String[] args) {
// write your code here
JFrame frame = new JFrame("Title"); //create a new window and set title on window
frame.setSize(600, 600); //set size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the window to close when the cross in the corner is pressed
frame.setVisible(true); //make the window visible
JPanel panel = new JPanel();
frame.add(panel);
Ball[] balls = new Ball[20];
for(int i = 0; i<20;i++){
balls[i] = new Ball(randInt(0,600),randInt(0,600),randInt(10,20),randInt(1,8), randInt(1,8),Color.yellow,600,600);
panel.add(balls[i]);
}
while(true){
for(int i = 0; i < balls.length; i++) {
balls[i].update();
}
panel.repaint();
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}
最佳答案
建议:
- 不要让 Ball 继承 JComponent 或 JPanel,而应使其成为逻辑非组件类。
- 创建一个扩展 JPanel 的 Drawing 类并在其
paintComponent
中进行绘制。方法,而不是它的paint(...)
方法。这将使动画更加流畅。 - 创建
ArrayList<Ball>
你的 Ball 对象并将它们绘制在paintComponent(...)
内通过迭代列表来重写方法。 - 移动列表中的球也是如此。
- 使用 Swing Timer 来驱动动画,而不是
while (true)
环形。如果您在该循环中犯了一个错误,您将卡住 GUI,使其无法运行,因此 Swing Timer 是一种更安全的方法。
关于java - JPanel 只显示一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28730060/