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());
    }
  }
示例#2
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");
   }
 }
示例#3
0
 public void actionPerformed(ActionEvent ae) {
   String cname = nameF.getText().trim();
   int state = conditions[stateC.getSelectedIndex()];
   try {
     if (isSpecialCase(cname)) {
       handleSpecialCase(cname, state);
     } else {
       JComponent comp = (JComponent) Class.forName(cname).newInstance();
       ComponentUI cui = UIManager.getUI(comp);
       cui.installUI(comp);
       results.setText("Map entries for " + cname + ":\n\n");
       if (inputB.isSelected()) {
         loadInputMap(comp.getInputMap(state), "");
         results.append("\n");
       }
       if (actionB.isSelected()) {
         loadActionMap(comp.getActionMap(), "");
         results.append("\n");
       }
       if (bindingB.isSelected()) {
         loadBindingMap(comp, state);
       }
     }
   } catch (ClassCastException cce) {
     results.setText(cname + " is not a subclass of JComponent.");
   } catch (ClassNotFoundException cnfe) {
     results.setText(cname + " was not found.");
   } catch (InstantiationException ie) {
     results.setText(cname + " could not be instantiated.");
   } catch (Exception e) {
     results.setText("Exception found:\n" + e);
     e.printStackTrace();
   }
 }
示例#4
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.");
 }
示例#5
0
 // サーバーに接続する
 public void connectServer() {
   try {
     socket = new Socket(HOST, PORT);
     msgTextArea.append(">サーバーに接続しました\n");
   } catch (Exception err) {
     msgTextArea.append("ERROR>" + err + "\n");
   }
 }
 private void RodytiKnyguRinkinius() {
   neregKnyguZona.setText("");
   for (Book a : rg.neregKnygos) neregKnyguZona.append(a.toString() + "\n");
   regKnyguZona.setText("");
   for (Map.Entry<String, Book> me : rg.regKnygos.entrySet())
     regKnyguZona.append(String.format("%8s=%s\n", me.getKey(), me.getValue()));
   tfNeregSKaitytojųKiekis.setText(Integer.toString(rg.neregKnygos.size()));
   tfRegSKaitytojųKiekis.setText(Integer.toString(rg.regKnygos.size()));
 }
示例#7
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();
    }
  }
 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()));
 }
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == buttonwrap) {
     textArea.append("Wrap Text. \n");
     setWrapText();
   } else if (e.getSource() == buttonDoNotWrap) {
     textArea.append("Do not wrap text.\n");
     setDoNotWrapText();
   } else if (e.getSource() == buttonBlank) textArea.append("Nothing to see here.\n");
   else if (e.getSource() == buttonClearText) {
     textArea.append("Clear text.\n");
     setClearText();
   } else if (e.getSource() == buttonScrollV) {
     textArea.append("Scrolling vertically.\n");
     setScrollVertical();
   } else if (e.getSource() == buttonScrollH) {
     textArea.append("Scrolling horizontally.\n");
     setScrollHorizontal();
   } else if (e.getSource() == buttonScrollBothWays) {
     textArea.append("Scroll both ways.\n");
     setScrollBothWays();
   } else if (e.getSource() == buttonDoNotScroll) {
     textArea.append("No scrolling allowed.\n");
     setDoNotScroll();
   } else textArea.append("Should not get here!\n");
 }
示例#10
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++;
     }
   }
 }
示例#11
0
 public void loadInputMap(InputMap im, String indent) {
   KeyStroke[] k = im.allKeys();
   if (k == null) {
     results.append(indent + "No InputMap defined\n");
   } else {
     results.append(indent + "\nInputMap (" + k.length + " local keys)\n");
   }
   if (k != null) {
     for (int i = 0; i < k.length; i++) {
       results.append(indent + "  Key:  " + k[i] + ", binding: " + im.get(k[i]) + "\n");
     }
   }
 }
示例#12
0
 public void loadActionMap(ActionMap am, String indent) {
   Object[] k = am.allKeys();
   if (k == null) {
     results.append(indent + "No ActionMap defined\n");
   } else {
     results.append(indent + "\nActionMap (" + k.length + " local keys)\n");
   }
   if (k != null) {
     for (int i = 0; i < k.length; i++) {
       results.append(indent + "  Action:  " + k[i] + "\n");
     }
   }
 }
示例#13
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");
 }
示例#14
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);
  }
示例#15
0
  @Override
  public void run() {
    while (true) {
      try {
        String msgFromClient = din.readUTF();
        StringTokenizer st = new StringTokenizer(msgFromClient);
        String loginName = st.nextToken();

        if (loginName.equals("server")) // message is from server, special request
        {
          String MsgType = st.nextToken();

          if (MsgType.equals("newRoom")) // create a new chatclient window
          {
            String token;
            token = st.nextToken();
            new ChatClient(loginName + " - " + token, userId, Integer.parseInt(token));
          }

        } else
          ta.append(
              " \n"
                  + msgFromClient); // normal communication, display all text received from server
                                    // onto text area.

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
示例#16
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);
      }
  }
示例#17
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());
      }
    }
  }
示例#18
0
 /**
  * Add a line of text to the transcript area.
  *
  * @param message text to be added; two line feeds is added at the end.
  */
 private void postMessage(String message) {
   transcript.append(message + "\n\n");
   // The following line is a nasty kludge that was the only way I could find to force
   // the transcript to scroll so that the text that was just added is visible in
   // the window.  Without this, text can be added below the bottom of the visible area
   // of the transcript.
   transcript.setCaretPosition(transcript.getDocument().getLength());
 }
示例#19
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");
  }
示例#20
0
  public void loadBindingMap(InputMap im, ActionMap am) {
    results.append("Bound Actions\n");
    String unboundActions = "";
    String unboundInputKeys = "";
    Hashtable mi = buildReverseMap(im);
    Object[] k = am.allKeys();
    if (k != null) {
      for (int i = 0; i < k.length; i++) {
        if (mi.containsKey(k[i])) {
          results.append("  " + getActionName(k[i]));
          results.append(";" + mi.get(k[i]) + "\n");
        } else {
          unboundActions += ("  " + getActionName(k[i]) + "\n");
        }
      }
      results.append("\nUnbound Actions\n\n");
      results.append(unboundActions);
    }

    results.append("\nUnbound InputMap Entries\n");
    k = im.allKeys();
    if (k != null) {
      for (int i = 0; i < k.length; i++) {
        KeyStroke key = (KeyStroke) k[i];
        Object actionKey = im.get(key);
        if (am.get(actionKey) == null) {
          results.append("  " + im.get((KeyStroke) k[i]) + ": " + k[i] + "\n");
        }
      }
    }
  }
示例#21
0
  public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();

    // Make sure the new text is visible, even if there
    // was a selection in the text area.
    textArea.setCaretPosition(textArea.getDocument().getLength());
  }
示例#22
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");
   }
 }
示例#23
0
  public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand().equals("Add User")) {
      jta.append("\n" + userId.getText());

      User user = new User(userId.getText());
    } else if (ae.getActionCommand().equals("Add Group")) {
      jta.append("\n" + groupId.getText());

      Group group = new Group(groupId.getText());
    } else if (ae.getActionCommand().equals("Open User View")) {
      try {
        if (!jta.getSelectedText().equals("null")) {
          userView.setVisible(true);
        }
      } catch (Exception e) {
        JOptionPane.showMessageDialog(
            frame, "Nothing selected", "Error", JOptionPane.ERROR_MESSAGE);
      }
    } else if (ae.getActionCommand().equals("Show User Total")) {
      JOptionPane.showMessageDialog(frame, User.getUserTotal());
    } else if (ae.getActionCommand().equals("Show Group Total")) {
      JOptionPane.showMessageDialog(frame, Group.getGroupTotal());
    } else if (ae.getActionCommand().equals("Show Messages Total")) {
      JOptionPane.showMessageDialog(frame, User.getMessageTotal());
    } else if (ae.getActionCommand().equals("Show Positive Percentage")) {
      String[] newsFeed = User.getNewsFeed();

      int positive = 0;
      int i = 0;
      while (!(newsFeed[i] == null)) {
        if (newsFeed[i].contains("good")
            || newsFeed[i].contains("great")
            || newsFeed[i].contains("excellent")) positive++;
        i++;
      }

      JOptionPane.showMessageDialog(frame, positive * 100.0 / i + "%");
    } else if (ae.getActionCommand().equals("Follow User")) {
      following.append("\n" + userId2.getText());
    } else if (ae.getActionCommand().equals("Post Tweet")) {
      User.postTweet(tweet.getText());
      newsFeed.append("\n" + jta.getSelectedText() + ": " + tweet.getText());
    }
  }
示例#24
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");
    }
  }
示例#25
0
 @Override
 public void actionPerformed(ActionEvent e) {
   // TODO Auto-generated method stub
   if (e.getSource() == convert || e.getSource() == input) {
     if (miUnit.isSelected()) {
       double miles = Double.parseDouble(input.getText());
       double km = MetricConverter.milesToKm(miles);
       display.append(miles + " miles equals " + km + " kilometers\n");
       input.setText("");
     } else {
       double km = Double.parseDouble(input.getText());
       double miles = MetricConverter.kmToMile(km);
       display.append(km + " km equals " + miles + " miles\n");
       input.setText("");
     }
   } else {
     JButton b = (JButton) e.getSource();
     if (b.getText().equals("C")) input.setText("");
     else input.setText(input.getText() + b.getText());
   }
 }
示例#26
0
  // calculate and display amounts
  private void calculateJButtonActionPerformed(ActionEvent event) {
    resultJTextArea.setText("Rate (%)\tAmount after 10 years");
    DecimalFormat dollars = new DecimalFormat("$0.00");

    int principal = Integer.parseInt(principalJTextField.getText());

    // for loop to calculate interest
    for (int rate = 5; rate <= 10; rate++) {
      double amount = (double) principal * Math.pow(1 + ((double) rate / 100), 10);
      resultJTextArea.append("\n" + rate + "\t" + dollars.format(amount));
    } // end for
  } // end method calculateJButtonActionPerformed
示例#27
0
 private void handleSpecialCase(String cname, int condition) {
   Component comp = null;
   JComponent mapComp = null;
   try {
     if (cname.equals("javax.swing.JApplet")
         || cname.equals("javax.swing.JDialog")
         || cname.equals("javax.swing.JFrame")
         || cname.equals("javax.swing.JWindow")) {
       comp = (Component) Class.forName(cname).newInstance();
       mapComp = (JComponent) ((JApplet) comp).getLayeredPane();
       results.setText("Map entries for " + cname + " (delegated to JRootPane):\n\n");
     } else if (cname.equals("javax.swing.JInternalFrame")) {
       JDesktopPane jdp = new JDesktopPane();
       JInternalFrame jif = new JInternalFrame("Demo");
       jif.setVisible(true);
       jdp.add(jif);
       mapComp = jif;
     }
     if (inputB.isSelected()) {
       loadInputMap(mapComp.getInputMap(condition), "");
       results.append("\n");
     }
     if (actionB.isSelected()) {
       loadActionMap(mapComp.getActionMap(), "");
       results.append("\n");
     }
     if (bindingB.isSelected()) {
       loadBindingMap(mapComp, condition);
     }
   } catch (ClassCastException cce) {
     results.setText(cname + " is not a subclass of JComponent.");
   } catch (ClassNotFoundException cnfe) {
     results.setText(cname + " was not found.");
   } catch (InstantiationException ie) {
     results.setText(cname + " could not be instantiated.");
   } catch (Exception e) {
     results.setText("Exception found:\n" + e);
     e.printStackTrace();
   }
 }
示例#28
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
示例#29
0
  // Method to build the dialog box for help.
  private void buildDialogBox() {
    // Set the JDialog window properties.
    setTitle("Stack Trace Detail");
    setResizable(false);
    setSize(dialogWidth, dialogHeight);

    // Append the stack trace output to the display area.
    displayArea.append(eStackTrace);

    // Create horizontal and vertical scrollbars for box.
    displayBox = Box.createHorizontalBox();
    displayBox = Box.createVerticalBox();

    // Add a JScrollPane to the Box.
    displayBox.add(new JScrollPane(displayArea));

    // Define behaviors of container.
    c.setLayout(null);
    c.add(displayBox);
    c.add(okButton);

    // Set scroll pane bounds.
    displayBox.setBounds(
        (dialogWidth / 2) - ((displayAreaWidth / 2) + 2),
        (top + (offsetMargin / 2)),
        displayAreaWidth,
        displayAreaHeight);

    // Set the behaviors, bounds and action listener for the button.
    okButton.setBounds(
        (dialogWidth / 2) - (buttonWidth / 2),
        (displayAreaHeight + offsetMargin),
        buttonWidth,
        buttonHeight);

    // Set the font to the platform default Font for the object with the
    // properties of bold and font size of 11.
    okButton.setFont(new Font(okButton.getFont().getName(), Font.BOLD, 11));

    // The class implements the ActionListener interface and therefore
    // provides an implementation of the actionPerformed() method.  When a
    // class implements ActionListener, the instance handler returns an
    // ActionListener.  The ActionListener then performs actionPerformed()
    // method on an ActionEvent.
    okButton.addActionListener(this);

    // Set the screen and display dialog window in relation to screen size.
    setLocation((dim.width / 2) - (dialogWidth / 2), (dim.height / 2) - (dialogHeight / 2));

    // Display JDialog.
    show();
  } // End of buildDialogBox method.
示例#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();
    }
  }