如何将多个类添加到单个JFrame? [英] How to add multiple classes to a single JFrame?
问题描述
因此,我尝试使用JPanel面板"将多个类添加到我的JFrame框架"中,但这似乎没有任何效果.这是我的主班:
So I'm trying to add multiple classes to my JFrame 'frame' using a JPanel 'panel' but it doesn't seem to have any effect. Here's my main class:
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方法,因此未呈现任何其他内容.这段代码有什么问题吗?谢谢.
When I run the program, the JFrame appears with a white background, but the paintComponent methods from the Player and Terrain classes aren't being called, so nothing else is being rendered. Is there anything wrong with this code? Thanks.
这是我的Player和Terrain类:
Here are my Player and Terrain classes:
玩家:
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);
}
}
推荐答案
- 您无法覆盖
Player
和Terrain
的getPreferredSize
,导致它们以默认大小0x0
进行布局
- 您通过不调用
super.paintComponent
破坏了绘画链,这可能导致绘画问题和伪像无休止地 -
Terrain
中Player
的引用与屏幕上的引用无关
- You've failed to override
getPreferredSize
ofPlayer
andTerrain
, causing them to be laid out at their default size of0x0
- You've broken the paint chain by not calling
super.paintComponent
, which could cause no end of painting issues and artifacts - The reference of
Player
inTerrain
has nothing to do with the reference on the screen
看看布置容器内的组件 , AWT和Swing中的绘画和
Take a look at Laying Out Components Within a Container, Painting in AWT and Swing and Performing Custom Painting for more details
这篇关于如何将多个类添加到单个JFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!