sách gpt4 ai đã đi

java - 反转 JFrame 边界

In lại 作者:行者123 更新时间:2023-11-30 07:46:26 30 4
mua khóa gpt4 Nike

我正在尝试制作一个弹跳球。设置的边界允许球在超出框架边界后从起点开始。我无法让球弹起来。一旦击中边界(框架的外边缘),如何让球弹起?我相信问题出在 moveBall() 方法中。

主类 导入 javax.swing.JFrame;

public class MainForm {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(220, 270);
mainFrame.setVisible(true);
}

}

二等

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainFrame extends JFrame {

private CustomPanel _panel;

public MainFrame()
{
super("Bouncing Ball");

_panel = new CustomPanel();
add(_panel, BorderLayout.CENTER);
}
}

三等

import java.awt.Graphics;
import javax.swing.JPanel;


public class CustomPanel extends JPanel{

private final BouncingBall _ball1;
private final BouncingBall _ball2;
private final BouncingBall _ball3;

public CustomPanel ()
{
_ball1 = new BouncingBall(this, 20, 3);
Thread thread1 = new Thread(_ball1);
_ball2 = new BouncingBall(this, 40, 6);
Thread thread2 = new Thread(_ball2);
_ball3 = new BouncingBall(this, 60, 9);
Thread thread3 = new Thread(_ball3);

thread1.start();
thread2.start();
thread3.start();
}

@Ghi đè
public void paintComponent(Graphics g)
{
super.paintComponent(g);

_ball1.draw(g);
_ball2.draw(g);
_ball3.draw(g);
}
}

四级

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;


public class BouncingBall implements Runnable {

private JPanel _panel;
private int _xComponent;
private int _yComponent;
private int _sleepDelay;

public BouncingBall(JPanel panel, int startingYPosition, int sleepDelay)
{
_panel = panel;
_xComponent = 0;
_yComponent = startingYPosition;
_sleepDelay = sleepDelay;
}

@Ghi đè
public void run()
{
while(true)
{
thử
{
Thread.sleep(_sleepDelay);

moveBall();
_panel.repaint();
}

catch (InterruptedException ex)
{
Logger.getLogger(BouncingBall.class.getName()).log(Level.SEVERE,null, ex);
}
}
}

public void draw(Graphics g)
{
g.setColor(new Color(255, 0, 0));
g.fillOval(_xComponent, _yComponent, 20, 20);
}

private void moveBall()
{
_xComponent += 2;

Rectangle bounds = _panel.getBounds();

if(_xComponent >= bounds.width)
_xComponent = -_xComponent;
}
}

1 Câu trả lời

您需要反转速度(步数)。

假设边界是相对的,位于 (0, 0),并且从边界内开始。

    x += dx;
y += dy;

if (x < 0 || x > bounds.width) {
dx = -dx;
x += dx;
}
if (y < 0 || y > bounds.height) {
dy = -dy;
y += dy;
}

(x _xComponent 的简写)

关于java - 反转 JFrame 边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871935/

30 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com