如何将多个类添加到单个JFrame?

时间:2015-02-03 03:17:59

标签: java swing jframe jpanel paintcomponent

所以我试图在我的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);
    }
}

1 个答案:

答案 0 :(得分:2)

  1. 您未能覆盖getPreferredSizePlayer的{​​{1}},导致它们的默认大小为Terrain
  2. 你没有调用0x0就打破了画颜链,这可能导致绘画问题和文物无法结束
  3. super.paintComponentPlayer的引用与屏幕上的引用无关
  4. 查看Laying Out Components Within a ContainerPainting in AWT and SwingPerforming Custom Painting了解详情