java - 如何在不使用按钮和面板的情况下将 ActionListener 添加到 JFrame ?

标签 java swing jframe listener actionlistener

我正在编写一个射击游戏(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);
                        }
                    }
                };

我想将 action 添加到 framePhaseOne 中,如何在不使用 JPanel 和按钮的情况下做到这一点?

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

/**
 * 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);
                }
            });
    }
}

问候

最佳答案

您无法将 ActionListener 添加到 JFrame,它的功能不像按钮,因此没有操作监听器。

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

这是一个例子:

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

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

编辑:

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

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
        }
    } 
});

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

关于java - 如何在不使用按钮和面板的情况下将 ActionListener 添加到 JFrame ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165800/

相关文章:

java - Android 应用程序,Java 的 Google map api 位置验证

java - 单个数组中的两个值从 json 组合起来

java - Like 子句中的 MySQLSyntaxErrorException 错误

java - Java 网格布局

Java - 如何使用 BoxLayout 更改组件高度?

java - 在使用 tomcat server.xml 或 web.xml 创建新日志之前备份日志文件

java - 我的 JScrollPane 滚动到我的 JTable 的倒数第二行,而不是最后一行

Java:JTextField(仍然)在最小化时调整大小(新信息)

java - 如何在 JTextArea 中格式化文本

java - 当我单击 JButton 时,JFrame 组件如何消失?