我正在创建一个简单的Java游戏,我对此很陌生。我的问题是我为我的游戏创建了想要添加到屏幕的对象和玩家。我所做的是我已将这些对象添加到一个JPanel中,我稍后会在该帧上添加这些对象。只显示我的对象,但播放器没有出现。我已经尝试创建两个单独的jpanels,我添加到框架上,但这不起作用
public GameViewer(Board b) {
PlayerPiece player = new PlayerPiece();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(player);
panel.addKeyListener(player);
panel.add(new GameComponent(b));
frame.setLayout(new BorderLayout());
//background image// frame.add(image, BorderLayout.CENTER); ****
frame.setSize(WIDTH,HEIGHT);
frame.add(panel, BorderLayout.CENTER);
更多进口*
public class PlayerPiece extends JPanel implements ActionListener, KeyListener{
Timer playTimer = new Timer(5,this);
int positionX = 150, positionY = 360, speedX = 0, speedY = 0;
public PlayerPiece(){
playTimer.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(positionX, positionY,50,30);
}
Further on I only have keyevents
@覆盖 public void actionPerformed(ActionEvent e){
if (positionX < 0){ //If the player is outside of the frame stop it
speedX = 0;
positionX = 0;
}
if (positionX > 300){ //Right side but outside of the screen, block it
speedX = 0;
positionX = 300;
}
if (positionY < 0){
speedY = 0;
positionY = 0;
}
if (positionY > 360){
speedY = 0;
positionY = 360;
}
positionX = positionX + speedX;
positionY = positionY + speedY;
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode(); //Get the button pressed
if(keyCode == KeyEvent.VK_RIGHT) { //Go Right
speedX = 2;
speedY = 0;
}
if(keyCode == KeyEvent.VK_DOWN) { //Go Down
speedX = 0;
speedY = 2;
}
if(keyCode == KeyEvent.VK_LEFT) { //Go Left
speedX = -2;
speedY = 0;
}
if(keyCode == KeyEvent.VK_UP) { //Go up
speedX = 0;
speedY = -2;
}
}
@Override
public void keyReleased(KeyEvent e) {
speedX = 0;
speedY = 0;
}
@Override
public void keyTyped(KeyEvent e) {
}
}
答案 0 :(得分:0)
您没有告诉我们PlayerPiece
是什么,所以我用一个按钮替换它。您发布的代码应该有效,因此问题必须在PlayerPiece
。
所以要修复它,将PlayerPiece
替换为另一个对象,如Button,并确保按钮显示。然后查看你的PlayerPiece
课程,并在那里找到问题。
更新:我认为你的问题是PlayerPiece(它只是另一个JPanel)显示在框架之外。试试下面的代码,你会发现它确实出现了。我省略了代码的不相关部分,例如事件监听器。
import java.awt.BorderLayout;
import java.awt.Button;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Test");
PlayerPiece player = new PlayerPiece();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(player);
frame.setLayout(new BorderLayout());
frame.setSize(400,400);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class PlayerPiece extends JPanel {
int positionX = 150, positionY = 150;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(positionX, positionY,50,30);
}
}