问题
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:
- 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
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