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

一月

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

我想向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);
                }
            });
    }
}

问候

威廉·莫里森

您不能将添加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接口所需的所有方法。

编辑:

在下面的注释中与您交谈之后,您想要的是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
        }
    } 
});

请注意,框架需要重点关注以接收关键事件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在不使用JLabel的情况下将背景图像添加到没有面板的JFrame中?

如何在不使用 jquery 的情况下动态地将禁用属性添加到引导按钮

如何在不使用Texturepacker的情况下将图像添加到Libgdx中的文本按钮?

如何在不使用for循环的情况下将数据从ByteArray添加到链表?

如何在不使用for循环的情况下多次将单个项目添加到arraylist

如何在不使用xml的情况下将进度条添加到画布?

如何在不使用环境变量的情况下将代理添加到Praw?

如何在不使用 estadd 的情况下将文本添加到 esttab 表的底部

如何在不使用RTC的情况下将时间戳添加到SD卡

如何在不覆盖JFrame的情况下将JPanel图形添加到JFrame

如何在不使用IDE的情况下将Maven pom.xml添加到现有项目?

如何在不使用ADD或COPY指令的情况下将文件添加到Dockerfile中的映像

如何在不使用Storyboard segue的情况下从单独的UIViewController将项目添加到UICollectionViewController?

如何在不使用Jquery的情况下将类添加到DOM元素-Angular 6

如何在不使用黑色背景的情况下将粒子系统添加到ios应用

如何在不使用标准算法的情况下将c元素添加到排序向量中?

如何在不使用gradle或Maven或Eclipse的情况下将jar文件添加到Java项目

如何在不使用熊猫的情况下将数据从不同列表添加到 csv 文件中?

如何在没有互联网的情况下使用按钮将图像项添加到 RecyclerView?

在不使用查看器的情况下将按钮添加到Eclipse视图工具栏

如何在不替换使用 NodeJS 的情况下将数据添加到 Firebase?

如何在不使用insertRow的情况下使用JavaScript将表行添加到HTML中的现有表中?

如何在不使用javafx中的observavbleList来仅将最后一行中的数据动态添加到tableView的情况下?

如何在不使用 xml 文件中的 <listener> 标记的情况下以编程方式将 IMethodInterceptor Listener 添加到 testng 套件

如何在不使用boto3删除现有标签的情况下将标签添加到S3存储桶?

Outlook 2007:如何在不使用鼠标的情况下将表格视图中的电子邮件添加到所选内容中?

如何在不使用 Javascript 中的 push 方法的情况下将对象添加到数组中?

如何在不使用Node类的情况下添加到二叉搜索树

R Shiny-如何在不使用全局变量的情况下动态添加到表中?