我正在制作像飞机游戏一样的飞鸟,在一个班级中,我有移动的背景,然后我将它添加到主类中的 jPanel 中,在另一个班级中,我有播放器,我添加了到主 Jpanel。但是,当我将第二个类添加到 JPanel 时,我首先添加的任何一个类都会消失。这是我的背景课程:
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class map1 extends JPanel implements ActionListener{
Timer t = new Timer(5, this);
int rect1x = 1000, rect1y = 0;
int rect2x = 1250, rect2y = 0;
int rect3x = 1500, rect3y = 0;
int rect4x = 1750, rect4y = 0;
int rect5x = 2000, rect5y = 0;
int rect1dx = 1000, rect1dy = 300;
int rect2dx = 1250, rect2dy = 350;
int rect3dx = 1500, rect3dy = 400;
int rect4dx = 1750, rect4dy = 350;
int rect5dx = 2000, rect5dy = 300;
public map1(){t.start();}
public void rectset1(Graphics g){
g.drawRect(rect1x, rect1y, 50, 100);
g.drawRect(rect1dx, rect1dy, 50, 300);
}
public void rect2(Graphics g){
g.drawRect(rect2x, rect2y, 50, 150);
g.drawRect(rect2dx, rect2dy, 50, 300);
}
public void rect3(Graphics g){
g.drawRect(rect3x, rect3y, 50, 200);
g.drawRect(rect3dx, rect3dy, 50, 300);
}
public void rect4(Graphics g){
g.drawRect(rect4x, rect4y, 50, 150);
g.drawRect(rect4dx, rect4dy, 50, 300);
}
public void rect5(Graphics g){
g.drawRect(rect5x, rect5y, 50, 100);
g.drawRect(rect5dx, rect5dy, 50, 300);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
rectset1(g);
rect2(g);
rect3(g);
rect4(g);
rect5(g);
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
rect1x--;
rect2x --;
rect3x --;
rect4x --;
rect5x --;
rect1dx --;
rect2dx --;
rect3dx --;
rect4dx --;
rect5dx --;
}
}
这是我的平面类:import java.awt.Graphics;导入 java.awt.event.ActionEvent;导入 java.awt.event.ActionListener;导入 java.awt.event.KeyEvent;导入 java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class player extends JPanel implements ActionListener, KeyListener {
int x = 200, y = 300;
Timer t = new Timer(5, this);
public void space(){
y+=20;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawOval(x, y, 50, 50);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_SPACE){space();}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
y--;
}
}
最后是我的主要内容: import javax.swing.JFrame;
@SuppressWarnings("serial")
public class testMain extends JFrame{
public testMain(){}
public static void main(String args[]){
map1 m = new map1();
player q = new player();
JFrame j = new JFrame();
j.setSize(800,600);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.add(m);
j.add(q);
j.setVisible(true);
}
}