gpt4 book ai didi

java - 重绘不会更新屏幕

转载 作者:行者123 更新时间:2023-12-02 09:49:16 25 4
gpt4 key购买 nike

我想重新绘制我的屏幕。到目前为止,它所做的只是在第一个屏幕上显示一个点,即头部应该在的位置。这很好,但是我在代码中写道,我希望每秒将头部向下移动 10 像素。我正在打印头部应该在的位置,并且在命令提示符中显示 y 值确实在增加。然而在我的屏幕上,头部没有移动。

我尝试过使用revalidate方法,尝试扩展canvas类而不是jframe,我尝试过仅针对paint方法使用不同的类,我尝试用paintComponent方法替换paint方法。正如你可能知道的那样,我对与 Java 绘画相关的任何事情的理解都不太好。我尝试过阅读这些父类(super class),但它们太复杂了,我无法理解。我也尝试过在没有 sleep 声明的情况下运行。这并不重要。

主类:该类包含开始运行贪吃蛇游戏的主要方法。

import java.util.concurrent.TimeUnit;

public class Main{

public static void main(String[] args) throws InterruptedException {
Main programma = new Main();
programma.rungame();
}

void rungame() throws InterruptedException {
AllGUIElements gui = new AllGUIElements();
gui.gui();
while (true) {
TimeUnit.SECONDS.sleep(1);
gui.setGameScreen();
}
}
}

AllGUIElements 类:此类创建一个新框架,其中包含一个新面板。该面板正在使用paintComponent 进行绘制。 setGameScreen 更新头部的位置并应该重新绘制屏幕。

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

public class AllGUIElements extends JPanel {

private JFrame frame;
private JPanel panel;

private int screen;

Snake hoofd = new Head(new Point(30,30),3,null);

void gui() throws InterruptedException {

frame = new JFrame("Snake Game");
panel = new AllGUIElements();
panel.setBackground(Color.GRAY);
panel.setSize(1000,500);
frame.setSize(1000,500);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

void setGameScreen() {
repaint();
if (hoofd.getDirection() == 1) {
hoofd.setPosition(new Point(hoofd.getPosition().x, hoofd.getPosition().y-10));
}
if (hoofd.getDirection() == 2) {
hoofd.setPosition(new Point(hoofd.getPosition().x+10, hoofd.getPosition().y));

}
if (hoofd.getDirection() == 3) {
hoofd.setPosition(new Point(hoofd.getPosition().x, hoofd.getPosition().y+10));

}
if (hoofd.getDirection() == 4) {
hoofd.setPosition(new Point(hoofd.getPosition().x-10, hoofd.getPosition().y));
}
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 1000, 10);
g.fillRect(0, 0, 10, 500);
g.fillRect(990, 0, 10, 500);
g.fillRect(0, 490, 1000, 10);

g.setColor(Color.GREEN);
g.fillRect(hoofd.getPosition().x, hoofd.getPosition().y, 10, 10);
}

}

Screenobject类:Snake和Food的父类(由于没有必要,所以没有发布),它返回头部、 body 部位和食物的位置。

import java.awt.*;

public class Screenobject{

Point pos;

Screenobject(Point pos){
this.pos = pos;
}

void setPosition(Point pos){
this.pos = pos;
}

Point getPosition() {
return pos;
}
}

Snake 类:Screenobject 的子级,Head 和 Body 的父级。此类设置对象的方向。

import java.awt.*;

public class Snake extends Screenobject{

int direction;
//directions:
//1 = up
//2 = right
//3 = down
//4 = left

Snake nextpart;

Snake(Point pos, int direction, Snake nextpart){
super(pos);
this.direction = direction;
this.nextpart = nextpart;
}

int getDirection() {
return direction;
}
}

Head类:snake的子类,应该是snake链表的第一个对象。

import java.awt.*;

public class Head extends Snake{
Head(Point pos, int direction, Snake nextpart){
super(pos, direction, nextpart);
}
}

body 类别:蛇的子类别,并随着吃的每一种食物而生长。

import java.awt.*;

public class Body extends Snake{
Body(Point pos, int direction, Snake nextpart){
super(pos, direction, nextpart);
}

}

最佳答案

首先要做的事情:

I have used the "Divide and conquer" method to only post the necessary information

是的,您只发布了必要的信息,但您仍然为MCVE / MRE使用了太多的类。 ,理想情况下您的所有代码都适合一个类。

I didn't manage to make it any shorter without omitting code to make it run.

这就是我们要求 MRE 的想法,您应该创建一个全新的程序来隔离问题,在您的情况下,这是:沿某个方向移动形状并继续沿该方向移动。

现在,我可以看到您已经尝试创建它并进行改进,因此我将发布一个示例,说明您将来提出的问题的预期内容,以便您将来提出更好的问题。

话虽这么说,让我们来回答你的问题。

<小时/>

这是一个不到 100 行代码(不包括注释)的示例,可解决代码中的以下问题:

  1. 删除 while(true)支持 Swing 计时器的声明,以防止阻塞事件调度线程 (EDT)

  2. 将程序放在 EDT 上,请参阅 this answer 的第 2 点

  3. 利用 JFrame#pack()方法而不是使用 setSize(...) 手动设置它对于JFrameJPanel

  4. 摆脱了方向的“魔数(Magic Number)”,并使用 enum对于这个问题,因此代码更具可读性,因为我们都知道 TOP应该将其移至顶部,但我们不知道 1应该将其移至顶部。

  5. 利用 Shape用于在 JPanel 上绘制形状的 API如this answer所示

  6. 我还建议使用 camelCase 命名您的方法。这样rungame()变成runGame()因为它更容易阅读,其他方法也是如此。并给它们更有意义的名称,例如 hoofd ,我不知道那是什么,如果我在没有上下文的情况下单独阅读它,将很难说出它是什么类型的对象。

<小时/>
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SnakeGame {
private JFrame frame;
private Snake snake;
private JPanel buttonsPane;
private JButton[] buttons; // Our array of buttons
private Timer timer;
private Direction currentDirection;

// This enum will be used to determine the direction the snake will take.
private enum Direction {
TOP, LEFT, BOTTOM, RIGHT
}

public static void main(String[] args) {
// We place our program on the EDT using Java 8 lambda expressions.
SwingUtilities.invokeLater(() -> new SnakeGame().createAndShowGUI());
}

private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
snake = new Snake();
buttonsPane = new JPanel();
buttons = new JButton[Direction.values().length];

for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(Direction.values()[i].toString()); // We create a JButton with the current value of the direction
buttons[i].addActionListener(listener); // We set their ActionListeners
buttonsPane.add(buttons[i]); // And add them to the buttonsPane
}

currentDirection = Direction.RIGHT; // We set a default direction
timer = new Timer(1000, listener); // And start our Swing Timer

// We add our components and then pack the frame, after that we start the timer.
frame.add(snake);
frame.add(buttonsPane, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
timer.start();
}

// Our ActionListener for moving the snake
private ActionListener listener = e -> { // Using Java 8 lambda expressions again
// We set the current direction using a ternary, if the source of the event is
// the timer we leave the current direction as is
// otherwise we set it to the direction from the button clicked
currentDirection = e.getSource().equals(timer) ? currentDirection : Direction.valueOf(e.getActionCommand());
snake.move(currentDirection); // And we call the move method
};

@SuppressWarnings("serial")
class Snake extends JPanel {
private int xPos;
private int yPos;
private static final int SPEED = 10; // We set the speed as a constant (10 pixels at a time) in any direction

// We determine the movement direction
public void move(Direction direction) {
switch (direction) {
case TOP:
yPos -= SPEED;
break;
case LEFT:
xPos -= SPEED;
break;
case BOTTOM:
yPos += SPEED;
break;
case RIGHT:
xPos += SPEED;
break;
}
this.repaint(); // And repaint the snake
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.DARK_GRAY);
g2d.fill(new Rectangle2D.Double(xPos, yPos, 10, 10)); // We draw a rectangle using the Shape API
}

@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300); // We set the preferredSize of the JPanel to 300 x 300
}
}
}

上面的代码产生以下结果,对于 Java 7 及以下版本,或者如果您不想使用 lambda 表达式或者对您来说太难,请检查此答案的第 2 点,它显示了如何放置程序在没有 lambda 表达式的 EDT 上和 this answer显示如何编写 ActionListener没有它们也是如此。

这就是一个简单的可运行示例,它是完整的、可验证的、最小的,这就是我们在未来的问题中对您的期望。

enter image description here

关于java - 重绘不会更新屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434452/

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