如何使对象在其自己的线程中与其他代码同时运行其命令

时间:2015-11-07 19:16:54

标签: java multithreading swing

所以我有一个迷宫游戏的Gremlin对象

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gremlinrunner;

import java.util.logging.Level;
import java.util.logging.Logger;
import static sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap.Byte0.runnable;

/**
 *
 * @author rohan
 */
public class Gremlin implements Runnable {
/** rest of the implementation not shown for brevity*/
/**
    *Every turn the Gremlin tries to attack (if it can) and then moves
    * it gets sent to a fictional location (one way off the board) if its dead
    * the gremlin can not move because its move method just throws an exception 
    * and catches it when it does
    * almost like a gremlin prison
    */
    public void takeTurn() {

        try{
        if(GremlinRunner.maze[coord[0]][coord[1]][coord[2]][coord[3]]!=127){
//im dead 
            byte[] coordsDead={-127,-127,-127,-127};
            coord=coordsDead.clone();
        }
        doAttack();
        move();
    }
    catch(Exception dead){}
}

    /**
     *time between two moves in milliseconds
     */
    public static final int timeBetweenMoves= 1000;
    @Override
    /**
        * the gremlins typically behavior 
        */
    public void run(){
        while(1==1){
            try {
                Thread.sleep(timeBetweenMoves);
                takeTurn();
            } catch (InterruptedException ex) {
                        takeTurn();
                        GremlinRunner.gui.doMoveDisplay();
            }
        }
    }
}

我的非静态jframe类看起来像这个

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gremlinrunner;

/**
 *
 * @author rohan
 */
import static gremlinrunner.GremlinRunner.maze;
import static gremlinrunner.GremlinRunner.position;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class JFRAME extends javax.swing.JFrame {
static int i=0;
    /**
     * Creates new form JFRAME
     */
    public JFRAME() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
 // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
 private void initComponents() {

  jOptionPane1 = new javax.swing.JOptionPane();
  textArea1 = new java.awt.TextArea();
  textArea2 = new java.awt.TextArea();
  textArea3 = new java.awt.TextArea();
  textArea4 = new java.awt.TextArea();
  textArea5 = new java.awt.TextArea();
  panel1 = new java.awt.Panel();
  jButton1 = new javax.swing.JButton();
  jButton2 = new javax.swing.JButton();
  jButton3 = new javax.swing.JButton();
  jButton4 = new javax.swing.JButton();
  jButton5 = new javax.swing.JButton();
  jButton6 = new javax.swing.JButton();

  jOptionPane1.setMessage("");

  setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

  panel1.setBackground(new java.awt.Color(0, 0, 255));

  jButton1.setText("Up (2d) ");
  jButton1.setToolTipText("Go up in the same floor");
  jButton1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton1.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
   }
  });

  jButton2.setText("Right ");
  jButton2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton2.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
   }
  });

  jButton3.setText("down(2d)");
  jButton3.setToolTipText("Go down in the same floor");
  jButton3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton3.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
   }
  });

  jButton4.setText("Left");
  jButton4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton4.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton4ActionPerformed(evt);
   }
  });

  jButton5.setText("Up(3d)");
  jButton5.setToolTipText("Jump up one floor");
  jButton5.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton5.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton5ActionPerformed(evt);
   }
  });

  jButton6.setText("Down 3D");
  jButton6.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
  jButton6.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton6ActionPerformed(evt);
   }
  });

  javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
  panel1.setLayout(panel1Layout);
  panel1Layout.setHorizontalGroup(
   panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
    .addContainerGap(42, Short.MAX_VALUE)
    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
     .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
     .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
     .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(19, 19, 19))
  );
  panel1Layout.setVerticalGroup(
   panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
    .addContainerGap(59, Short.MAX_VALUE)
    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
      .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
       .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addGap(38, 38, 38))
     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
      .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
       .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(jButton5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
      .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
       .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))))
    .addGap(44, 44, 44))
  );

  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  getContentPane().setLayout(layout);
  layout.setHorizontalGroup(
   layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     .addGroup(layout.createSequentialGroup()
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
       .addComponent(textArea2, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(textArea5, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(textArea3, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
       .addComponent(textArea4, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE))
     .addGroup(layout.createSequentialGroup()
      .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    .addGap(602, 602, 602)
    .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  );
  layout.setVerticalGroup(
   layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
   .addGroup(layout.createSequentialGroup()
    .addComponent(textArea5, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(textArea4, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(textArea3, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(textArea2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(2, 2, 2)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
     .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
     .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(75, Short.MAX_VALUE))
  );

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

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    doMoveDisplay('w');
 }                                        

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        doMoveDisplay('d');
 }                                        

 private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
doMoveDisplay('a');     
 }                                        

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        doMoveDisplay('s');
 }                                        

 private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
doMoveDisplay('v');
 }                                        

 private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
doMoveDisplay('r'); 
 }                                        

/**
    * gets string from pop up dialog box
    * requires a JFRAME class
    * @param prompt is the message
     * @return a string from the pop up window
    */
    public String getStringFromPopUp(String prompt){
    try {
        Thread.sleep(10);
    } catch (InterruptedException ex) {
        Logger.getLogger(JFRAME.class.getName()).log(Level.SEVERE, null, ex);
    }
        JTextArea textArea = new JTextArea();
            textArea.setEditable(true);
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.requestFocus();
            textArea.requestFocusInWindow();
            scrollPane.setPreferredSize(new Dimension(200, 100));
                                                textArea5.setEditable(true);
                                                //writeTo(5,prompt);
                                                JOptionPane.showMessageDialog(
                   this.jOptionPane1, scrollPane,
                    prompt, JOptionPane.PLAIN_MESSAGE);
            String info;
                                                do{
                                                 info = textArea.getText();
                                                }while(info == null);
                                                return info;
    }
    /**
     * 
     */
    public void mainMethod() {
        /* 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(JFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFRAME.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFRAME().setVisible(true);
            }
        });
    }

    /**
     *@fixME this doesn't work 
     * @param field the number of the field to write to 1-6 6 being jText area1
     * @param words String to write
     */
    /*
    public void writeTo(int field, String words) {
        if (field == 1) {
this.textArea1.setText(words);
        } else if (field == 2) {
        this.textArea2.setText(words);
        } else if (field == 3) {
this.textArea3.setText(words);
        }else if(field==4){
            this.textArea4.setText(words);
        }else if(field==5){
            this.textArea5.setText(words);
        }
        else{
            Exception badException=new Exception("Illegal arguments that should"
                                        + "not happen"); 
            try {
                throw badException;
            } catch (Exception ex) {
                Logger.getLogger(JFRAME.class.getName()).log(Level.SEVERE, null, ex);
            }
}
    }
    */
 // Variables declaration - do not modify                     
 private javax.swing.JButton jButton1;
 private javax.swing.JButton jButton2;
 private javax.swing.JButton jButton3;
 private javax.swing.JButton jButton4;
 private javax.swing.JButton jButton5;
 private javax.swing.JButton jButton6;
 private javax.swing.JOptionPane jOptionPane1;
 private java.awt.Panel panel1;
 private java.awt.TextArea textArea1;
 private java.awt.TextArea textArea2;
 private java.awt.TextArea textArea3;
 private java.awt.TextArea textArea4;
 private java.awt.TextArea textArea5;
 // End of variables declaration                   

    /**
        * @param move is a char representing the move
        */
    public void doMoveDisplay(char move) {
GremlinRunner.makeMove(move);
        textArea1.setEditable(true);
textArea1.setText(null);
textArea2.setEditable(true);
textArea2.setText(null);
textArea3.setEditable(true);
textArea3.setText(null);
textArea4.setEditable(true);
textArea4.setText(null);
textArea5.setEditable(true);
textArea5.setText(null);    
dispPosition(2);
    }
        public void doMoveDisplay() {
textArea1.setEditable(true);
textArea1.setText(null);
textArea2.setEditable(true);
textArea2.setText(null);
textArea3.setEditable(true);
textArea3.setText(null);
textArea4.setEditable(true);
textArea4.setText(null);
textArea5.setEditable(true);
textArea5.setText(null);    
dispPosition(2);
    }
        /**
        * prints to console the area around the player "P"
        * @param renderDistance render distance around it
        */
    public void dispPosition(int renderDistance) {
        int floor=6;

        for (int z = position[1] - renderDistance; 
                                        z <= position[1] + renderDistance; z++) {
            String dispMe="";
            for (int y = position[2] - renderDistance; 
                                            y <= position[2] + renderDistance; y++) {
                for (int x = position[3] - renderDistance; 
                                                x <= position[3] + renderDistance; x++) {
                    String symbol = "[!!!]"; //its a gremlin unless its one of the others
                    // a gremlin has code 127
                    try {
                        if (maze[0][z][y][x] == 1) {
                            symbol = "[__]";//pasage
                        } else if (maze[0][z][y][x] == 2) {
                            symbol = "[ P ]";//player
                        } else if (maze[0][z][y][x] == 0) {
                            symbol = "[W]";//wall
                        }else if(maze[0][z][y][x]==3){
                            symbol="[F]";//Finish line
                        }
                    } catch (Exception e) {
// Render walls all around the maze
                        symbol = "[W]";
                    }
                 dispMe+=symbol;
                }
                dispMe+="\n";
            }
        floor--;
        if(floor==1){
            textArea1.setText(dispMe);
        }else if(floor==2){
            textArea2.setText(dispMe);
        }else if(floor==3){
            textArea3.setText(dispMe);
        }else if(floor==4){
            textArea4.setText(dispMe);
            }
        else /**floor ==5*/{
            textArea5.setText(dispMe);
        }
    }
    }
}

我已经声明了这个JFRAME对象的一个​​实例,并将其命名为gui。 我肯定知道这个gui有效。 为什么我的gremlines不会在地图上移动? 此外,当我尝试从anotehr方法调用doMoveDisplay()时,它无法工作。但是它允许我在类的侧面调用doMoveDisplay()和doMoveDisplay(此处为字符)。 我究竟做错了什么? 如何修复我的gremlin run方法,以便gremlins每1000毫秒在地图上移动一次。 我的Gremlin博士有一个跑步方法。然而,它实际上并没有采取行动。当我让所有的gremlins按顺序执行它们时它工作得很好。 主线程也没有捕获gremlin构造函数抛出的异常

1 个答案:

答案 0 :(得分:1)

虽然main方法已经移动了异常将被捕获的点,但是你抛出异常。