我还是Java新手。这是我的程序,当你点击我的菜单下的'Slow'时,随机地在我的阵列中的不同位置画一个'mole'。但是我无法得到任何东西。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.*;
public class WackAmole extends JFrame{
MolePanel molePanel = new MolePanel();
JMenu file = new JMenu("File");
JMenuItem exitItem = new JMenuItem("EXIT GAME");
JMenu gameSpeed = new JMenu("Game Speed");
JMenuItem slow= new JMenuItem("Slow");
JMenuItem normal = new JMenuItem("Normal");
JMenuItem fast = new JMenuItem("Fast");
JLabel score = new JLabel("Score");
JLabel time = new JLabel("Elasped Time");
public void createGUI(){
JPanel scoreBoard = new JPanel(new FlowLayout(FlowLayout.CENTER));
scoreBoard.add(score);
scoreBoard.add(time);
JFrame frame = new JFrame("WHACK 'A' MOLE");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scoreBoard);
gameSpeed.add(slow);
gameSpeed.add(normal);
gameSpeed.add(fast);
file.add(exitItem);
file.add(gameSpeed);
JMenuBar menuBar = new JMenuBar();
menuBar.add(file);
frame.setJMenuBar(menuBar);
slow.addActionListener(new ButtonListener());
exitItem.addActionListener(new ButtonListener());
frame.setPreferredSize(new Dimension(600,400));
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args){
//show the frame
WackAmole wackAmole = new WackAmole();
wackAmole.createGUI();
}
public class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent e){
if (e.getActionCommand().equals("EXIT GAME")){
System.exit(0);
}
if (e.getActionCommand().equals("Slow")){
// this button works... it receives input
molePanel.aMole();
}
}
}
}
文件2:
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
public class MolePanel extends JPanel{
Random random = new Random();
private static final long serialVersionUID = 1L;
private int xCoord[] = {-1, -1};
private int yCoord[] = {-1, -1};
private Dimension preferredSize = new Dimension(300,200);
int x = random.nextInt(2);
int y = random.nextInt(2);
public void aMole (){
xCoord[x] +=25;
yCoord[y] +=25;
repaint();
}
@Override
public Dimension getPreferredSize(){
return preferredSize;
}
protected void paintComponent (Graphics mole){
if(xCoord[x] < 0 || yCoord[y] < 0){
xCoord[x] = 25;
yCoord[y] = 25;
}
super.paintComponent(mole);
mole.fillOval(xCoord[x], yCoord[y], 10, 10);
}
}