在另一个类中调用JFrame表单时遇到麻烦

时间:2019-12-07 10:03:19

标签: java swing jframe

我正在为小组项目制作一只飞扬的小鸟克隆。游戏运行良好,并且JFrame表单分别运行良好。问题是,每当触发屏幕游戏时,我都希望JFrame表单可见。但我无法终生使它弹出。 这是主要类别。(游戏本身)     软件包flappyBird;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.Timer;

                //inheariting other classes to use their functions
public class FlappyBird implements ActionListener, MouseListener, KeyListener
{

    public static class Information{
       // private JLabel lbl1;

        public Information(){

        }

        private void setVisible(boolean b) {

            if(gameOver){
       //   new Information().setVisible(true);

            }

            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    }
    public static FlappyBird flappyBird;

    public final int WIDTH = 800, HEIGHT = 600;

    public Renderer renderer;

    public Rectangle bird;

    public ArrayList<Rectangle> columns;
                         //motion of the player on the Y axis
    public int ticks, yMotion, score, send;
      //game start and game end flags.
    public boolean started;
        public static boolean gameOver;

    public Random rand;

    public  FlappyBird()
    {       //objects of timer and JFrame class
        JFrame jframe = new JFrame();
        Timer timer = new Timer(20, this);


        renderer = new Renderer();
        rand = new Random();
                //adjusting our jframe

        jframe.add(renderer);
        jframe.setTitle("Bouncy Ball");
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setSize(WIDTH, HEIGHT);
        jframe.addMouseListener(this);
        jframe.addKeyListener(this);
        jframe.setResizable(false);
        jframe.setVisible(true);
                //creating the player,
        bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);
        columns = new ArrayList<Rectangle>();
              /*
                adding 4 columns because there are 2 obsticles on the screen 
                at a time and we need a gap to go through.
                */
        addColumn(true);
        addColumn(true);
        addColumn(true);
        addColumn(true);

        timer.start();
    }
        //adding oscticles in the game  
    public void addColumn(boolean start)
    {
        int space = 300;
        int width = 100;
              //using a random number for the hight of the obsticle
              //so the gap appears at a random spot on the obsticle
        int height = 50 + rand.nextInt(300);

        if (start)
        {   //this is out starting column obsticle
                    //the gap appears in the middle
        columns.add(new Rectangle(WIDTH + width + columns.size() * 300, HEIGHT - height - 120, width, height));
        columns.add(new Rectangle(WIDTH + width + (columns.size() - 1) * 300, 0, width, HEIGHT - height - space));
        }
        else
        {   //this is the other column it changes relative to the 1st 
                    //colomn. hence we are getting the size of the previous column
        columns.add(new Rectangle(columns.get(columns.size() - 1).x + 600, HEIGHT - height - 120, width, height));
        columns.add(new Rectangle(columns.get(columns.size() - 1).x, 0, width, HEIGHT - height - space));
        }
    }
        //coloring obsticles so they stick out
    public void paintColumn(Graphics g, Rectangle column)
    {
        g.setColor(Color.green.darker());
        g.fillRect(column.x, column.y, column.width, column.height);
    }

    public void jump()
    {                                                                              //time stamp 51:18
        if (gameOver)
        {
            bird = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 20, 20);
                     //clearing the obsticles from the array in order to restart
                     //also resetting position of the player.   
            columns.clear();
            yMotion = 0;
            score = 0;

            addColumn(true);
            addColumn(true);
            addColumn(true);
            addColumn(true);

            gameOver = false;

        }

        if (!started)
        {
            started = true;
        }
        else if (!gameOver)
        {
        if (yMotion > 0)
        {
        yMotion = 0;
        }
        yMotion -= 10;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {   //the speed at which the obsticles move
        int speed = 8;

        ticks++;
//(started) won't let the player move untill the player inputs something
    if (started)
    {   for (int i = 0; i < columns.size(); i++)
    {   Rectangle column = columns.get(i);
        column.x -= speed;
    }
        if (ticks % 2 == 0 && yMotion < 15)
        {
            yMotion += 2;
        }
        for (int i = 0; i < columns.size(); i++)
        {
            Rectangle column = columns.get(i);
            if (column.x + column.width < 0)
            {
    //removing obsticles from the array so it dosent overflow as we play
            columns.remove(column);

            if (column.y == 0)
            {
            addColumn(false);
            }
            }
            }

        bird.y += yMotion;
//the reason we have another for loop here is so that the obsticle 
//constently keep spawning.
    for (Rectangle column : columns)
    {
    if (column.y == 0 && bird.x + bird.width / 2 > column.x + column.width / 2 - 10 && bird.x + bird.width / 2 < column.x + column.width / 2 + 10)
    {
    score++;
        send=score;
    }
//checking for collision(if the player hits the obsticle)
    if (column.intersects(bird))
    {//triggering game over flag
    gameOver = true;


    if (bird.x <= column.x)
    {
    bird.x = column.x - bird.width;
    }
    else
    {
    if (column.y != 0)
    {
    bird.y = column.y - bird.height;
    }
    else if (bird.y < column.height)
    {
    bird.y = column.height;
    }
    }
    }
    }
//checing if the player hits the ceiling or floor of the map
// it will also trigger a game over flag.
        if (bird.y > HEIGHT - 120 || bird.y < 0)
        {
        gameOver = true;
        }

        if (bird.y + yMotion >= HEIGHT - 120)
        {
            bird.y = HEIGHT - 120 - bird.height;
            gameOver = true;
                        //new Information().setVisible(true);
        }
        }

        renderer.repaint();
    }
        //transfering score value to the JFrame.
        public int sendNum(){
            if(score !=0){
             return send;   
            }
            else{
               return 0;
            }
        }

        public void nfo(){
            if(gameOver){

            }
        }

    public void repaint(Graphics g)
    {
        g.setColor(Color.cyan);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        g.setColor(Color.orange);
        g.fillRect(0, HEIGHT - 120, WIDTH, 120);

        g.setColor(Color.blue);
        g.fillRect(0, HEIGHT - 120, WIDTH, 20);

        g.setColor(Color.red);
        g.fillRect(bird.x, bird.y, bird.width, bird.height);
              //for each loop
        for (Rectangle column : columns)
        {
            paintColumn(g, column);
        }
              //the game start and game over screen.
        g.setColor(Color.black);
        g.setFont(new Font("Arial", 1, 100));

        if (!started)
        { //instruction for the player before they start
            g.drawString("Click to start!", 75, HEIGHT / 2 - 50);
        }

        if (gameOver)
        { //game over screen
            g.drawString("Game Over!", 100, HEIGHT / 2 - 50);
                        inFo();

        }

                if (gameOver){
                     //Information nfo=new Information(); 
                     // nfo.setVisible(gameOver);
                   // new Information().setVisible(gameOver);

                }

        if (!gameOver && started)
        {
            g.drawString(String.valueOf(score), WIDTH / 2 - 25, 100);
        }

    }

        public static void inFo(){
            System.out.println("hello world");

            new Information().setVisible(true);
           // if(gameOver){
                    //Information nfo=new Information();                       

                // throw new UnsupportedOperationException("Not supported yet.");
                 //i was running out of memory
                 //i have changed java heap space   
             //   }

        }
    public static void main(String[] args)
    {

       flappyBird = new FlappyBird();

    }

    @Override
    public void mouseClicked(MouseEvent e)
    {
        jump();
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
        if (e.getKeyCode() == KeyEvent.VK_SPACE)
        {
            jump();
        }
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
    }

    @Override
    public void mouseEntered(MouseEvent e)
    {
    }

    @Override
    public void mouseExited(MouseEvent e)
    {
    }

    @Override
    public void keyTyped(KeyEvent e)
    {

    }

    @Override
    public void keyPressed(KeyEvent e)
    {

    }

}

这是第二个用于渲染对象的类

    package flappyBird;

import java.awt.Graphics;

import javax.swing.JPanel;

public class Renderer extends JPanel
{

    private static final long serialVersionUID = 1L;

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        FlappyBird.flappyBird.repaint(g);
    }

}

这是第三个类,它是JFrame形式

    package flappybird;

import javax.swing.*;
import java.util.*;

public class Information extends javax.swing.JFrame {

    /**
     * Creates new form Information
     */
    public int Num;
    public Information() {

        initComponents();

      // FlappyBird Flap=new FlappyBird();
      // Num=Flap.sendNum();


    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField2 = new javax.swing.JTextField();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        D1 = new javax.swing.JDialog();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        D2 = new javax.swing.JDialog();
        emptyBorder1 = (javax.swing.border.EmptyBorder)javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1);
        jLabel1 = new javax.swing.JLabel();
        NameField = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Field1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        MenuClose = new javax.swing.JMenuItem();

        jTextField2.setText("jTextField2");

        jMenuItem2.setText("jMenuItem2");

        jMenuItem3.setText("jMenuItem3");

        jMenuItem5.setText("jMenuItem5");

        D1.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        D1.getContentPane().setLayout(new java.awt.CardLayout());

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setText("Hello there");
        jScrollPane2.setViewportView(jTextArea1);

        D1.getContentPane().add(jScrollPane2, "card2");

        D2.getContentPane().setLayout(new java.awt.CardLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("High Scores");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jLabel1.setText("Enter your name ");

        NameField.setFocusCycleRoot(true);
        NameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NameFieldActionPerformed(evt);
            }
        });

        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        Field1.setColumns(20);
        Field1.setRows(5);
        jScrollPane1.setViewportView(Field1);

        jButton2.setText("Close");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("How to play");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem4.setText("About");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem4);

        MenuClose.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        MenuClose.setText("Close");
        MenuClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MenuCloseActionPerformed(evt);
            }
        });
        jMenu1.add(MenuClose);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NameField, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(NameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        this.dispose();
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       //if(Num !=0){
       // Field1.append(""+ Num);
    //}
    }                                        

    private void MenuCloseActionPerformed(java.awt.event.ActionEvent evt) {                                          
      this.dispose();
    }                                         

    private void NameFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          

    }                                         

    private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
       //HowToPlay.setVisible(false);
    }                                    

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
     D1.setVisible(true); 
     D1.setSize(375, 372);
     D1.setLocationRelativeTo(null);
    }                                          

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {                                           
    D2.setVisible(true);  
    D2.setSize(375, 372);
    D2.setLocationRelativeTo(null);
    }                                          


    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Information.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Information.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Information.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Information.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Information().setVisible(true);
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JDialog D1;
    private javax.swing.JDialog D2;
    private javax.swing.JTextArea Field1;
    private javax.swing.JMenuItem MenuClose;
    private javax.swing.JTextField NameField;
    private javax.swing.border.EmptyBorder emptyBorder1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                   
}

0 个答案:

没有答案