我只是在编写一个java游戏,并且repaint()方法存在问题: 我想从菜单到游戏,所以我删除菜单面板并添加游戏面板(“Zeichnen”扩展JPanel)但每次我尝试重绘时,eclipse给我以下错误:“方法repaint()未定义对于新的ActionListener()类型{}“任何人都可以帮助我吗? :(
代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Frame {
JFrame frame;
JPanel menu;
JButton start;
Zeichnen game;
public Frame() {
start = new JButton("Start Game");
menu = new JPanel();
game = new Zeichnen();
frame = new JFrame("Epic Game");
start.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
frame.remove(menu);
frame.add(game);
repaint();
}});
frame.setVisible(true);
frame.setSize(640,480);
game.addKeyListener(new Listener(game));
menu.add(start);
frame.add(menu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
}
答案 0 :(得分:2)
Suggestsions:
例如:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ContentPane extends JPanel {
public static final String MENU = "menu";
public static final String GAME = "game";
private static final int PREF_W = 640;
private static final int PREF_H = 480;
private CardLayout cardlayout = new CardLayout();
private JPanel menu = new JPanel();
private JButton start;
private Zeichnen game;
public ContentPane() {
setLayout(cardlayout);
start = new JButton("Start Game");
game = new Zeichnen();
add(menu, MENU);
add(game, GAME);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardlayout.next(ContentPane.this);
}
});
menu.add(start);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Epic Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
关键绑定:
@SuppressWarnings("serial")
class Zeichnen extends JPanel {
private static final String DOWN = "down";
public Zeichnen() {
int condition = WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), DOWN);
actionMap.put(DOWN, new AbstractAction(DOWN) {
{
putValue(ACTION_COMMAND_KEY, DOWN);
}
@Override
public void actionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommand());
}
});
}
}
答案 1 :(得分:1)
你需要调用game.repaint(),因为你创建的匿名类有没有方法,名为repaint()
答案 2 :(得分:1)
那是因为该结构中的任何类都没有方法(即Frame
→匿名ActionListener
)扩展Component
且具有repaint
方法。
您可以让主Frame
课程延长JFrame
,或致电game.repaint()
。你可能想做前者。