【发布时间】:2019-10-14 15:57:20
【问题描述】:
我在其中创建了一个 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;
}
}
他们怎么了??
【问题讨论】:
-
如果没有
Robot和PlayField,我们将无法重现您的问题;但this.setLayout(null);绝不是个好主意。 -
@ElliottFrisch 我已经添加了该代码。我知道这不是一个好主意但是当我不设置布局时,结果是一样的
-
@ElliottFrisch 我不会说永远不会。如果你想做绝对定位(不管你是否同意),你应该
setLayout(null)。 -
你为什么要扩展
JFrame?你没有压倒任何东西。所以最好使用JFrame的实例。 -
@ThànhCông,我知道这不是一个好主意 - 然后不要使用它。问一个表明您正在使用“良好”编程实践的问题。如果您坚持使用不良做法,我们不会为您提供帮助,因为这些做法很容易导致问题。花时间学习良好的编程实践,减少错误实践导致的调试问题。