public void windowClosing(WindowEvent e) // write file on finish
     {
   FileOutputStream out = null;
   ObjectOutputStream data = null;
   try {
     // open file for output
     out = new FileOutputStream(DB);
     data = new ObjectOutputStream(out);
     // write Person objects to file using iterator class
     Iterator<Person> itr = persons.iterator();
     while (itr.hasNext()) {
       data.writeObject((Person) itr.next());
     }
     data.flush();
     data.close();
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         objUpdate.this,
         "Error processing output file" + "\n" + ex.toString(),
         "Output Error",
         JOptionPane.ERROR_MESSAGE);
   } finally {
     System.exit(0);
   }
 }
  private void doSave() {
    ObjectOutputStream objectStream = getObjectOutputStream();

    if (objectStream != null) {
      try {
        System.out.println("Saving " + selectedChildrenPaths.size() + " Selected Generations...");

        for (int i = 0; i < selectedChildrenPaths.size(); i++) {
          // Get the userObject at the supplied path
          Object selectedPath =
              ((TreePath) selectedChildrenPaths.elementAt(i)).getLastPathComponent();
          DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath;

          objectStream.writeObject(selectedNode.getUserObject());
        }

        objectStream.close();
        System.out.println("Save completed successfully.");
      } catch (IOException e) {
        System.err.println(e);
      }
    } else {
      System.out.println("Save Selected Files has been aborted!");
    }
  }
Ejemplo n.º 3
0
 /**
  * A getter for the high scores list. Reads it directly from file and throws an error if the file
  * is not found (!working on this!).
  *
  * @return Object[][] where [i][0] is the rank (String), [i][1] is the name (String) and [i][2] is
  *     the score (Integer).
  */
 public static Object[][] getHighScore() {
   if (!new File("HighScores.dat").exists()) {
     // This object matrix actually stores the information of the high scores list
     Object[][] highScores = new Object[10][3];
     // We fill the high scores list with blank entries:  #.    " "    0
     for (int i = 0; i < highScores.length; i++) {
       highScores[i][0] = (i + 1) + ".";
       highScores[i][1] = " ";
       highScores[i][2] = 0;
     }
     // This actually writes and makes the high scores file
     try {
       ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
       o.writeObject(highScores);
       o.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   try {
     // Read and return the read object matrix
     ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
     Object[][] highScores = (Object[][]) o.readObject();
     o.close();
     return highScores;
   } catch (IOException | ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 4
0
 // Utility methods
 // Send message to client
 private void sendMessage(String message) {
   try {
     output.writeObject("KELVIN: " + message);
     output.flush();
     showMessage("\nKELVIN: " + message);
   } catch (IOException ioException) {
     chatWindow.append("\n ERROR: CANNOT SEND MESSAGE! \n");
   }
 }
Ejemplo n.º 5
0
 private void writeSerializedContents(File file) {
   try {
     ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
     objectOutputStream.writeObject(getQuizFromContents());
     objectOutputStream.flush();
     objectOutputStream.close();
   } catch (Exception ex) {
     exceptionErrorDialog(ex);
   }
 }
Ejemplo n.º 6
0
 // saves the current configuration (breakpoints, window sizes and positions...)
 private void saveConfig() {
   try {
     ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(idxName + ".config"));
     Breakpoints.save(out);
     Properties.save(out);
     out.close();
   } catch (IOException exc) {
     consoleFrame.echoInfo("Could not save settings: " + exc);
   }
 }
 /**
  * sends a message to the server, and to the other clients
  *
  * @param message: message to be sent
  */
 public void sendMessage(String message) {
   try {
     System.out.println("Sending a message..." + message);
     toChatServer.writeObject(new String(message));
     toChatServer.flush();
   } catch (IOException e) {
     System.out.println("IOException in sendMessage");
     System.err.println(e);
     System.exit(1);
   }
 }
 private void saveObject(Object obj, String fName) {
   try {
     FileOutputStream fos = new FileOutputStream(fName);
     ObjectOutputStream oos = new ObjectOutputStream(fos);
     oos.writeObject(obj);
     oos.flush();
     oos.close();
     fos.close();
   } catch (IOException ex) {
     JOptionPane.showMessageDialog(this, "Problemos saugojant Objektus");
   }
 }
 /** Start talking to the server */
 public void start() {
   String codehost = getCodeBase().getHost();
   if (socket == null) {
     try {
       // Open the socket to the server
       socket = new Socket(codehost, port);
       // Create output stream
       out = new ObjectOutputStream(socket.getOutputStream());
       out.flush();
       // Create input stream and start background
       // thread to read data from the server
       in = new ObjectInputStream(socket.getInputStream());
       new Thread(this).start();
     } catch (Exception e) {
       // Exceptions here are unexpected, but we can't
       // really do anything (so just write it to stdout
       // in case someone cares and then ignore it)
       System.out.println("Exception! " + e.toString());
       e.printStackTrace();
       setErrorStatus(STATUS_NOCONNECT);
       socket = null;
     }
   } else {
     // Already started
   }
   if (socket != null) {
     // Make sure the right buttons are enabled
     start_button.setEnabled(false);
     stop_button.setEnabled(true);
     setStatus(STATUS_ACTIVE);
   }
 }
Ejemplo n.º 10
0
 public synchronized void sendClientData(String name, ObjectOutputStream out) throws IOException {
   for (ClientData cd : clientList)
     if (cd.getName().equals(name)) {
       out.writeObject(cd);
       return;
     }
 }
 /** Stop talking to the server */
 public void stop() {
   if (socket != null) {
     // Close all the streams and socket
     if (out != null) {
       try {
         out.close();
       } catch (IOException ioe) {
       }
       out = null;
     }
     if (in != null) {
       try {
         in.close();
       } catch (IOException ioe) {
       }
       in = null;
     }
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException ioe) {
       }
       socket = null;
     }
   } else {
     // Already stopped
   }
   // Make sure the right buttons are enabled
   start_button.setEnabled(true);
   stop_button.setEnabled(false);
   setStatus(STATUS_STOPPED);
 }
Ejemplo n.º 12
0
 /**
  * This method saves the current MOCOData into a serialized file
  *
  * @param saveAs The name of the outputfile
  */
 public void saveObject(String saveAs) {
   File sFile = new File(saveAs);
   try {
     ObjectOutputStream oo =
         new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile)));
     oo.writeObject(this.state);
     oo.close();
   } catch (Exception ex) {
     if (this.mainFrame != null) {
       JOptionPane.showMessageDialog(
           this.mainFrame,
           "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(),
           "Save object",
           JOptionPane.ERROR_MESSAGE);
     } else {
       System.out.println("Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage());
     }
   }
 }
Ejemplo n.º 13
0
 // Close crap after chatting
 private void closeCrap() {
   showMessage("\n Closing connection... \n ");
   ableToType(false);
   try {
     output.close();
     input.close();
     connection.close();
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
  private void jMenuItemSaveLSAResultsActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItemSaveLSAResultsActionPerformed
    if (this.currentResults != null) {
      JFileChooser jfc = new JFileChooser();
      int fileDialogReturnVal = jfc.showSaveDialog(this);

      if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
        try {
          File outputFile = jfc.getSelectedFile();
          FileOutputStream fos = new FileOutputStream(outputFile);
          ObjectOutputStream oos = new ObjectOutputStream(fos);

          oos.writeObject(this.currentResults);
        } catch (IOException e) {
          System.out.println("IOexception");
          System.out.println(e.getMessage());
        }
      }
    }
  } // GEN-LAST:event_jMenuItemSaveLSAResultsActionPerformed
Ejemplo n.º 15
0
 /**
  * Defines each button's actions
  *
  * @param e Required ActionEvent
  */
 @Override
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == returns) {
     this.setVisible(false);
     backMenu.sounds.sound.sfx.stop();
     backMenu.dispose();
     configSave[0] = (float) musicSlider.getValue();
     configSave[1] = (float) volumeSlider.getValue();
     try {
       try (ObjectOutputStream salidaObjs =
           new ObjectOutputStream(new FileOutputStream("Saves" + File.separator + "config.dat"))) {
         salidaObjs.writeObject(configSave);
       }
     } catch (IOException ex) {
       System.out.println(ex.getMessage());
     }
     menu = new Menu();
     this.dispose();
   }
 }
Ejemplo n.º 16
0
  // fixme todo change all to XML serialization, so class versions are NOT an issue !
  public void saveSerializedData() {

    // saveXML();
    try {
      lastRace.setName(getName());
      lastRace.saveSerializedData();
      String filename = getName() + ".ser";

      FileOutputStream fileOut = new FileOutputStream(filename);
      ObjectOutputStream out =
          new ObjectOutputStream(
              fileOut); /// MUST FIX 2016 Nationals ERROR CONCurrentMpdificationException
      out.writeObject(
          this); // See   Ref#20161008 This was Line 913 BELOW on 20161008   //// This was line 869
      // in bwlow Log -->> Got CONCurrentMpdificationException ///20160727 in test
      /*
                  PRIOR CRASH  Prior to 20161008  See bottom of source file for new carsh dump
      at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:329)
      	at com.tcay.slalom.Race.saveSerializedData(Race.java:869)
      	at com.tcay.slalom.Race.updateResults(Race.java:1177)
      	at com.tcay.slalom.Race.updateResults(Race.java:1168)
      	at com.tcay.slalom.RaceRun.updateResults(RaceRun.java:535)
      	at com.tcay.slalom.RaceRun.setPhotoCellRaceRun(RaceRun.java:139)
      	at com.tcay.slalom.Race.associatePhotoCellRun(Race.java:1163)
      	at com.tcay.slalom.timingDevices.PhotoCellAgent.saveResult(PhotoCellAgent.java:57)
      	at com.tcay.slalom.timingDevices.tagHeuer.TagHeuerAgent.processDeviceOutput(TagHeuerAgent.java:174)
      	at com.tcay.RS232.PhotoEyeListener.readAndProcess(PhotoEyeListener.java:241)
      	at com.tcay.RS232.PhotoEyeListener.processPhotoEyeDataFromDevice(PhotoEyeListener.java:190)
      	at com.tcay.RS232.PhotoEyeListener.listenAndProcessPortOutput(PhotoEyeListener.java:304)
      	at com.tcay.RS232.PhotoEyeListener.run(PhotoEyeListener.java:76)
                  */

      out.close();
      fileOut.close();
      log.trace("Saved serialized data to " + filename);

    } catch (IOException i) {
      i.printStackTrace();
    }
  }
Ejemplo n.º 17
0
  /**
   * Checks if the score is high enough to get to the high scores list, adds the name and score and
   * organizes the list. If HighScores.dat is not found, the method generates a blank one.
   *
   * @param name The nickname of the person getting to the list.
   * @param score The score gained.
   */
  public static void addHighScore(String name, int score) {

    // If we don't yet have a high scores table, we create a blank (and let the user know about it)
    if (!new File("HighScores.dat").exists()) {
      // This object matrix actually stores the information of the high scores list
      Object[][] highScores = new Object[10][3];
      // We fill the high scores list with blank entries:  #.    " "    0
      for (int i = 0; i < highScores.length; i++) {
        highScores[i][0] = (i + 1) + ".";
        highScores[i][1] = " ";
        highScores[i][2] = 0;
      }
      // This actually writes and makes the high scores file
      try {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        o.writeObject(highScores);
        o.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // We read the file to check if we have a new high score, and then rewrite the highscore
    // This is done even if we didn't previously have a high scores list
    try {
      ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
      // The object matrix does the same as the previous one.
      // Here we just take what we read from the HighScores.dat to the Object[][] HighScores.
      Object[][] highScores = (Object[][]) o.readObject();
      // Then we start searching for an entry for which the score is smaller than the achieved score
      for (int i = 0; i < highScores.length; i++) {
        if ((Integer) highScores[i][2] < score) {
          // Once found we start to move entries, which are below the score we had, downwards.
          // I.e. 10. becomes whatever 9. was. 9. becomes what 8. was etc...
          for (int j = 9; j > i; j--) {
            highScores[j][0] = (j + 1) + ".";
            highScores[j][1] = highScores[j - 1][1];
            highScores[j][2] = highScores[j - 1][2];
          }
          // Then we write the score and the name we just got to the correct place
          highScores[i][0] = (i + 1) + ".";
          highScores[i][1] = name;
          highScores[i][2] = score;
          // And break the loop.
          /*Maybe this could be avoided somehow? I haven't been able to come up with an easy way yet.*/
          break;
        }
      }
      try {
        // And finally we overwrite the HighScores.dat with our highScores object matrix
        ObjectOutputStream n = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        n.writeObject(highScores);
        n.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
  }
  private void doSaveAll() {
    ObjectOutputStream objectStream = getObjectOutputStream();

    if (objectStream != null) {
      try {
        System.out.println("Saving All " + generations.getLeafCount() + " Generations...");

        for (Enumeration e = generations.depthFirstEnumeration(); e.hasMoreElements(); ) {
          DefaultMutableTreeNode tmpNode = (DefaultMutableTreeNode) e.nextElement();

          if (tmpNode.isLeaf()) objectStream.writeObject(tmpNode.getUserObject());
        }

        objectStream.close();
        System.out.println("Save completed successfully.");
      } catch (IOException e) {
        System.err.println(e);
      }
    } else {
      System.out.println("Save All Files has been aborted!");
    }
  }
  private void jMenuItemSaveProjectActionPerformed(
      java.awt.event.ActionEvent evt) // GEN-FIRST:event_jMenuItemSaveProjectActionPerformed
      { // GEN-HEADEREND:event_jMenuItemSaveProjectActionPerformed
    if (this.theProject != null) {
      JFileChooser jfc = new JFileChooser();
      int fileDialogReturnVal = jfc.showSaveDialog(this);

      if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
        try {
          File outputFile = jfc.getSelectedFile();
          FileOutputStream fos = new FileOutputStream(outputFile);
          ObjectOutputStream oos = new ObjectOutputStream(fos);

          oos.writeObject(this.theProject);
          if (this.currentResults != null) {
            oos.writeObject(this.currentResults);
          }
        } catch (IOException e) {
          log.log(Log.ERROR, "Failed to save file\n" + e.getMessage());
        }
      }
    }
  } // GEN-LAST:event_jMenuItemSaveProjectActionPerformed
Ejemplo n.º 20
0
 public void actionPerformed(ActionEvent ae) {
   // 如果用户点击了发送按钮
   if (ae.getSource() == send_button) {
     // 就将发送者、接受者的信息以及聊天消息封装成数据包一并发送给服务器
     MessageShare message_to_server = new MessageShare();
     message_to_server.set_message_type(MessageType.is_chat_content);
     message_to_server.set_sender(this.user);
     message_to_server.set_receiver(this.friend);
     message_to_server.set_content(input_text_field.getText());
     message_to_server.set_send_time(new java.util.Date().toString());
     // 将数据包发送给服务器
     try {
       ObjectOutputStream object_output_stream =
           new ObjectOutputStream(
               ManageClientToServerConnectionThread.get_lient_to_server_connectinon_thread(user)
                   .get_socket()
                   .getOutputStream());
       object_output_stream.writeObject(message_to_server);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 21
0
  /**
   * Methode de connection avec le serveur
   *
   * @return
   * @throws IOException
   */
  public boolean serverConnection() throws IOException {

    boolean ok = false;
    // créer la connexion au serveur, ainsi que les flux uniquement si elle n'est pas active
    if (comm == null) {
      try {
        // Récupération de l'adresse du serveur
        comm = new Socket(textServerIP.getText(), 12345);

        oos = new ObjectOutputStream(comm.getOutputStream());
        ois = new ObjectInputStream(comm.getInputStream());

        // envoyer le pseudo du joueur
        oos.writeObject(textPseudo.getText());
        oos.flush();
        // lire un booléen -> ok
        ok = true;
      } catch (IOException e) {
        System.out.println("problème de connexion au serveur : (JungleIG)" + e.getMessage());
        System.exit(1);
      }
    }
    return ok;
  }
  /**
   * run will be exicuted when the thread is called, and will connect to the server and start
   * communicating with it.
   */
  public void run() {
    WaitForConnection wfc = new WaitForConnection("Waiting For Connection");
    m_OldWindow.setEnabled(false);
    try {
      m_Socket = new Socket(m_IP, m_Port);

      // System.out.println("Connecting to ChatService...");
      m_ChatSocket = new Socket(m_IP, m_Port);
      // System.out.println("\nConnected to ChatService...");

      wfc.updateMessage("Waiting For Other Players");

      // System.out.println("Getting OutputStream Stream From server...");
      toServer = new ObjectOutputStream(m_Socket.getOutputStream());
      toChatServer = new ObjectOutputStream(m_ChatSocket.getOutputStream());
      toChatServer.flush();

      // System.out.println("Getting Input Stream From server...");
      fromServer = new ObjectInputStream(m_Socket.getInputStream());
      fromChatServer = new ObjectInputStream(m_ChatSocket.getInputStream());

      m_ChatService = new ChatService();
      m_ChatServiceThread = new Thread(m_ChatService);
      m_ChatServiceThread.start();

      m_MultiPlayerMenu.startGame();
      wfc.dispose();
      m_OldWindow.dispose();
    } catch (java.net.ConnectException e) {
      wfc.dispose();
      MenuWindow menu = new MenuWindow(new JFrame(""));
      JOptionPane.showMessageDialog(menu.getMainFrame(), "Error Connection refused");
      m_OldWindow.setEnabled(true);
    } catch (IOException ex) {
      System.err.print(ex);
    }
  }
Ejemplo n.º 23
0
  public void mouseClicked(MouseEvent e) {
    /*can = false;
    boolean f = true;
    for (int i = 0; i < 8; i++)
    {
    	for (int j = 0; j < 8; j++)
    	if (cell[i][j] == e.getSource())
    	{
    		int judege = Clicked(cell[i][j]);
    		f = false;
    		break;
    	}
    	if (!f) break;
    }*/

    boolean flage = CheckAll();
    if (flage) {
      can = false;
      if (kind.equals("" + turn)) {
        ChessBoard cel = (ChessBoard) (e.getSource());
        int judge = Clicked(cel);
        if (judge == 1) {
          try {
            System.out.println("发送前:" + cell[3][5].taken);
            out66.writeObject("落子" + turn);
            out66.flush();
            out66.writeObject(stateList.get(stateList.size() - 1));
            out66.flush();
            out66.writeObject(takenList.get(takenList.size() - 1));
            out66.flush();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      } else {
        JOptionPane.showMessageDialog(null, "请确定您的身份,您此时不能落子");
      }
    } else CheckAtTheEnd();
  }
Ejemplo n.º 24
0
  // create a new profile: read the script and possibly execute the queries,
  // save the stats (if 'import' == true, we assume the profile already exists
  // and don't run the queries)
  public void createWkld(String name, String scriptFile, boolean runQueries) {
    System.gc();
    Workload wkld = new Workload(name);

    if (showCmdsItem.getState()) {
      consoleFrame.echoCmd((!runQueries ? "importprof " : "newwkld ") + name + " " + scriptFile);
    }

    // construct the Workload object from the script;
    // first, check if the file exists
    try {
      FileReader reader = new FileReader(scriptFile);
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("couldn't open " + scriptFile);
      return;
    } catch (IOException e) {
      System.out.println("couldn't close " + scriptFile);
    }

    // now, check if it contains only queries
    int scriptId = 0;
    try {
      scriptId = Libgist.openScript(scriptFile);
    } catch (LibgistException e) {
      System.out.println("couldn't open (C) " + scriptFile);
      return;
    }
    char[] arg1 = new char[64 * 1024];
    StringBuffer arg1Buf = new StringBuffer();
    char[] arg2 = new char[64 * 1024];
    StringBuffer arg2Buf = new StringBuffer();
    // for (;;) {
    // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
    // if (cmd == Libgist.EOF) break;
    // if (cmd != Libgist.FETCH) {
    // there should only be queries
    // System.out.println("Script file contains non-SELECT command");
    // return;
    // }
    // }

    if (runQueries) {
      // turn profiling on and execute queries
      // Libgist.setProfilingEnabled(true);
      Libgist.disableBps(true); // we don't want to stop at breakpoints

      // rescan queries
      try {
        scriptId = Libgist.openScript(scriptFile);
      } catch (LibgistException e) {
        System.out.println("couldn't open (C) " + scriptFile);
        return;
      }
      int cnt = 1;
      // for (;;) {
      // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
      // if (cmd == Libgist.EOF) break;
      // arg1Buf.setLength(0);
      // arg1Buf.append(arg1, 0, strlen(arg1));
      // arg2Buf.setLength(0);
      // arg2Buf.append(arg2, 0, strlen(arg2));
      // OpThread.execCmd(LibgistCommand.FETCH, arg1Buf.toString(),
      // arg2Buf.toString(), false);
      // System.out.print(cnt + " ");
      // System.out.println(cnt + ": execute " + arg2Buf.toString() + " "
      // + arg1Buf.toString());
      // cnt++;
      // }
      System.out.println();

      Libgist.disableBps(false);
      // compute optimal clustering and some more statistics
      // Libgist.computeMetrics(wkld.filename);
    }

    // save profile
    try {
      // we're saving Java and C++ data in separate files (filename and filename.prof)
      // the profile object only contains the filename, the queries will be
      // read in from the file when the profile is opened (faster that way)
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(wkld.filename));
      out.writeObject(wkld);
      out.close();
      System.out.println("copy query file");
      Runtime.getRuntime().exec("cp " + scriptFile + " " + wkld.filename + ".queries");
      System.out.println("saving tree and profile");
      Libgist.saveToFile(wkld.filename + ".idx");
      if (runQueries) {
        // Libgist.saveProfile(wkld.filename + ".prof");
      }
    } catch (Exception e) {
      System.out.println("Error saving profile: " + e);
      return;
    }

    if (runQueries) {
      // turn profiling off (after the metrics were computed and
      // the profile saved)
      // Libgist.setProfilingEnabled(false);
    }
  }
Ejemplo n.º 25
0
  public void actionPerformed(ActionEvent e) {
    System.out.println("actionPerformed");
    if (e.getSource() == pen) // 画笔
    {
      System.out.println("pen");
      toolFlag = 0;
    }

    if (e.getSource() == eraser) // 橡皮
    {
      System.out.println("eraser");
      toolFlag = 1;
    }

    if (e.getSource() == clear) // 清除
    {
      System.out.println("clear");
      toolFlag = 2;
      paintInfo.removeAllElements();
      repaint();
    }

    if (e.getSource() == drLine) // 画线
    {
      System.out.println("drLine");
      toolFlag = 3;
    }

    if (e.getSource() == drCircle) // 画圆
    {
      System.out.println("drCircle");
      toolFlag = 4;
    }

    if (e.getSource() == drRect) // 画矩形
    {
      System.out.println("drRect");
      toolFlag = 5;
    }

    if (e.getSource() == colchooser) // 调色板
    {
      System.out.println("colchooser");
      Color newColor = JColorChooser.showDialog(this, "我的调色板", c);
      c = newColor;
    }

    if (e.getSource() == openPic) // 打开图画
    {

      openPicture.setVisible(true);

      if (openPicture.getFile() != null) {
        int tempflag;
        tempflag = toolFlag;
        toolFlag = 2;
        repaint();

        try {
          paintInfo.removeAllElements();
          File filein = new File(openPicture.getDirectory(), openPicture.getFile());
          picIn = new FileInputStream(filein);
          VIn = new ObjectInputStream(picIn);
          paintInfo = (Vector) VIn.readObject();
          VIn.close();
          repaint();
          toolFlag = tempflag;

        } catch (ClassNotFoundException IOe2) {
          repaint();
          toolFlag = tempflag;
          System.out.println("can not read object");
        } catch (IOException IOe) {
          repaint();
          toolFlag = tempflag;
          System.out.println("can not read file");
        }
      }
    }

    if (e.getSource() == savePic) // 保存图画
    {
      savePicture.setVisible(true);
      try {
        File fileout = new File(savePicture.getDirectory(), savePicture.getFile());
        picOut = new FileOutputStream(fileout);
        VOut = new ObjectOutputStream(picOut);
        VOut.writeObject(paintInfo);
        VOut.close();
      } catch (IOException IOe) {
        System.out.println("can not write object");
      }
    }
  }
Ejemplo n.º 26
0
  /** Performs the action of saving a session to a file. */
  public void actionPerformed(ActionEvent e) {

    // Get the frontmost SessionWrapper.
    SessionEditorIndirectRef sessionEditorRef =
        DesktopController.getInstance().getFrontmostSessionEditor();
    SessionEditor sessionEditor = (SessionEditor) sessionEditorRef;
    SessionEditorWorkbench workbench = sessionEditor.getSessionWorkbench();
    SessionWrapper sessionWrapper = workbench.getSessionWrapper();
    TetradMetadata metadata = new TetradMetadata();

    // Select the file to save this to.
    File file =
        EditorUtils.getSaveFile(
            sessionEditor.getName(),
            "tet",
            JOptionUtils.centeringComp(),
            true,
            "Save Session As...");

    if (file == null) {
      this.saved = false;
      return;
    }

    if ((DesktopController.getInstance().existsSessionByName(file.getName())
        && !(sessionWrapper.getName().equals(file.getName())))) {
      this.saved = false;
      JOptionPane.showMessageDialog(
          JOptionUtils.centeringComp(),
          "Another session by that name is currently open. Please "
              + "\nclose that session first.");
      return;
    }

    sessionWrapper.setName(file.getName());
    sessionEditor.setName(file.getName());

    // Save it.
    try {
      FileOutputStream out = new FileOutputStream(file);
      ObjectOutputStream objOut = new ObjectOutputStream(out);
      objOut.writeObject(metadata);
      objOut.writeObject(sessionWrapper);
      out.close();

      FileInputStream in = new FileInputStream(file);
      ObjectInputStream objIn = new ObjectInputStream(in);
      objIn.readObject();

      sessionWrapper.setSessionChanged(false);
      sessionWrapper.setNewSession(false);
      this.saved = true;
    } catch (Exception e2) {
      this.saved = false;
      e2.printStackTrace();
      JOptionPane.showMessageDialog(
          JOptionUtils.centeringComp(), "An error occurred while attempting to save the session.");
    }

    DesktopController.getInstance().putMetadata(sessionWrapper, metadata);
    sessionEditor.firePropertyChange("name", null, file.getName());
  }
Ejemplo n.º 27
0
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == butConnect) {
      try {
        boolean ok = serverConnection();
        if (ok) {
          setInitPanel();
        } else {
          System.out.println("Le pseudo existe déjà, choisissez en un autre.");
        }
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butListParty) {
      try {
        // envoyer requête LIST PARTY
        oos.writeInt(JungleServer.REQ_LISTPARTY);
        oos.flush();

        // recevoir résultat et l'afficher dans textInfoInit
        System.out.println("flush");
        boolean pret = ois.readBoolean();
        System.out.println(pret);
        if (pret) {
          String nomParty = (String) ois.readObject();
          System.out.println("apres read");
          textInfoInit.append(nomParty + " ");
        }

      } catch (ClassNotFoundException err) {
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }

    } else if (e.getSource() == butCreateParty) {
      try {
        boolean ok;
        // envoyer requête CREATE PARTY (paramètres : nom partie et nb joueurs nécessaires)
        oos.writeInt(JungleServer.REQ_CREATEPARTY);
        oos.writeObject(textCreate.getText());
        int nbJoueurs = (Integer) spinNbPlayer.getValue();
        oos.writeInt(nbJoueurs);
        oos.flush();
        // recevoir résultat -> ok
        ok = ois.readBoolean();
        System.out.println(ok);
        // si ok == true :
        if (ok) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre le début de la partie");
          // créer un ThreadClient et lancer son exécution
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
        }
      } catch (IOException err) {
        System.err.println(
            "probleme de connection serveur : " + err.getMessage() + "\n.Aborting...");
        System.exit(1);
      }
    } else if (e.getSource() == butJoinParty) {

      try {
        int idPlayer;
        // envoyer requête JOIN PARTY (paramètres : numero partie)
        oos.writeInt(JungleServer.REQ_JOINPARTY);
        oos.flush();
        System.out.println("requete envoyée");
        int numPartie = Integer.parseInt(textJoin.getText());
        oos.writeInt(numPartie);
        oos.flush();
        System.out.println("numPartie flushé");
        // recevoir résultat -> idPlayer
        idPlayer = ois.readInt();
        System.out.println("idplayer reçu : " + idPlayer);
        // si idPlayer >= 1 :
        if (idPlayer >= 1) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre la début de la partie");
          // créer un ThreadClient et lancer son exécution
          System.out.println("avant démarrage du thread");
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
          System.out.println("Apres le thread");
        }
      } catch (IOException err) {
        System.err.println("Problème de connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butPlay) {
      try {
        // envoyer requête PLAY (paramètre : contenu de textPlay)
        oos.writeInt(JungleServer.REQ_PLAY);
        oos.writeObject(textPlay.getText());
        oos.flush();
        orderSent = true;
        butPlay.setEnabled(false);
        textPlay.setEnabled(false);

        // mettre orderSent à true
        // bloquer le bouton play et le textfiled associé
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butQuit) {
      try {
        oos.close();
        ois.close();
        setConnectionPanel();
        comm = null;
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    }
  }
Ejemplo n.º 28
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("下棋")) {
     audience.setEnabled(false);
     fighter.setEnabled(false);
     begin.setEnabled(true);
     //			JOptionPane.showMessageDialog(null, "下棋");
     System.out.println("下棋");
     try {
       System.out.println("客户端发送下棋指令");
       out66.writeObject("对手");
       out66.flush();
       out66.writeObject(new char[0][0]);
       out66.flush();
       out66.writeObject(new boolean[0][0]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   if (e.getActionCommand().equals("观看")) {
     submit.setEnabled(false);
     regret.setEnabled(false);
     audience.setEnabled(false);
     fighter.setEnabled(false);
     //			JOptionPane.showMessageDialog(null, "观看");
     System.out.println("观看");
     try {
       out66.writeObject("观众");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   /*if (e.getActionCommand().equals("人机对弈"))
   {
   	audience.setEnabled(false);
   	fighter.setEnabled(false);
   	AIPlayer.setEnabled(false);
   	begin.setEnabled(true);
   	JOptionPane.showMessageDialog(null, "人机对弈");
   }*/
   if (e.getActionCommand().equals("发送")) {
     //			JOptionPane.showMessageDialog(null, "发送");
     System.out.println("发送");
     String str = myRole + ": " + " " + jt1.getText() + "\n";
     try {
       out99.writeObject(" " + str);
       out99.flush();
       out99.writeObject(new char[8][8]);
       out99.flush();
       out99.writeObject(new boolean[8][8]);
       out99.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     jt2.append(str);
     jt1.setText("");
   }
   if (e.getActionCommand().equals("取消")) {
     //			JOptionPane.showMessageDialog(null, "取消");
     System.out.println("取消");
     jt1.setText("");
   }
   if (e.getActionCommand().equals("悔棋")) {
     //			JOptionPane.showMessageDialog(null, "悔棋");
     System.out.println("悔棋");
     try {
       out66.writeObject("请求悔棋");
       out66.flush();
       out66.writeObject(new char[8][8]);
       out66.flush();
       out66.writeObject(new boolean[8][8]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     // RegretChess();
     // ShowChessNumber();
   }
   if (e.getActionCommand().equals("退出")) {
     int quit =
         JOptionPane.showConfirmDialog(null, "您确定要强制退出吗?", "请确认您的选择", JOptionPane.YES_NO_OPTION);
     if (quit == JOptionPane.YES_OPTION) {
       JOptionPane.showMessageDialog(null, "已强制退出");
       System.exit(0);
     } else return;
   }
   if (e.getActionCommand().equals("开始")) {
     begin.setEnabled(false);
     System.out.println("客户端发送开始指令");
     //			JOptionPane.showMessageDialog(null, "开始");
     try {
       out66.writeObject("请求开始");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     Begin();
     if (kind == "黑") {
       for (int i = 0; i < 8; i++)
         for (int j = 0; j < 8; j++)
           if (cell[i][j].taken == false) {
             CheckPlace(cell[i][j]);
             if (canPut) {
               cell[i][j].ChangeBackground();
               canPut = false;
             }
           }
     }
   }
   if (e.getActionCommand().equals("存盘")) {
     //			JOptionPane.showMessageDialog(null, "存盘");
     System.out.println("存盘");
     try {
       System.out.println();
       out.writeObject(stateList);
       out.flush();
       out.close();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
 }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbSaveLayer) {
      try {
        FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf");
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(itemArray);
        oout.close();
        fout.close();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
    } else if (e.getSource() == jbLoadLayer) {
      try {
        FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf");
        ObjectInputStream oin = new ObjectInputStream(fin);
        itemArray = (Item[][]) oin.readObject();

        oin.close();
        fin.close();
        this.flush();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
      lvp.repaint();
    } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中

      for (int row = 0; row < 40; row++) {
        for (int col = 0; col < 60; col++) {
          Item item = ((Item) (jl.getSelectedValue())).clone();
          itemArray[row][col] = item;
          if (item != null) {
            item.setPosition(col, row);
          }
        }
      }

      lvp.repaint();
    } else if (e.getSource() == jbCreate) { // 生成源代码

      try {
        FileOutputStream fout = null;
        DataOutputStream dout = null;
        fout = new FileOutputStream("maps.so");
        dout = new DataOutputStream(fout);
        int totalBlocks = 0;

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              totalBlocks++;
            }
          }
        }
        System.out.println("totalBlocks=" + totalBlocks);

        // 写入不空块的数量
        dout.writeInt(totalBlocks);

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              int w = item.w; // 元素的图片宽度
              int h = item.h; // 元素的图片高度
              int col = item.col; // 元素的地图列
              int row = item.row; // 元素的地图行
              int pCol = item.pCol; // 元素的占位列
              int pRow = item.pRow; // 元素的占位行
              String leiMing = item.leiMing; // 类名

              int[][] notIn = item.notIn; // 不可通过
              int[][] keYu = item.keYu; // 可遇矩阵

              // 计算图片下标
              int outBitmapInxex = 0;
              if (leiMing.equals("Grass")) {
                outBitmapInxex = 0;
              } else if (leiMing.equals("XiaoHua1")) {
                outBitmapInxex = 1;
              } else if (leiMing.equals("MuZhuang")) {
                outBitmapInxex = 2;
              } else if (leiMing.equals("XiaoHua2")) {
                outBitmapInxex = 3;
              } else if (leiMing.equals("Road")) {
                outBitmapInxex = 4;
              } else if (leiMing.equals("Jing")) {
                outBitmapInxex = 5;
              }

              dout.writeByte(outBitmapInxex); // 记录图片下标
              dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇
              dout.writeByte(w); // 图片宽度
              dout.writeByte(h); // 图片高度
              dout.writeByte(col); // 总列数
              dout.writeByte(row); // 总行数
              dout.writeByte(pCol); // 占位列
              dout.writeByte(pRow); // 占位行

              int bktgCount = notIn.length; // 不可通过点的数量
              dout.writeByte(bktgCount); // 写入不可通过点的数量

              for (int k = 0; k < bktgCount; k++) {
                dout.writeByte(notIn[k][0]);
                dout.writeByte(notIn[k][1]);
              }
            }
          }
        }

        dout.close();
        fout.close();

      } catch (Exception ea) {
        ea.printStackTrace();
      }
    }
  }
Ejemplo n.º 30
0
        public void actionPerformed(ActionEvent e) {
          saveOld();
          area1.setText("");
          resetArea2();
          try {
            clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText()));
            Random r = new Random();
            serverport = 10000 + r.nextInt(8999); // random port :D

            serverSocket = new ServerSocket(serverport);
            active = true;
            editor.setTitleToListen();

            connected = true;

            ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
            output.writeObject(new JoinNetworkRequest(serverport));

            ConnectionData data = getConnectionData(clientSocket, input);

            lc = new LamportClock(data.getId());
            lc.setMaxTime(data.getTs());
            dec = new DocumentEventCapturer(lc, editor);
            er = new EventReplayer(editor, dec, lc);
            ert = new Thread(er);
            ert.start();

            Peer peer =
                new Peer(
                    editor,
                    er,
                    data.getHostId(),
                    clientSocket,
                    output,
                    input,
                    lc,
                    clientSocket.getInetAddress().getHostAddress(),
                    data.getPort());
            dec.addPeer(peer);
            Thread thread = new Thread(peer);
            thread.start();

            er.setAcknowledgements(data.getAcknowledgements());
            er.setEventHistory(data.getEventHistory());
            er.setCarets(data.getCarets());

            er.addCaretPos(lc.getID(), 0);

            for (PeerWrapper p : data.getPeers()) {
              Socket socket;
              try {
                socket = connectToPeer(p.getIP(), p.getPort());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                outputStream.writeObject(
                    new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0));
                Peer newPeer =
                    new Peer(
                        editor,
                        er,
                        p.getId(),
                        socket,
                        outputStream,
                        inputStream,
                        lc,
                        p.getIP(),
                        p.getPort());
                dec.addPeer(newPeer);
                Thread t = new Thread(newPeer);
                t.start();
              } catch (IOException ex) {
                continue;
              }
            }

            Thread t1 =
                new Thread(
                    new Runnable() {

                      @Override
                      public void run() {
                        waitForConnection();
                      }
                    });
            t1.start();
            area1.setText(data.getTextField());
            area1.setCaretPosition(0);
            setDocumentFilter(dec);

            dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp()));

            changed = false;
            Connect.setEnabled(false);
            Disconnect.setEnabled(true);
            Listen.setEnabled(false);
            Save.setEnabled(false);
            SaveAs.setEnabled(false);
          } catch (NumberFormatException | IOException e1) {
            setTitle("Unable to connect");
          }
        }