[英]Just show the JFrame and don't paint anything when add a JPanel to it
I create a JFrame and a JPanel inside it.我在其中创建了一个 JFrame 和一个 JPanel。 I've implemented the paintComponent but it shows nothing, Just a blank JFrame appears I'm confused with it.
我已经实现了paintComponent,但它什么也没显示,只是一个空白的 JFrame 似乎我对它感到困惑。 The picture when the program runs
程序运行时的画面
This the JPanel code这是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);
}
}
And this is the JFrame code:这是 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();
}
}
And this is Robot class code这是机器人 class 代码
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 class code:运动场 class 代码:
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;
}
}
What's wrong with them??他们怎么了??
The code 'works' as is (but still has much that needs changing).代码按原样“工作”(但仍有很多需要更改的地方)。 To prove this, change the robot color to
Color.RED
and increase the size from 4 to 40.为了证明这一点,将机器人颜色更改为
Color.RED
,并将大小从 4 增加到 40。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.