【发布时间】:2014-05-28 03:40:46
【问题描述】:
我用一个启动 JPanel 的 JFrame 开始我的游戏。当 JPanel 准备好后,该 JPanel 将继续进行下一个。我可以切换到新的 JPanel,但它不响应我的按键。第二个 JPanel 以前运行良好,所以我认为问题在于它们之间的切换。 (我去掉了一些不相关的方法)
public class GameRunner extends JFrame
{
public GameRunner()
{
super("Scrolling Shooter");
Toolkit tk = Toolkit.getDefaultToolkit();
int width = ((int) tk.getScreenSize().getWidth());
int height = ((int) tk.getScreenSize().getHeight());
setSize(width, height);
TitleScreen title = new TitleScreen(this);
((Component)title).setFocusable(true);
getContentPane().add(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{new GameRunner();}
}
public class TitleScreen extends JPanel implements KeyListener, Runnable
{
private JFrame frame; //the JFrame
private ImageItem background; //the background
private String name = ""; //the player's name
/**
* Constructs a title screen
* @param f the JFrame
*/
public TitleScreen (JFrame f)
{
frame = f;
ImageItem fix = new ImageItem();
fix.fixMainPath(); //fixes the main path for all the ImageItems
background = new ImageItem(0, 0, frame.getWidth(), frame.getHeight(), "splashscreen.png"); //makes background stretch between the top and bottom walls
setVisible(true);
addKeyListener(this);
new Thread(this).start();
}
/**
* Draws the stuff on the screen
* @param g some Graphics object
*/
protected void paintComponent(Graphics g)
{
background.draw(g);
if (!(name.equals("")))
{
g.setFont(g.getFont().deriveFont(80f));
g.drawString(name, frame.getWidth() / 3, frame.getHeight() - 60);
}
}
/**
* When a key is typed it is added to the name
* @param key the key typed
*/
public void keyTyped(KeyEvent key)
{
if (!(key.getKeyCode() == KeyEvent.VK_ENTER))
name += key.getKeyChar();
}
/**
* Enter makes moves to the game if the name is ok
* @param key the key pressed
*/
public void keyPressed(KeyEvent key)
{
if (key.getKeyCode() == KeyEvent.VK_ENTER)
{
boolean isValid = false;
if (name.length() > 20)
JOptionPane.showMessageDialog(frame, "That name is too long. Try again.");
if (!name.equals(""))
{
try {if (!hasBannedWord(name)) isValid = true;} //breaks the loop if there are no banned words in the name
catch (FileNotFoundException e) {e.printStackTrace();}
}
if (!isValid)
{
JOptionPane.showMessageDialog(frame, "Bad name. Try again.");
name = "";
}
if (isValid)
{
ScrollingShooter game = new ScrollingShooter(frame, name);
((Component)game).setFocusable(true);
frame.getContentPane().removeAll();
frame.getContentPane().add(game);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
public void run()
{
try
{
while(true)
{
Thread.currentThread().sleep(0);
repaint();
}
}
catch(Exception e){e.printStackTrace();}
}
【问题讨论】:
-
Thread.currentThread().sleep(0); repaint();不是做动画的正确方法。使用 SwingTimer调用repaint()来制作动画。
标签: java swing jframe jpanel keyevent