所以我试图在我的JFrame'框架中添加多个类。使用JPanel'面板'但它似乎没有任何效果。这是我的主要课程:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame
{
public static void main (String[] args)
{
JPanel panel = new JPanel();
panel.setBackground (Color.WHITE);
panel.add (new Player()); // Class with paintComponent method.
panel.add (new Terrain()); // Class with paintComponent method.
JFrame frame = new JFrame ("Java Game");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (1000, 600);
frame.getContentPane().add (panel);
frame.setVisible (true);
}
}
当我运行程序时,JFrame显示为白色背景,但是没有调用Player和Terrain类中的paintComponent方法,因此没有其他任何东西被渲染。这段代码有什么问题吗?感谢。
编辑:这是我的玩家和地形类:
播放器:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
@SuppressWarnings ("serial")
public class Player extends JComponent
{
int x = 50;
int y = 450;
public void paintComponent (Graphics graphics)
{
graphics.setColor (Color.BLACK);
graphics.fillRect (x, y, 50, 50);
}
}
地形:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;
@SuppressWarnings ("serial")
public class Terrain extends JComponent
{
Player playerClass = new Player();
public void paintComponent (Graphics graphics)
{
graphics.setColor (Color.GREEN);
graphics.fillRect (0, 500, 1000, 500);
}
}
答案 0 :(得分:2)
getPreferredSize
和Player
的{{1}},导致它们的默认大小为Terrain
0x0
就打破了画颜链,这可能导致绘画问题和文物无法结束super.paintComponent
中Player
的引用与屏幕上的引用无关查看Laying Out Components Within a Container,Painting in AWT and Swing和Performing Custom Painting了解详情