gpt4 book ai didi

java - 添加 JPanel 时仅显示 JFrame 并且不绘制任何内容

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

我在其中创建了一个 JFrame 和一个 JPanel 。我已经实现了paintComponent,但它什么也没显示,只出现一个空白的JFrame我对此感到困惑。 The picture when the program runs

这是 JPanel 代码

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

/**
*
* @author nguyencong
*/
public class RobotWorld extends JPanel {
public Robot robot;
public PlayField field;

public RobotWorld(Robot robot , PlayField field) {
super();
this.robot = robot;
this.field = field;
this.setSize(field.width , field.height);
this.setVisible(true);
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphic = (Graphics2D)g;
graphic.setBackground(field.fill_Color);
graphic.setColor(robot.color);
graphic.drawOval(robot.x, robot.y, 4, 4);
}

}

这是 JFrame 代码:

import java.awt.Color;
import javax.swing.JFrame;

/**
*
* @author nguyencong
*/
public class GameMain extends JFrame {
public void Game_Start()
{
Robot a = new Robot(10, 10, Color.yellow);
PlayField field = new PlayField(500, 500, Color.BLACK);
RobotWorld world = new RobotWorld(a, field);
this.setSize(field.width , field.height);
this.setLayout(null);
this.add(world);
world.setBounds(0, 0, world.field.width, world.field.height);
this.setVisible(true);
world.repaint();
}

public static void main(String args[])
{
GameMain main = new GameMain();
main.Game_Start();
}
}

这是机器人类代码

import java.awt.Color;

/**
*
* @author nguyencong
*/
public class Robot {
public int x;
public int y;
public Color color;
public final int speed = 2;
Robot(int x , int y , Color color)
{
this.x = x;
this.y = y;
this.color = color;
}
public void move()
{

}
}

Play Field 类代码:

import java.awt.Color;

/**
*
* @author nguyencong
*/
public class PlayField {
public int width;
public int height;
public Color fill_Color;
PlayField(int width , int height , Color fill_Color)
{
this.width = width;
this.height = height;
this.fill_Color = fill_Color;
}
}

他们怎么了?

最佳答案

代码按原样“工作”(但仍有很多需要更改的地方)。为了证明这一点,请将机器人颜色更改为 Color.RED 并将大小从 4 增加到 40。

关于java - 添加 JPanel 时仅显示 JFrame 并且不绘制任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380256/

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