1

我正在编写一个射击游戏(FPS - 第一人称射击游戏),并且我正在使用 OpenGl (jogl 1.0) 和 JFrame 。

我想向 JFrame 添加一个 ActionListener :

public class Main extends JDialog { 

private static ActionListener action;
private static JFrame framePhaseOne;
private static JFrame framePhaseTwo;
...
...


                action  = new ActionListener()      // this is for PHASE 2
                {
                    public void actionPerformed(ActionEvent ae)
                    {
                        if (userPoints.getGamePhase())  // if F2 was clicked 
                        {
                            framePhaseTwo = new JFrame(WorldName2);
                            framePhaseTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
                            framePhaseTwo.setLocationByPlatform(true);
                            framePhaseTwo.setLocation(FRAME_LOCATION_X, FRAME_LOCATION_Y);
                            Renderer_PhaseTwo myCanvas2 = new Renderer_PhaseTwo(userPoints);
                            final Animator animator2 = new Animator(myCanvas2);
                            framePhaseTwo.add(myCanvas2);
                            framePhaseTwo.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
                            framePhaseTwo.addWindowListener(new WindowAdapter()
                            {
                                @Override
                                public void windowClosing(WindowEvent e) 
                                {
                                    new Thread() 
                                    {
                                         @Override
                                         public void run() 
                                         {
                                             animator2.stop();
                                             System.exit(0);
                                         }
                                    }.start();
                                }
                            });

                            framePhaseTwo.setVisible(true);
                            animator2.start();
                            myCanvas2.requestFocus();
                            myCanvas2.setFocusable(true);
                        }
                    }
                };

我想添加actionframePhaseOne,我怎么能做到这一点,而不使用 JPanel 和按钮?

如果需要,这是 Main 类的完整代码:

/**
 * This is the main class that runs the First Person Java app 
 * using the OpenGL mechanism , with JOGL 1.0 
 * @author X2
 *
 */
public class Main extends JDialog
{   

    // when true permission granted for starting the game 
    private static boolean start = false; 
    private static final long serialVersionUID = 1L;
    protected static TimerThread timerThread;
    static JStatusBar statusBar = new JStatusBar();
    private static JFrame framePhaseOne;
    private static JFrame framePhaseTwo;
    private static ActionListener action;

    /**
     *  framePhaseOne properties
     */

    private static final int FRAME_LOCATION_X = 300;
    private static final int FRAME_LOCATION_Y = 50;
    private static final int FRAME_SIZE_X = 850; // animator's target frames per second
    private static final int FRAME_SIZE_Y = 700; // animator's target frames per second

    /**
     * start button properties
     */

    private static final int BUTTON_LOCATION_X = (FRAME_SIZE_X / 2) - 100;
    private static final int BUTTON_LOCATION_Y = (FRAME_SIZE_Y / 2) - 50; 
    private static final int BUTTON_SIZE_X = 140; // animator's target frames per second
    private static final int BUTTON_SIZE_Y = 50; // animator's target frames per second


    /**
     *  timer & game title & arrow picture
     */

    private static final String WorldName1 = "FPS 2013 CG Project - Phase 1";
    private static final String WorldName2 = "FPS 2013 CG Project - Phase 2";
    private static final String HARD_TARGET = "src/res/target.jpg";
    private static final String runningOut = "Time is running out - you have : ";

    static int interval;
    static Timer timer1;
    static JLabel changingLabel1 = null;

    static Points userPoints = new Points(); 


    /**
     *  Timer properties
     */

    private static Timer timer;
    private static int count = 60;

    /**
     * ActionListener for timer
     */
    private static ActionListener timerAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            if (start)
            {
                count--;
                if (count == 0)
                    timer.stop();
                changingLabel1.setText(runningOut + count + " seconds" + " , and your points are: " 
                        + userPoints.getPoints()); 
            }

        }
    };


    public static void exitProcedure() {
        System.out.println();
        timerThread.setRunning(false);
        System.exit(0);
    }


        /**
         * Clock timer1 
         * @author X2
         *
         */
        public static class TimerThread extends Thread 
        {

            protected boolean isRunning;

            protected JLabel dateLabel;
            protected JLabel timeLabel;

            protected SimpleDateFormat dateFormat = 
                    new SimpleDateFormat("EEE, d MMM yyyy");
            protected SimpleDateFormat timeFormat =
                    new SimpleDateFormat("h:mm a");

            public TimerThread(JLabel dateLabel, JLabel timeLabel) {
                this.dateLabel = dateLabel;
                this.timeLabel = timeLabel;
                this.isRunning = true;
            }

            @Override
            public void run() {
                while (isRunning) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Calendar currentCalendar = Calendar.getInstance();
                            Date currentTime = currentCalendar.getTime();
                            dateLabel.setText(dateFormat.format(currentTime));
                            timeLabel.setText(timeFormat.format(currentTime));
                        }
                    });

                    try {
                        Thread.sleep(5000L);
                    } catch (InterruptedException e) {
                    }
                }
            }

            public void setRunning(boolean isRunning) {
                this.isRunning = isRunning;
            }

        }




    /**
     *     
     * @param args
     */
    public static void main(String[] args) 
    {

           SwingUtilities.invokeLater(new Runnable() 
            {
                @Override
                public void run() 
                {

                    framePhaseOne = new JFrame(WorldName1);

                    action  = new ActionListener()      // this is for PHASE 2
                    {
                        public void actionPerformed(ActionEvent ae)
                        {
                            if (userPoints.getGamePhase())  // if F2 was clicked 
                            {
                                framePhaseTwo = new JFrame(WorldName2);
                                framePhaseTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
                                framePhaseTwo.setLocationByPlatform(true);
                                framePhaseTwo.setLocation(FRAME_LOCATION_X, FRAME_LOCATION_Y);
                                Renderer_PhaseTwo myCanvas2 = new Renderer_PhaseTwo(userPoints);
                                final Animator animator2 = new Animator(myCanvas2);
                                framePhaseTwo.add(myCanvas2);
                                framePhaseTwo.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
                                framePhaseTwo.addWindowListener(new WindowAdapter()
                                {
                                    @Override
                                    public void windowClosing(WindowEvent e) 
                                    {
                                        new Thread() 
                                        {
                                             @Override
                                             public void run() 
                                             {
                                                 animator2.stop();
                                                 System.exit(0);
                                             }
                                        }.start();
                                    }
                                });

                                framePhaseTwo.setVisible(true);
                                animator2.start();
                                myCanvas2.requestFocus();
                                myCanvas2.setFocusable(true);
                            }
                        }
                    };

                    final Container contentPane = framePhaseOne.getContentPane();
                    contentPane.setLayout(new BorderLayout());

                    /**
                     *  the timer of the count-down
                     */

                    timer = new Timer(1000, timerAction);
                    timer.start();

                    changingLabel1 = new JLabel("Game is offline , hit Start to continue !");
                    statusBar.setLeftComponent(changingLabel1);

                    final JLabel dateLabel = new JLabel();
                    dateLabel.setHorizontalAlignment(JLabel.CENTER);
                    statusBar.addRightComponent(dateLabel);

                    final JLabel timeLabel = new JLabel();
                    timeLabel.setHorizontalAlignment(JLabel.CENTER);
                    statusBar.addRightComponent(timeLabel);

                    contentPane.add(statusBar, BorderLayout.SOUTH);

                    /**
                     *  start button
                     */

                    final JButton startButton = new JButton("Start the game !");
                    // startButton.setBounds(300, 50,140, 50 );
                    startButton.setBounds(BUTTON_LOCATION_X
                                        , BUTTON_LOCATION_Y,
                                          BUTTON_SIZE_X, 
                                          BUTTON_SIZE_Y );

                    startButton.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent event)
                        {
                            start = true;       // start the game
                            userPoints.startGame();
                            contentPane.remove(startButton);
                            contentPane.revalidate();
                            contentPane.repaint();

                        }
                    });                 
                    contentPane.add(startButton);

                    framePhaseOne.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    framePhaseOne.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent event) {
                            exitProcedure();
                        }
                    });

                    timerThread = new TimerThread(dateLabel, timeLabel);
                    timerThread.start();

                    Renderer_PhaseOne myCanvas = new Renderer_PhaseOne(userPoints);
                    final Animator animator = new Animator(myCanvas);

                    Toolkit t = Toolkit.getDefaultToolkit();
                    BufferedImage originalImage = null;

                    try 
                    {
                        originalImage = ImageIO.read(new File(HARD_TARGET));
                    } 

                    catch (Exception e1) {e1.printStackTrace();}
                    Cursor newCursor = t.createCustomCursor(originalImage, new Point(0, 0), "none"); 

                    framePhaseOne.setCursor(newCursor);
                    framePhaseOne.setLocation(FRAME_LOCATION_X, FRAME_LOCATION_Y);
                    framePhaseOne.add(myCanvas);
                    framePhaseOne.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
                    framePhaseOne.addWindowListener(new WindowAdapter()

                    {
                        @Override
                        public void windowClosing(WindowEvent e) 
                        {
                            new Thread() 
                            {
                                 @Override
                                 public void run() 
                                 {
                                     animator.stop();
                                     System.exit(0);
                                 }
                            }.start();
                        }
                    });

                    framePhaseOne.setVisible(true);
                    animator.start();
                    myCanvas.requestFocus();
                    myCanvas.setFocusable(true);
                }
            });
    }
}

问候

4

1 回答 1

2

您不能将 an 添加ActionListener到 a JFrame,它的功能不像按钮,因此没有动作侦听器。

您正在寻找的是MouseListener。它检测鼠标点击。您可能还对提供鼠标移动信息的MouseMotionListener感兴趣。

这是一个例子:

framePhaseOne.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e){
        System.out.println("Mouse was clicked on my frame!");
    }
};

MouseAdapter 是一个实现 MouseListener 的抽象类。它使您不必实现 MouseListener 接口所需的所有方法。

编辑:

在下面的评论中与您交谈后,您正在寻找的是KeyListener。同样,出于与 MouseAdapter 相同的原因,我推荐 KeyAdapter。这是一个例子:

framePhaseOne.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_F2){
            //close frame one.
        }
    } 
});

如果您希望它也关闭您的第一帧,也可以使用 framePhaseTwo 执行此操作。

framePhaseTwo.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent e){
        if(e.getKeyCode()==KeyEvent.VK_F2){
            //close frame one
        }
    } 
});

请注意,框架需要焦点才能接收关键事件。

于 2013-08-10T20:02:13.173 回答