예제 #1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
  public void actionPerformed(ActionEvent e) {

    // Handle open button action.
    if (e.getSource() == openButton) {
      int returnVal = fc.showOpenDialog(FileChooserDemo.this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        // This is where a real application would open the file.
        log.append("Opening: " + file.getName() + "." + newline);
      } else {
        log.append("Open command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());

      // Handle save button action.
    } else if (e.getSource() == saveButton) {
      int returnVal = fc.showSaveDialog(FileChooserDemo.this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        // This is where a real application would save the file.
        log.append("Saving: " + file.getName() + "." + newline);
      } else {
        log.append("Save command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());
    }
  }
예제 #3
0
 // サーバーから送られてきたメッセージの処理
 public void reachedMessage(String name, String value) {
   // チャットルームのリストに変更が加えられた
   if (name.equals("rooms")) {
     if (value.equals("")) {
       roomList.setModel(new DefaultListModel());
     } else {
       String[] rooms = value.split(" ");
       roomList.setListData(rooms);
     }
   }
   // ユーザーが入退室した
   else if (name.equals("users")) {
     if (value.equals("")) {
       userList.setModel(new DefaultListModel());
     } else {
       String[] users = value.split(" ");
       userList.setListData(users);
     }
   }
   // メッセージが送られてきた
   else if (name.equals("msg")) {
     msgTextArea.append(value + "\n");
   }
   // 処理に成功した
   else if (name.equals("successful")) {
     if (value.equals("setName")) msgTextArea.append(">名前を変更しました\n");
   }
   // エラーが発生した
   else if (name.equals("error")) {
     msgTextArea.append("ERROR>" + value + "\n");
   }
 }
 @Override
 public synchronized void write(byte[] ba, int str, int len) {
   try {
     curLength += len;
     if (bytesEndWith(ba, str, len, LINE_SEP)) {
       lineLengths.addLast(new Integer(curLength));
       curLength = 0;
       if (lineLengths.size() > maxLines) {
         textArea.replaceRange(null, 0, lineLengths.removeFirst().intValue());
       }
     }
     for (int xa = 0; xa < 10; xa++) {
       try {
         textArea.append(new String(ba, str, len));
         break;
       } catch (
           Throwable
               thr) { // sometimes throws a java.lang.Error: Interrupted attempt to aquire write
                      // lock
         if (xa == 9) {
           thr.printStackTrace();
         }
       }
     }
     textArea.setCaretPosition(textArea.getText().length());
   } catch (Throwable thr) {
     CharArrayWriter caw = new CharArrayWriter();
     thr.printStackTrace(new PrintWriter(caw, true));
     textArea.append(System.getProperty("line.separator", "\n"));
     textArea.append(caw.toString());
   }
 }
예제 #5
0
 // サーバーに接続する
 public void connectServer() {
   try {
     socket = new Socket(HOST, PORT);
     msgTextArea.append(">サーバーに接続しました\n");
   } catch (Exception err) {
     msgTextArea.append("ERROR>" + err + "\n");
   }
 }
예제 #6
0
 private void about() {
   results.setText("-About-");
   results.append("\n\n\nVersion 1.1.");
   results.append("\n\nCreated by Sean Crowley");
   results.append("\n\[email protected]");
   results.append("\n\nReddit.com/u/Crowley2012");
   results.append("\n\n\nFeel free to contact me via email or reddit with bugs/new features.");
 }
 private void rodytiAutoRinkinius() {
   zonaNeregAuto.setText("");
   for (Automobilis a : rg.neregAuto) zonaNeregAuto.append(a.toString() + "\n");
   zonaRegAuto.setText("");
   for (Map.Entry<String, Automobilis> me : rg.regAuto.entrySet())
     zonaRegAuto.append(String.format("%8s=%s\n", me.getKey(), me.getValue()));
   tfNeregKiekis.setText(Integer.toString(rg.neregAuto.size()));
   tfRegKiekis.setText(Integer.toString(rg.regAuto.size()));
 }
예제 #8
0
  /** The listener method. */
  public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();

    if (source == b1) // click button
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }

    if (source == tf) // press return
    {
      try {
        String message = tf.getText();
        server.sendPrivateMessage(parent, selfIdentity, message);
        ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator);
        ta.setCaretPosition(ta.getText().length());
        tf.setText("");
      } catch (RemoteException ex) {
        System.out.print("Exception encountered while sending" + " private message.");
      }
    }
    if (source == jMenuItem3) {
      JFileChooser fileChooser = new JFileChooser();

      fileChooser.setDialogTitle("Choose or create a new file to store the conversation");
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setDoubleBuffered(true);

      fileChooser.showOpenDialog(this);

      File file = fileChooser.getSelectedFile();

      try {
        if (file != null) {

          Writer writer = new BufferedWriter(new FileWriter(file));

          writer.write(ta.getText());
          writer.flush();
          writer.close();
        }
      } catch (IOException ex) {
        System.out.println("Can't write to file. " + ex);
      }
    }
    if (source == jMenuItem4) {
      selfRemove();
      this.dispose();
    }
  }
예제 #9
0
 public void updateStatus() {
   txaStatus.setText("");
   txaStatus.append("size\t" + store.getRowCount() + "\n");
   txaStatus.append("total\t" + store.sumLengths() + "KB\n");
   txaStatus.append("\nThreads:\n");
   for (int i = 0; i < numThreads; i++) {
     txaStatus.append(" " + i + "- ");
     String jb = encryptDecryptThreads[i].getCur();
     if (jb == null) txaStatus.append("idle\n");
     else {
       txaStatus.append(jobString(jb) + "\n");
     }
   }
   txaStatus.append("\nJobs:\n");
   int c = 6 + numThreads;
   int i = 0;
   synchronized (jobs) {
     for (String s : jobs) {
       if (c + i < TXA_HEIGHT - 1) txaStatus.append(" - " + jobString(s) + "\n");
       else if (c + i == TXA_HEIGHT - 1) {
         txaStatus.append(" - [" + (jobs.size() - i) + "more ]");
       }
       i++;
     }
   }
 }
예제 #10
0
 protected void compileGoal(boolean andRun) {
   String sgoal = gl.getText();
   if (!(sgoal.length() == 0)) {
     try {
       ProParser p = new ProParser(sgoal, intmsg);
       goal = p.getClause();
       intmsg.append("compiled goal: " + goal + "\n");
       if (andRun) run();
     } catch (Exception e) {
       outp.append("errore" + e + " \n");
     }
   } else outp.append("inserire il goal" + " \n");
 }
예제 #11
0
  protected void doSysValidation() {
    int nComps = m_pnlDisplay.getComponentCount();
    JTextArea txaMsg = null;

    for (int i = 0; i < nComps; i++) {
      Component comp = m_pnlDisplay.getComponent(i);
      if (comp instanceof JTextArea) txaMsg = (JTextArea) comp;
    }

    if (txaMsg != null) {
      txaMsg.append("VALIDATING SYSTEM FILES...\n");
      txaMsg.append("\n");
    }
    runScripts(txaMsg);
  }
예제 #12
0
  public synchronized void run() {

    byte[] buffer = new byte[BUFFER_SIZE];

    for (; ; ) {
      try {
        this.wait(100);
      } catch (InterruptedException ie) {
      }

      int len = 0;
      try {
        int noBytes = pin.available();

        if (noBytes > 0) {
          len = pin.read(buffer, 0, Math.min(noBytes, BUFFER_SIZE));
          if (len > 0) {
            jTextArea.append(new String(buffer, 0, len));
            jTextArea.setCaretPosition(jTextArea.getText().length());
          }
        }
      } catch (IOException ioe) {
        throw new UIError("Unable to read from input stream! " + ioe.getMessage());
      }
    }
  }
예제 #13
0
  /**
   * Appends each string in the new_strings parameter as a new line in the text area. Sets the caret
   * is set to the beginning of the text.
   *
   * @param new_strings The strings to add. Each entry is added to a new line. This method performs
   *     no action if this parameter is empty or null.
   */
  public void appendStrings(String[] new_strings) {
    if (new_strings != null)
      if (new_strings.length != 0) {
        // Append the text
        for (int i = 0; i < new_strings.length; i++) {
          if (i == 0) {
            if (!text_area.getText().equals("")) text_area.append("\n");
          } else text_area.append("\n");

          text_area.append(new_strings[i]);
        }

        // Reset the caret position
        text_area.setCaretPosition(0);
      }
  }
예제 #14
0
  private void PrettyPrint(File file, TreeMap<String, Long> sortedMap) {

    //        Long size = 0L;
    //        ArrayList<Long> values = new ArrayList<Long>(sortedMap.values());

    Long total = 0L;
    for (Long value : sortedMap.values()) {
      total = total + value; // Can also be done by total += value;
    }

    log.append(file.getName() + ": " + readableFileSize(total) + "\n\n");
    for (Map.Entry<String, Long> entry : sortedMap.entrySet()) {
      log.append("[ " + readableFileSize(entry.getValue()) + " ]");
      log.append(" --> " + entry.getKey() + "\n");
    }
    //        log.append(sortedMap + "\n");
  }
예제 #15
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");
   }
 }
예제 #16
0
  public ConnectFourServer() {
    JTextArea jtaLog = new JTextArea();

    // Create a scroll pane to hold text area
    JScrollPane scrollPane = new JScrollPane(jtaLog);

    // Add the scroll pane to the frame
    add(scrollPane, BorderLayout.CENTER);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300, 300);
    setTitle("TicTacToeServer");
    setVisible(true);

    try {
      // Create a server socket
      ServerSocket serverSocket = new ServerSocket(8000);
      jtaLog.append(new Date() + ": Server started at socket 8000\n");

      // Number a session
      int sessionNo = 1;

      // Ready to create a session for every two players
      while (true) {
        jtaLog.append(new Date() + ": Wait for players to join session " + sessionNo + '\n');

        // Connect to player 1
        Socket player1 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 1 joined session " + sessionNo + '\n');
        jtaLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 1
        new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1);

        // Connect to player 2
        Socket player2 = serverSocket.accept();

        jtaLog.append(new Date() + ": Player 2 joined session " + sessionNo + '\n');
        jtaLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + '\n');

        // Notify that the player is Player 2
        new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2);

        // Display this session and increment session number
        jtaLog.append(new Date() + ": Start a thread for session " + sessionNo++ + '\n');

        // Create a new thread for this session of two players
        HandleASession task = new HandleASession(player1, player2);

        // Start the new thread
        new Thread(task).start();
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
예제 #17
0
  // メッセージをサーバーに送信する
  public void sendMessage(String msg) {
    try {
      OutputStream output = socket.getOutputStream();
      PrintWriter writer = new PrintWriter(output);

      writer.println(msg);
      writer.flush();
    } catch (Exception err) {
      msgTextArea.append("ERROR>" + err + "\n");
    }
  }
예제 #18
0
  // ====================================================================
  private void findShort() {
    // svårt att behålla linjefärgerna?
    int start, s**t;
    try { // read from station
      String str = from.getText();
      str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
      start = noderna.find(str).getNodeNo();
    } catch (NullPointerException npe) {
      route.setText(felTextStart + "\n");
      return;
    }
    try { // read to station
      String str = to.getText();
      str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
      s**t = noderna.find(str).getNodeNo();
    } catch (NullPointerException npe) {
      route.setText(felTextSlut + "\n");
      return;
    }

    double totWeight = 0;
    int totNodes = 0;
    route.setText("");
    karta.clearLayer(DrawGraph.Layer.OVERLAY);
    Iterator<BusEdge> it = grafen.shortestPath(start, s**t);
    while (it.hasNext()) {
      BusEdge e = it.next();
      route.append(makeText1(e) + "\n");
      totNodes++;
      totWeight += e.getWeight();
      // draw the shortest path
      BusStop from = noderna.find(e.from), to = noderna.find(e.to);
      karta.drawLine(
          from.xpos, from.ypos, to.xpos, to.ypos, Color.black, 4.0, DrawGraph.Layer.OVERLAY);
    }
    karta.repaint();
    route.append("Antal: " + totNodes + " totalvikt: " + totWeight + "\n");
    from.setText("");
    to.setText("");
  } // findShort
예제 #19
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();
   }
 }
예제 #20
0
  protected void compile() {
    Sexp curClause;
    goal = new NilSexp();
    prog = new NilSexp();
    prog2 = new NilSexp();
    String codice = code.getText();

    try {
      ProParser p = new ProParser(codice, intmsg);
      for (; ; ) {
        curClause = p.getClause(); // seleziono una singola clausola
        intmsg.append("compiled: " + curClause + "\n");
        if (!(curClause instanceof eofToken)) {
          prog = Sexp.append(prog, Sexp.list1(curClause));
        }
        if (p.atEOF()) {
          break;
        }
      }
      String codice2 = code.getText();
      ProParser p2 = new ProParser(codice2, intmsg);
      for (; ; ) {
        curClause = p2.getClause(); // seleziono una singola clausola
        // intmsg.append( "compiled: " + curClause + "\n" );
        if (!(curClause instanceof eofToken)) {
          prog2 = Sexp.append(prog2, Sexp.list1(curClause));
        }
        if (p2.atEOF()) {
          break;
        }
      }

      showProg(prog, outp);
      // showProg( prog2, outp );
    } catch (Exception e) {
      outp.append("error" + e + " \n");
    }
  }
예제 #21
0
  @Override
  public void init() {
    getContentPane().setLayout(new BorderLayout());

    try {
      setInputPanel();
    } catch (Exception e) {
      outp.append("errore input panel" + e);
    }
    ;
    setOutputPanel();
    getContentPane().add(input, BorderLayout.WEST);
    getContentPane().add(output, BorderLayout.EAST);
  }
예제 #22
0
 // ====================================================================
 private void findMinSpan() {
   route.setText("");
   Iterator<BusEdge> it = grafen.minimumSpanningTree();
   if (it != null && it.hasNext()) {
     double totWeight = 0;
     int totNodes = 0; // only for easier testing
     karta.clearLayer(DrawGraph.Layer.OVERLAY);
     while (it.hasNext()) {
       BusEdge be = it.next();
       totNodes++;
       totWeight += be.getWeight();
       route.append(makeText2(be) + "\n");
       // draw the MST
       BusStop from = noderna.find(be.from);
       BusStop to = noderna.find(be.to);
       karta.drawLine(
           from.xpos, from.ypos, to.xpos, to.ypos, Color.red, 2.5, DrawGraph.Layer.OVERLAY);
     }
     karta.repaint();
     route.append("Antal: " + totNodes + " totalvikt: " + totWeight + "\n");
   } else from.setText("Det fanns ej någon lösning");
   to.setText("");
   from.setText("");
 } //  findMinSpan
예제 #23
0
  /** 利用IO流接受外部的文本文件 */
  private void receiveTxt() {

    InputStream txtPath = DeteDialog.class.getResourceAsStream("help.txt");
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(txtPath));
      String line;
      while ((line = in.readLine()) != null) {
        textArea.append(line + "\n");
      }

      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #24
0
  /** Display the file in the text area */
  private void showFile() {
    Scanner input = null;
    try {
      // Use a Scanner to read text from the file
      input = new Scanner(new File(jtfFilename.getText().trim()));

      // Read a line and append the line to the text area
      while (input.hasNext()) jtaFile.append(input.nextLine() + '\n');
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + jtfFilename.getText());
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
예제 #25
0
파일: JChat.java 프로젝트: ThatoP/JChat
 @Override
 public void run() {
   // TODO Auto-generated method stub
   String inputLine;
   try {
     while ((inputLine = in.readLine()) != null) {
       inputLine = "\nYour peer says >> " + inputLine;
       chatField.append(inputLine);
     }
     out.close();
     in.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
예제 #26
0
 // MUST BE THE ONLY METHOD THAT TOUCHES textArea!
 public synchronized void run() {
   if (clear) {
     textArea.setText("");
   }
   for (String val : values) {
     curLength += val.length();
     if (val.endsWith(EOL1) || val.endsWith(EOL2)) {
       if (lengths.size() >= maxLines) {
         textArea.replaceRange("", 0, lengths.removeFirst());
       }
       lengths.addLast(curLength);
       curLength = 0;
     }
     textArea.append(val);
   }
   values.clear();
   clear = false;
   queue = true;
 }
  private void populateList() {
    try {
      String path = ".";
      fileList.setText(" ");

      String files;
      File folder = new File(path);
      File[] listOfFiles = folder.listFiles();

      for (int i = 0; i < listOfFiles.length; i++) {

        if (listOfFiles[i].isFile()) {
          files = listOfFiles[i].getName();
          // if(files.endsWith(".dat"))
          fileList.append(files + "\n");
        }
      }
    } catch (java.security.AccessControlException k) {
    }
  }
예제 #28
0
  public void actionPerformed(ActionEvent e) {

    // Handle open button action.
    if (e.getSource() == openButton) {
      int returnVal = fc.showOpenDialog(DirectorySize.this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        // This is where a real application would open the file.
        ListSubDirectorySizes(file);
      } else {
        log.append("Open command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());

      // Handle save button action.
    } else if (e.getSource() == saveButton) {
      log.setText(""); // reset
    }
  }
예제 #29
0
  @Override
  public void run() {
    // TODO Auto-generated method stub
    try {
      Socket s = new Socket(hostin, portin);
      InputStream ins = s.getInputStream();
      OutputStream os = s.getOutputStream();
      ir = new BufferedReader(new InputStreamReader(ins));
      pw = new PrintWriter(new OutputStreamWriter(os), true);

      pw.print(nick);
      while (true) {
        String line = ir.readLine();
        jta.append(line + "\n");
        jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum());
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
예제 #30
-1
  private void saveItem() {

    File f = new File("config.txt");

    if (f.exists() && !f.isDirectory()) {

      try (PrintWriter out =
          new PrintWriter(new BufferedWriter(new FileWriter("config.txt", true)))) {
        if (!searchName.getText().equals("") && !item.getText().equals("")) {

          out.println(
              searchName.getText()
                  + ","
                  + "http://www.reddit.com/r/hardwareswap/search?q="
                  + item.getText()
                  + "&sort=new&restrict_sr=on");
          addItem();

        } else {

          results.setText("Please provide all info for Search Name and Item");
        }

      } catch (IOException e1) {
        results.append("Error saving to file.");
      }

    } else {
      Main.checkFiles();
    }
  }