Пример #1
0
  public boolean loadDocument(String fileName) {
    try {
      File file = new File(fileName);
      ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
      SavedDocument doc = (SavedDocument) in.readObject();

      document =
          new EditorDocument(
              doc.getTitle(), doc.getDescription(),
              doc.getText(), doc.getStartTime());
      paragraphs = new Paragraphs(document, doc.getParagraphsVector());
      clients = doc.getClients();
      Iterator i = clients.iterator();
      while (i.hasNext()) {
        EditorClient c = (EditorClient) i.next();
        c.setPresent(false);

        if (c.getIdNumber() > nextClientId) nextClientId = c.getIdNumber();
      }
      nextClientId++;

      lockManager = new LockManager(clients, document, paragraphs);
      highlights =
          new Highlights(lockManager, document, doc.getHighlightTypes(), doc.getHighlights());

      return true;
    } catch (Exception e) {
      System.out.println("EditorServer: loadDocument. error");
      e.printStackTrace();
      return false;
    }
  } // endof const WITH audio profile maker
Пример #2
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;
 }
Пример #3
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();
    }
  }
 public void windowOpened(WindowEvent e) // read file on start
     {
   FileInputStream in = null;
   ObjectInputStream data = null;
   try {
     in = new FileInputStream(DB);
     data = new ObjectInputStream(in);
     p = (Person) data.readObject();
     while (p != null) {
       persons.add(p); // store Person object in ArrayList collection
       p = (Person) data.readObject(); // read the next record
     }
     data.close();
   } catch (Exception ex) {
     // IOException will always occur on the last read above
   } finally {
     if (persons.size() > 0) displayRecord();
   }
 }
  private void jMenuItemLoadProjectActionPerformed(
      java.awt.event.ActionEvent evt) // GEN-FIRST:event_jMenuItemLoadProjectActionPerformed
      { // GEN-HEADEREND:event_jMenuItemLoadProjectActionPerformed
    JFileChooser jfc = new JFileChooser();
    if (lastPath != null) {
      jfc.setCurrentDirectory(lastPath);
    }
    int fileDialogReturnVal = jfc.showOpenDialog(this);

    if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
      try {
        File inputFile = jfc.getSelectedFile();
        FileInputStream fis = new FileInputStream(inputFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.theProject = (Project) ois.readObject();
        this.currentResults = (LSAResults) ois.readObject();

        lastPath = new File(jfc.getSelectedFile().getPath());
      } catch (IOException e) {
        if (this.theProject == null) {
          log.log(Log.ERROR, "Failed to load project");
        }
        if (this.currentResults == null) {
          log.log(Log.WARNING, "Failed to load results");
        }

        log.log(Log.WARNING, e.getMessage());
      } catch (ClassNotFoundException e) {
        log.log(Log.ERROR, "Class not found error, version mismatch");
      }
    }
    if (this.theProject != null) {
      jMenuItemViewDocuments.setEnabled(true);
      jMenuItemSaveProject.setEnabled(true);
      this.setTitle(theProject.getProjectName());
      log.log(Log.INFO, "Project Loaded");
    }
    if (this.currentResults != null) {
      log.log(Log.INFO, "Results loaded");
    }
  } // GEN-LAST:event_jMenuItemLoadProjectActionPerformed
Пример #6
0
  private void deSerialize(ObjectInputStream in) throws DuplicateBibException {
    Object o;
    try {
      while ((o = in.readObject()) != null) {
        Race raceFromSerialized = (Race) o;

        this.date = raceFromSerialized.date;
        this.name = raceFromSerialized.name;
        this.location = raceFromSerialized.location;
        setNbrGates(raceFromSerialized.nbrGates); // this.nbrGates = race.nbrGates;// = 25;
        this.upstreamGates = raceFromSerialized.upstreamGates;
        this.judgingSections = raceFromSerialized.judgingSections;
        for (JudgingSection s : judgingSections) {
          // must assign all transients, otherwise they are null and cause problsm
          s.setClientDeviceAttached(new Boolean(false));
        }

        // Race Status
        this.pendingRerun = raceFromSerialized.pendingRerun;
        this.activeRuns = raceFromSerialized.activeRuns;
        this.completedRuns = raceFromSerialized.completedRuns;

        this.startList = raceFromSerialized.startList;
        this.runsStartedOrCompletedCnt = raceFromSerialized.runsStartedOrCompletedCnt;
        this.currentRunIteration =
            raceFromSerialized.currentRunIteration; // are we on 1st runs, or 2nd runs ?
        this.racers = raceFromSerialized.racers;
        this.tagHeuerEnabled =
            raceFromSerialized.tagHeuerEnabled; // todo REMOVE ->tagHeuerEmulation =
        // raceFromSerialized.tagHeuerEmulation;
        this.microgateEnabled = raceFromSerialized.microgateEnabled;
        this.microgateEnabled = raceFromSerialized.timyEnabled;

        this.icfPenalties = raceFromSerialized.icfPenalties;
      }

    } catch (InvalidClassException ice) {
      clearRace();
      System.out.println("All data cleared, incompatible race object version information");
    } catch (EOFException io) {
      // io.printStackTrace();

    } catch (IOException io) {
      io.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    }
    String duplicates = lookForDuplicateBibsInTheSameClass();
    if (duplicates != null) {
      log.error(duplicates);
      throw new DuplicateBibException();
    }
  }
Пример #7
0
 private ConnectionData getConnectionData(Socket clientSocket, ObjectInputStream input) {
   ConnectionData res;
   try {
     Object o = input.readObject();
     res = (ConnectionData) o;
     return res;
   } catch (IOException | ClassNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
Пример #8
0
 public void run() {
   String texto = "";
   while (repetir) {
     try {
       Empleados e = (Empleados) inObjeto.readObject();
       textarea1.setText("");
       textarea1.setForeground(Color.blue);
       if (e == null) {
         textarea1.setForeground(Color.red);
         PintaMensaje("<<EL EMPLEADO NO EXISTE>>");
       } else {
         texto =
             "Empleado: "
                 + e.getEmpNo()
                 + "\n   "
                 + "Oficio: "
                 + e.getOficio()
                 + "\tApellido: "
                 + e.getApellido()
                 + "\n    "
                 + "Comisión: "
                 + e.getComision()
                 + "\tDirección: "
                 + e.getDir()
                 + "\n    "
                 + "Alta: "
                 + e.getFechaAlt()
                 + "\tSalario: "
                 + e.getSalario()
                 + "\n    "
                 + "Departamento: "
                 + e.getDepartamentos().getDnombre();
         textarea1.append(texto);
       }
     } catch (SocketException s) {
       repetir = false;
     } catch (IOException e) {
       e.printStackTrace();
       repetir = false;
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
       repetir = false;
     }
   }
   try {
     socket.close();
     System.exit(0);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Пример #9
0
 // Fun chatting
 private void whileChatting() throws IOException {
   String message = " You are now connected! ";
   sendMessage(message);
   ableToType(true);
   do {
     // have conversation
     try {
       message = (String) input.readObject();
       showMessage("\n" + message);
     } catch (ClassNotFoundException classNotFoundException) {
       showMessage("\n idk wtf that user sent! \n");
     }
   } while (!message.equals("LEEPING: END"));
 }
Пример #10
0
 private void deSerializeXML(ObjectInputStream in) {
   Object o;
   try {
     while ((o = in.readObject()) != null) {
       System.out.println(o);
     }
   } catch (IOException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   } catch (ClassNotFoundException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   }
 }
 private Object loadObject(String fName) {
   Object obj = null;
   try {
     FileInputStream fis = new FileInputStream(fName);
     ObjectInputStream oin = new ObjectInputStream(fis);
     obj = oin.readObject();
   } catch (IOException ex) {
     JOptionPane.showMessageDialog(this, "Problemos skaitant Objektus");
     return null;
   } catch (ClassNotFoundException ex) {
     JOptionPane.showMessageDialog(this, "Nerasta objekto klasė");
     return null;
   }
   return obj;
 }
  public static void main(String[] args) {

    MyCustomizableGUI custGUI = new MyCustomizableGUI();
    UserPreferences savedPrefs;

    try (FileInputStream fileIn = new FileInputStream("preferences.ser");
        ObjectInputStream objectIn = new ObjectInputStream(fileIn); ) {

      savedPrefs = (UserPreferences) objectIn.readObject();

      if (savedPrefs.getColor().contains("Red")) {
        custGUI.textField.setForeground(Color.red);
        custGUI.color.setSelectedItem("Red");
      } else if (savedPrefs.getColor().contains("Green")) {
        custGUI.textField.setForeground(Color.green);
        custGUI.color.setSelectedItem("Green");
      } else if (savedPrefs.getColor().contains("Blue")) {
        custGUI.textField.setForeground(Color.blue);
        custGUI.color.setSelectedItem("Blue");
      } else if (savedPrefs.getColor().contains("Cyan")) {
        custGUI.textField.setForeground(Color.cyan);
        custGUI.color.setSelectedItem("Cyan");
      } else if (savedPrefs.getColor().contains("Magenta")) {
        custGUI.textField.setForeground(Color.magenta);
        custGUI.color.setSelectedItem("Magenta");
      } else if (savedPrefs.getColor().contains("Yellow")) {
        custGUI.textField.setForeground(Color.yellow);
        custGUI.color.setSelectedItem("Yellow");
      } else if (savedPrefs.getColor().contains("Black")) {
        custGUI.textField.setForeground(Color.black);
        custGUI.color.setSelectedItem("Black");
      }

      custGUI.setFont(savedPrefs.getFont(), savedPrefs.getFontSize());
      custGUI.font.setSelectedItem(savedPrefs.getFont());
      custGUI.fontSize.setSelectedItem("" + savedPrefs.getFontSize());

    } catch (FileNotFoundException noFile) {
      // load default font and color
      custGUI.setFont("Arial", 25);
      custGUI.textField.setForeground(Color.black);

    } catch (ClassNotFoundException noPrefs) {
      noPrefs.printStackTrace();
    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    }
  }
  private void jMenuItemLoadLSAResultsActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItemLoadLSAResultsActionPerformed
    JFileChooser jfc = new JFileChooser();
    int fileDialogReturnVal = jfc.showOpenDialog(this);

    if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
      try {
        File inputFile = jfc.getSelectedFile();
        FileInputStream fis = new FileInputStream(inputFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.currentResults = (LSAResults) ois.readObject();
      } catch (IOException e) {
        log.log(Log.ERROR, "Failed to load LSA results\n" + e.getMessage());
      } catch (ClassNotFoundException e) {
        log.log(Log.ERROR, "Class not found : Error loading LSA results due to version mismatch");
      }

      System.out.println(currentResults == null);
    }
  } // GEN-LAST:event_jMenuItemLoadLSAResultsActionPerformed
Пример #14
0
 /**
  * This methods loads the current state of MOCO from a serialized file
  *
  * @param loadFrom The name of the serialized file
  * @return The new state of MOCO
  */
 public Object openObject(String loadFrom) {
   File selected = new File(loadFrom);
   try {
     ObjectInputStream oi =
         new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected)));
     Object obj = oi.readObject();
     oi.close();
     if (!(obj instanceof MOCCOState)) {
       throw new Exception("Object not of type MOCCOState");
     }
     return obj;
   } catch (Exception ex) {
     if (this.mainFrame != null) {
       JOptionPane.showMessageDialog(
           this.mainFrame,
           "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(),
           "Open object file",
           JOptionPane.ERROR_MESSAGE);
     } else {
       System.out.println("Couldn't read object: " + selected.getName() + "\n" + ex.getMessage());
     }
   }
   return null;
 }
Пример #15
0
 private Quiz loadSerializedQuiz(File f) throws Exception {
   ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
   Quiz q = (Quiz) objectInputStream.readObject();
   objectInputStream.close();
   return q;
 }
Пример #16
0
  public fileBackupProgram(JFrame frame) {
    super(new BorderLayout());
    this.frame = frame;

    errorDialog = new CustomDialog(frame, "Please enter a new name for the error log", this);
    errorDialog.pack();

    moveDialog = new CustomDialog(frame, "Please enter a new name for the move log", this);
    moveDialog.pack();

    printer = new FilePrinter();
    timers = new ArrayList<>();
    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    Object obj;
    copy = true;
    listModel = new DefaultListModel();
    // destListModel = new DefaultListModel();
    directoryList = new directoryStorage();

    // Create a file chooser
    fc = new JFileChooser();

    // Create the menu bar.
    menuBar = new JMenuBar();

    // Build the first menu.
    menu = new JMenu("File");
    menu.getAccessibleContext()
        .setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    editError = new JMenuItem("Save Error Log As...");
    editError
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the error log file");
    editError.addActionListener(new ErrorListener());
    menu.add(editError);

    editMove = new JMenuItem("Save Move Log As...");
    editMove
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the move log file");
    editMove.addActionListener(new MoveListener());
    menu.add(editMove);

    exit = new JMenuItem("Exit");
    exit.getAccessibleContext().setAccessibleDescription("Exit the Program");
    exit.addActionListener(new CloseListener());
    menu.add(exit);
    frame.setJMenuBar(menuBar);
    // Uncomment one of the following lines to try a different
    // file selection mode.  The first allows just directories
    // to be selected (and, at least in the Java look and feel,
    // shown).  The second allows both files and directories
    // to be selected.  If you leave these lines commented out,
    // then the default mode (FILES_ONLY) will be used.
    //
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    openButton = new JButton(openString);
    openButton.setActionCommand(openString);
    openButton.addActionListener(new OpenListener());

    destButton = new JButton(destString);
    destButton.setActionCommand(destString);
    destButton.addActionListener(new DestListener());

    // Create the save button.  We use the image from the JLF
    // Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton(saveString);
    saveButton.setActionCommand(saveString);
    saveButton.addActionListener(new SaveListener());

    URL imageURL = getClass().getResource(greenButtonIcon);
    ImageIcon greenSquare = new ImageIcon(imageURL);
    startButton = new JButton("Start", greenSquare);
    startButton.setSize(60, 20);
    startButton.setHorizontalTextPosition(AbstractButton.LEADING);
    startButton.setActionCommand("Start");
    startButton.addActionListener(new StartListener());

    imageURL = getClass().getResource(redButtonIcon);
    ImageIcon redSquare = new ImageIcon(imageURL);
    stopButton = new JButton("Stop", redSquare);
    stopButton.setSize(60, 20);
    stopButton.setHorizontalTextPosition(AbstractButton.LEADING);
    stopButton.setActionCommand("Stop");
    stopButton.addActionListener(new StopListener());

    copyButton = new JRadioButton("Copy");
    copyButton.setActionCommand("Copy");
    copyButton.setSelected(true);
    copyButton.addActionListener(new RadioListener());

    moveButton = new JRadioButton("Move");
    moveButton.setActionCommand("Move");
    moveButton.addActionListener(new RadioListener());

    ButtonGroup group = new ButtonGroup();
    group.add(copyButton);
    group.add(moveButton);

    // For layout purposes, put the buttons in a separate panel

    JPanel optionPanel = new JPanel();

    GroupLayout layout = new GroupLayout(optionPanel);
    optionPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout.createSequentialGroup().addComponent(copyButton).addComponent(moveButton));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(copyButton)
                    .addComponent(moveButton)));

    JPanel buttonPanel = new JPanel(); // use FlowLayout

    layout = new GroupLayout(buttonPanel);
    buttonPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(openButton)
                    .addComponent(optionPanel))
            .addComponent(destButton)
            .addComponent(startButton)
            .addComponent(stopButton)
        // .addComponent(saveButton)
        );
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(openButton)
                    .addComponent(destButton)
                    .addComponent(startButton)
                    .addComponent(stopButton)
                // .addComponent(saveButton)
                )
            .addComponent(optionPanel));

    buttonPanel.add(optionPanel);
    /*
    buttonPanel.add(openButton);
    buttonPanel.add(destButton);
    buttonPanel.add(startButton);
    buttonPanel.add(stopButton);
    buttonPanel.add(saveButton);
    buttonPanel.add(listLabel);
    buttonPanel.add(copyButton);
    buttonPanel.add(moveButton);
    */
    destButton.setEnabled(false);
    startButton.setEnabled(false);
    stopButton.setEnabled(false);

    // Add the buttons and the log to this panel.

    // add(logScrollPane, BorderLayout.CENTER);

    JLabel listLabel = new JLabel("Monitored Directory:");
    listLabel.setLabelFor(list);

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(8);
    JScrollPane listScrollPane = new JScrollPane(list);
    JPanel listPane = new JPanel();
    listPane.setLayout(new BorderLayout());

    listPane.add(listLabel, BorderLayout.PAGE_START);
    listPane.add(listScrollPane, BorderLayout.CENTER);

    listSelectionModel = list.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    // monitored, destination, waitInt, check

    destination = new JLabel("Destination Directory: ");

    waitField = new JFormattedTextField();
    // waitField.setValue(240);
    waitField.setEditable(false);
    waitField.addPropertyChangeListener(new FormattedTextListener());

    waitInt = new JLabel("Wait Interval (in minutes)");
    // waitInt.setLabelFor(waitField);

    checkField = new JFormattedTextField();
    checkField.setSize(1, 10);
    // checkField.setValue(60);
    checkField.setEditable(false);
    checkField.addPropertyChangeListener(new FormattedTextListener());

    check = new JLabel("Check Interval (in minutes)");
    // check.setLabelFor(checkField);

    fireButton = new JButton(fireString);
    fireButton.setActionCommand(fireString);
    fireButton.addActionListener(new FireListener());

    JPanel fieldPane = new JPanel();
    // fieldPane.add(destField);
    layout = new GroupLayout(fieldPane);
    fieldPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitInt)
                    .addComponent(check))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitField, 60, 60, 60)
                    .addComponent(checkField, 60, 60, 60)));

    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(waitInt)
                    .addComponent(waitField))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(check)
                    .addComponent(checkField)));

    JPanel labelPane = new JPanel();

    labelPane.setLayout(new BorderLayout());

    labelPane.add(destination, BorderLayout.PAGE_START);
    labelPane.add(fieldPane, BorderLayout.CENTER);

    layout = new GroupLayout(labelPane);
    labelPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(destination)
                    .addComponent(fieldPane)));

    layout.setVerticalGroup(
        layout.createSequentialGroup().addComponent(destination).addComponent(fieldPane));
    // labelPane.add(destination);
    // labelPane.add(fieldPane);

    try {
      // Read from disk using FileInputStream
      FileInputStream f_in = new FileInputStream(LOG_DIRECTORY + "\\save.data");

      // Read object using ObjectInputStream
      ObjectInputStream obj_in = new ObjectInputStream(f_in);

      // Read an object
      directoryList = (directoryStorage) obj_in.readObject();
      ERROR_LOG_NAME = (String) obj_in.readObject();
      MOVE_LOG_NAME = (String) obj_in.readObject();

      if (ERROR_LOG_NAME instanceof String) {
        printer.changeErrorLogName(ERROR_LOG_NAME);
      }

      if (MOVE_LOG_NAME instanceof String) {
        printer.changeMoveLogName(MOVE_LOG_NAME);
      }

      if (directoryList instanceof directoryStorage) {
        System.out.println("found object");
        // directoryList = (directoryStorage) obj;

        Iterator<Directory> directories = directoryList.getDirectories();
        Directory d;
        while (directories.hasNext()) {
          d = directories.next();

          try {
            listModel.addElement(d.getDirectory().toRealPath());
          } catch (IOException x) {
            printer.printError(x.toString());
          }

          int index = list.getSelectedIndex();
          if (index == -1) {
            list.setSelectedIndex(0);
          }

          index = list.getSelectedIndex();
          Directory dir = directoryList.getDirectory(index);

          destButton.setEnabled(true);
          checkField.setValue(dir.getInterval());
          waitField.setValue(dir.getWaitInterval());
          checkField.setEditable(true);
          waitField.setEditable(true);

          // directoryList.addNewDirectory(d);
          // try {
          // listModel.addElement(d.getDirectory().toString());
          // } catch (IOException x) {
          // printer.printError(x.toString());
          // }

          // timer = new Timer();
          // timer.schedule(new CopyTask(d.directory, d.destination, d.getWaitInterval(), printer,
          // d.copy), 0, d.getInterval());
        }

      } else {
        System.out.println("did not find object");
      }
      obj_in.close();
    } catch (ClassNotFoundException x) {
      printer.printError(x.getLocalizedMessage());
      System.err.format("Unable to read");
    } catch (IOException y) {
      printer.printError(y.getLocalizedMessage());
    }

    // Layout the text fields in a panel.

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));

    buttonPane.add(fireButton);
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(buttonPanel, BorderLayout.PAGE_START);
    add(listPane, BorderLayout.LINE_START);
    // add(destListScrollPane, BorderLayout.CENTER);

    add(fieldPane, BorderLayout.LINE_END);
    add(labelPane, BorderLayout.CENTER);
    add(buttonPane, BorderLayout.PAGE_END);
  }
Пример #17
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);
      }
    }
  }
Пример #18
0
  /**
   * waitForConnection waits for incomming connections. There are two cases. If we receive a
   * JoinNetworkRequest it means that a new peer tries to get into the network. We lock the entire
   * system, and sends a ConnectionData object to the new peer, from which he can connect to every
   * other peer. We add this new peer to our data.
   *
   * <p>If we receive a NewPeerDataRequest, it means that a new peer has received ConnectionData
   * from another peer in the network, and he is now trying to connect to everyone, including me. We
   * then update our data with the new peer.
   */
  private void waitForConnection() {
    while (active) {
      Socket client = waitForConnectionFromClient();
      if (client != null) {
        try {
          ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
          ObjectInputStream input = new ObjectInputStream(client.getInputStream());
          Object o = input.readObject();

          if (o instanceof JoinNetworkRequest) {
            JoinNetworkRequest request = (JoinNetworkRequest) o;
            dec.sendObjectToAllPeers(new LockRequest(lc.getTimeStamp()));
            waitForAllToLock();
            setLocked(true);
            Thread.sleep(500);
            int id = getNewId();
            Peer p =
                new Peer(
                    editor,
                    er,
                    id,
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            ConnectionData cd =
                new ConnectionData(
                    er.getEventHistory(),
                    er.getAcknowledgements(),
                    er.getCarets(),
                    id,
                    area1.getText(),
                    lc.getTimeStamp(),
                    lc.getID(),
                    dec.getPeers(),
                    serverSocket.getLocalPort());
            p.writeObjectToStream(cd);
            dec.addPeer(p);
            Thread t = new Thread(p);
            t.start();
            er.addCaretPos(id, 0);
          } else if (o instanceof NewPeerDataRequest) {
            NewPeerDataRequest request = (NewPeerDataRequest) o;
            Peer newPeer =
                new Peer(
                    editor,
                    er,
                    request.getId(),
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            dec.addPeer(newPeer);
            er.addCaretPos(request.getId(), request.getCaretPos());
            newPeer.writeObjectToStream(new NewPeerDataAcknowledgement(lc.getTimeStamp()));
            Thread t = new Thread(newPeer);
            t.start();
          }
        } catch (IOException | ClassNotFoundException | InterruptedException e) {
          e.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();
      }
    }
  }
Пример #20
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());
  }
Пример #21
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");
      }
    }
  }
Пример #22
0
  /**
   * Creates a new configuration method
   *
   * @param backMenu Menu instance used to control its music
   */
  public Config(Menu backMenu) {

    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      try (ObjectInputStream entradaObjs =
          new ObjectInputStream(new FileInputStream("Saves" + File.separator + "config.dat"))) {
        configSave = (float[]) entradaObjs.readObject();
      }
    } catch (ClassNotFoundException
        | IOException
        | InstantiationException
        | IllegalAccessException
        | UnsupportedLookAndFeelException e) {
      System.out.println(e.getMessage());
    }

    this.setSize(800, 300);
    this.add(fondo = new Fondo("fondoConfig.png"));
    this.setUndecorated(true);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setIconImage(Toolkit.getDefaultToolkit().getImage("Images" + File.separator + "logo.png"));
    this.backMenu = backMenu;

    icon = new ImageIcon("Images/brick.png");

    fondo.setLayout(new BorderLayout());

    returns = CustomButton.createButton("Go Back", this.getGraphicsConfiguration(), 18);
    returns.addActionListener(this);

    musicSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[0]);
    musicSlider.setOpaque(false);
    musicSlider.setMajorTickSpacing(10);
    musicSlider.setMinorTickSpacing(2);
    musicSlider.setPaintTicks(true);

    volumeSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[1]);
    volumeSlider.setOpaque(false);
    volumeSlider.setMajorTickSpacing(10);
    volumeSlider.setMinorTickSpacing(2);
    volumeSlider.setPaintTicks(true);

    fondo.add(returns, BorderLayout.SOUTH);
    fondo.add(musicSlider, BorderLayout.NORTH);
    fondo.add(volumeSlider, BorderLayout.CENTER);

    try {
      this.getContentPane()
          .setCursor(
              Toolkit.getDefaultToolkit()
                  .createCustomCursor(
                      CompatibleImage.toCompatibleImage(
                          ImageIO.read(new File("Images" + File.separator + "cursor.png"))),
                      new Point(0, 0),
                      "cursor"));
    } catch (IOException ex) {
      Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.setVisible(true);
  }
Пример #23
0
 public void run() {
   while (connected) {
     try {
       Object obj = in.readObject();
       if (obj.toString().equals("-101")) {
         connected = false;
         in.close();
         out.close();
         socket.close();
         SwingUtilities.invokeLater(
             new Runnable() {
               public void run() {
                 Cashier.closee = true;
                 JOptionPane.showMessageDialog(
                     null,
                     "Disconnected from server. Please Restart",
                     "Error:",
                     JOptionPane.PLAIN_MESSAGE);
                 try {
                   m.stop();
                 } catch (Exception w) {
                 }
               }
             });
       } else if (obj.toString().split("::")[0].equals("broadcast")) {
         // System.out.println("braodcast received");
         bc.run(obj.toString().substring(obj.toString().indexOf("::") + 2));
       } else if (obj.toString().split("::")[0].equals("chat")) {
         // System.out.println("chat received:
         // "+obj.toString().substring(obj.toString().indexOf("::")+2));
         cc.run(obj.toString().substring(obj.toString().indexOf("::") + 2));
       } else if (obj.toString().split("::")[0].equals("rankings")) {
         String hhh = obj.toString().split("::")[1];
         final JDialog jd = new JDialog();
         jd.setUndecorated(false);
         JPanel pan = new JPanel(new BorderLayout());
         JLabel ppp = new JLabel();
         ppp.setFont(new Font("Arial", Font.BOLD, 20));
         ppp.setText(
             "<html><pre>Thanks for playing !!!<br/>1st: "
                 + hhh.split(":")[0]
                 + "<br/>2nd: "
                 + hhh.split(":")[1]
                 + "<br/>3rd: "
                 + hhh.split(":")[2]
                 + "</pre></html>");
         pan.add(ppp, BorderLayout.CENTER);
         JButton ok = new JButton("Ok");
         ok.addActionListener(
             new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                 jd.setVisible(false);
                 try {
                   m.stop();
                 } catch (Exception w) {
                 }
               }
             });
         pan.add(ok, BorderLayout.SOUTH);
         jd.setContentPane(pan);
         jd.setModalityType(JDialog.ModalityType.APPLICATION_MODAL);
         jd.pack();
         jd.setLocationRelativeTo(null);
         jd.setVisible(true);
       } else if (obj.toString().split("::")[0].equals("rank")) {
         rc.run(obj.toString().substring(obj.toString().indexOf("::") + 2));
       } else {
         User hhh = null;
         try {
           hhh = (User) obj;
           /*if(usrD==1)
           {
               reply=obj;
               ccl.interrupt();
           }
           else*/
           {
             try {
               m.ur.changeData((User) obj);
             } catch (Exception w) {
               try {
                 maain.ur.changeData((User) obj);
               } catch (Exception ppp) {
                 ppp.printStackTrace();
               }
             }
           }
         } catch (Exception p) {
           int iid = -1;
           try {
             iid = Integer.parseInt(obj.toString());
             obj = in.readObject();
             if (obj.toString().equals("-102")) {
               // ccl.interrupt();
               SwingUtilities.invokeLater(
                   new Runnable() {
                     public void run() {
                       Cashier.closee = true;
                       JOptionPane.showMessageDialog(
                           null, "Server Not Running.", "Error:", JOptionPane.PLAIN_MESSAGE);
                     }
                   });
             }
             // Thread th = ((Thread)rev.remove(iid));
             rev2.put(iid, obj);
             // System.out.println("Put: "+iid+"   :   "+obj.toString()+"   :
             // "+Thread.currentThread());
             // th.interrupt();
             // ccl.interrupt();
           } catch (Exception ppp) {
               /*ppp.printStackTrace();*/
             System.out.println(
                 "Shit: "
                     + iid
                     + "   :   "
                     + obj.toString()
                     + "   :   "
                     + Thread.currentThread());
           }
         }
       }
       try {
         Thread.sleep(500);
       } catch (Exception n) {
       }
     } catch (Exception m) {
     }
   }
 }
    /** Background thread used to receive data from the server. */
    public void run() {
      Long id;
      Integer message_type;
      String target;
      String soap;
      SOAPMonitorData data;
      int selected;
      int row;
      boolean update_needed;
      while (socket != null) {
        try {
          // Get the data from the server
          message_type = (Integer) in.readObject();
          // Process the data depending on its type
          switch (message_type.intValue()) {
            case SOAPMonitorConstants.SOAP_MONITOR_REQUEST:
              // Get the id, target and soap info
              id = (Long) in.readObject();
              target = (String) in.readObject();
              soap = (String) in.readObject();
              // Add new request data to the table
              data = new SOAPMonitorData(id, target, soap);
              model.addData(data);
              // If "most recent" selected then update
              // the details area if needed
              selected = table.getSelectedRow();
              if ((selected == 0) && model.filterMatch(data)) {
                valueChanged(null);
              }
              break;
            case SOAPMonitorConstants.SOAP_MONITOR_RESPONSE:
              // Get the id and soap info
              id = (Long) in.readObject();
              soap = (String) in.readObject();
              data = model.findData(id);
              if (data != null) {
                update_needed = false;
                // Get the selected row
                selected = table.getSelectedRow();
                // If "most recent", then always
                // update details area
                if (selected == 0) {
                  update_needed = true;
                }
                // If the data being updated is
                // selected then update details
                row = model.findRow(data);
                if ((row != -1) && (row == selected)) {
                  update_needed = true;
                }
                // Set the response and update table
                data.setSOAPResponse(soap);
                model.updateData(data);
                // Refresh details area (if needed)
                if (update_needed) {
                  valueChanged(null);
                }
              }
              break;
          }

        } catch (Exception e) {
          // Exceptions are expected here when the
          // server communication has been terminated.
          if (stop_button.isEnabled()) {
            stop();
            setErrorStatus(STATUS_CLOSED);
          }
        }
      }
    }