gpt4 book ai didi

Java 在 JPanel 中限制 fps

转载 作者:行者123 更新时间:2023-12-01 22:26:13 26 4
gpt4 key购买 nike

我正在尝试限制程序的 fps,因为代码中的球移动得太快。我一直在尝试使用计时器和 Action 监听器来做到这一点,但我不知道如何正确实现它。

主类

    package com.company;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;


public class Main extends JPanel implements ActionListener {


Ball[] balls = new Ball[20];
Random rand = new Random();
private final Timer timer = new Timer(40, this);



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(0, 600),Ball.randInt(0, 600),Ball.randInt(10, 50),rand.nextInt(3-1)+1,randomColor,600,600);


}
}

public void paintComponent(Graphics g) {

super.paintComponent(g);
for(int i=0;i<20;i++) {
balls[i].draw(g);
balls[i].update();
}

}


@Override
public void actionPerformed(ActionEvent e) {
this.repaint();
}


public static void main(String[] args) {


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



}


}

球类

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);

}
}

最佳答案

不要从paintComponent()调用更新。

球应该通过actionPerformed()方法(从计时器调用)改变它们的位置。因此,如果您更改计时器毫秒数,则可以使其更快/更慢。

事实上,计时器应该定义重新绘制内容的频率(并更改模型 - 内容元素的位置/大小)

关于Java 在 JPanel 中限制 fps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28744240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com