How to add multiple classes to a single JFrame?

筅森魡賤 提交于 2019-12-25 04:06:04

问题


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);
    }
}

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.

Edit: Here are my Player and Terrain classes:

Player:

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);
    }
}

Terrain:

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:


  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

Take a look at Laying Out Components Within a Container, Painting in AWT and Swing and Performing Custom Painting for more details



来源:https://stackoverflow.com/questions/28290768/how-to-add-multiple-classes-to-a-single-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!