如何将多个类添加到单个JFrame? [英] How to add multiple classes to a single JFrame?

查看:179
本文介绍了如何将多个类添加到单个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);
    }
}

推荐答案

  1. 您无法覆盖PlayerTerraingetPreferredSize,导致它们以默认大小0x0
  2. 进行布局
  3. 您通过不调用super.paintComponent破坏了绘画链,这可能导致绘画问题和伪像无休止地
  4. TerrainPlayer的引用与屏幕上的引用无关
  1. You've failed to override getPreferredSize of Player and Terrain, causing them to be laid out at their default size of 0x0
  2. You've broken the paint chain by not calling super.paintComponent, which could cause no end of painting issues and artifacts
  3. The reference of Player in Terrain 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆