Exemplo n.º 1
1
  public String getTextForGesture(long parId, Point topLeft, Point bottomRight) {

    try {
      Paragraph p = lockManager.getParFromId(parId);

      int parY = documentPanel.textPane.modelToView(p.getOffset()).y;

      topLeft.y = topLeft.y + parY;
      bottomRight.y = bottomRight.y + parY;

      int startOffset = documentPanel.textPane.viewToModel(topLeft);
      int endOffset = documentPanel.textPane.viewToModel(bottomRight);

      while (startOffset > 0
          && Character.isLetterOrDigit((document.getText(startOffset - 1, 1).charAt(0))))
        startOffset--;

      while (endOffset < document.getLength()
          && Character.isLetterOrDigit((document.getText(endOffset, 1).charAt(0)))) endOffset++;

      String text = document.getText(startOffset, endOffset - startOffset);
      return text;
    } catch (Exception e) {
      System.out.println("EditorClient: addGestureAction. error identifying text");
      e.printStackTrace();
      return "";
    }

    // return "PLACEBO";
  }
Exemplo n.º 2
1
  /**
   * Sets a mnemomic for the specified button.
   *
   * @param b button
   * @param mnem mnemonics that have already been assigned
   */
  public static void setMnemonic(final AbstractButton b, final StringBuilder mnem) {
    // do not set mnemonics for Mac! Alt+key used for special characters.
    if (Prop.MAC) return;

    // find and assign unused mnemomic
    final String label = b.getText();
    final int ll = label.length();
    for (int l = 0; l < ll; l++) {
      final char ch = Character.toLowerCase(label.charAt(l));
      if (!letter(ch) || mnem.indexOf(Character.toString(ch)) != -1) continue;
      b.setMnemonic(ch);
      mnem.append(ch);
      break;
    }
  }
Exemplo n.º 3
1
 public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
     throws BadLocationException {
   StringBuilder builder = new StringBuilder(string);
   for (int i = builder.length() - 1; i >= 0; i--) {
     int cp = builder.codePointAt(i);
     if (!Character.isDigit(cp) && cp != '-') {
       builder.deleteCharAt(i);
       if (Character.isSupplementaryCodePoint(cp)) {
         i--;
         builder.deleteCharAt(i);
       }
     }
   }
   super.insertString(fb, offset, builder.toString(), attr);
 }
Exemplo n.º 4
1
 public PropertyAction(RADProperty<?> aProperty) {
   super();
   property = (RADProperty<Object>) aProperty;
   String name = (String) aProperty.getValue("actionName"); // NOI18N
   if (name == null) {
     StringBuilder sb = new StringBuilder(aProperty.getName());
     sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
     name = sb.toString();
   }
   putValue(Action.NAME, name);
 }
Exemplo n.º 5
0
 /** Controls the movements and actions of character and tetris pieces */
 public void keyPressed(KeyEvent key) {
   String keyText = KeyEvent.getKeyText(key.getKeyCode());
   if (!pause) {
     if (!shapeAI.getAI()) {
       if (keyText.equalsIgnoreCase("a")) {
         shapes.get(0).moveLeft(map);
         shapeTrack.add(1);
       }
       if (keyText.equalsIgnoreCase("d")) {
         shapes.get(0).moveRight(map);
         shapeTrack.add(2);
       }
       if (keyText.equalsIgnoreCase("w")) {
         shapes.get(0).turn(map, shapeTrack);
       }
     }
     if (keyText.equalsIgnoreCase("left")) {
       character.moveLeft();
     }
     if (keyText.equalsIgnoreCase("right")) {
       character.moveRight();
     }
     if (keyText.equalsIgnoreCase("up")) {
       character.jump();
     }
     if (keyText.equalsIgnoreCase("Slash")) {
       guntrack += 1;
       if (guntrack > weapons.length - 1) {
         guntrack = 0;
       }
     }
   }
   repaint();
 }
Exemplo n.º 6
0
 public void mouseMoved(MouseEvent e) {
   int k = html.viewToModel(e.getPoint());
   if (html.hasFocus() && html.getSelectionStart() <= k && k < html.getSelectionEnd()) {
     setMessage("(on selection)", MOVE);
     return;
   }
   String s = text.getText(); // "";
   int m = s.length(); // html.getDocument().getLength();
   /*try {
          s = html.getText(0, m);
      } catch (BadLocationException x) {
   setMessage("BadLocation "+m, TEXT); return;
      } */
   if (!Character.isLetter(s.charAt(k))) {
     setMessage("(not a letter)", TEXT);
     return;
   }
   selB = k;
   selE = k + 1;
   while (!Character.isWhitespace(s.charAt(selB - 1))) selB--;
   while (!Character.isWhitespace(s.charAt(selE))) selE++;
   setMessage(selB + "-" + selE, HAND);
   word = "";
   for (int i = selB; i < selE; i++) if (Character.isLetter(s.charAt(i))) word += s.charAt(i);
   html.setToolTipText(word);
 }
Exemplo n.º 7
0
 /** Fires weapons when left mouse is pressed */
 public void mousePressed(MouseEvent evt) {
   int mx = evt.getX(); // x-coordinate where user clicked.
   int my = evt.getY(); // y-coordinate where user clicked.
   if (!pause) {
     if (!evt.isMetaDown()) {
       if (weapons[guntrack].equals("gun") && bshoot) {
         weaponList.add(
             new Bullet(
                 mx, my, character.getX(), character.getY(), 0, THA.WIDTH, 0, THA.HEIGHT, 7));
         bshoot = false;
         ammo.useBullet();
         bulletTime.restart();
       }
       if (weapons[guntrack].equals("grenade") && gshoot) {
         weaponList.add(
             new Grenade(
                 mx, my, character.getX(), character.getY(), 0, THA.WIDTH, 0, THA.HEIGHT, 12));
         gshoot = false;
         ammo.useGrenade();
         grenadeTime.restart();
       }
       if (weapons[guntrack].equals("laser") && lshoot) {
         weaponList.add(
             new Laser(
                 mx, my, character.getX(), character.getY(), 0, THA.WIDTH, 0, THA.HEIGHT, 20));
         lshoot = false;
         ammo.useLaser();
         laserTime.restart();
       }
       if (weapons[guntrack].equals("shotgun") && sgshoot) {
         weaponList.add(
             new ShotGun(
                 mx,
                 my,
                 character.getX(),
                 character.getY(),
                 0,
                 THA.WIDTH,
                 0,
                 THA.HEIGHT,
                 7,
                 character.getX(),
                 character.getY(),
                 25,
                 90,
                 weaponList));
         sgshoot = false;
         ammo.useShotgun();
         shotgunTime.restart();
       }
     }
   }
 }
Exemplo n.º 8
0
 public void keyReleased(KeyEvent key) {
   String keyText = KeyEvent.getKeyText(key.getKeyCode());
   if (!pause) {
     if (keyText.equalsIgnoreCase("left")) {
       character.stop();
     }
     if (keyText.equalsIgnoreCase("right")) {
       character.stop();
     }
   }
   repaint();
 }
Exemplo n.º 9
0
  /**
   * Retrieves the word on which the mouse pointer is present
   *
   * @param evt - the MouseEvent which triggered this method
   */
  private String fetchPhrase(MouseEvent evt) {
    Messages.log("--handle Mouse Right Click--");
    int off = xyToOffset(evt.getX(), evt.getY());
    if (off < 0) return null;
    int line = getLineOfOffset(off);
    if (line < 0) return null;
    String s = getLineText(line);
    if (s == null) return null;
    else if (s.length() == 0) return null;
    else {
      int x = xToOffset(line, evt.getX()), x2 = x + 1, x1 = x - 1;
      int xLS = off - getLineStartNonWhiteSpaceOffset(line);
      Messages.log("x=" + x);
      if (x < 0 || x >= s.length()) return null;
      String word = s.charAt(x) + "";
      if (s.charAt(x) == ' ') return null;
      if (!(Character.isLetterOrDigit(s.charAt(x)) || s.charAt(x) == '_' || s.charAt(x) == '$'))
        return null;
      int i = 0;
      while (true) {
        i++;
        if (x1 >= 0 && x1 < s.length()) {
          if (Character.isLetter(s.charAt(x1)) || s.charAt(x1) == '_') {
            word = s.charAt(x1--) + word;
            xLS--;
          } else x1 = -1;
        } else x1 = -1;

        if (x2 >= 0 && x2 < s.length()) {
          if (Character.isLetterOrDigit(s.charAt(x2)) || s.charAt(x2) == '_' || s.charAt(x2) == '$')
            word = word + s.charAt(x2++);
          else x2 = -1;
        } else x2 = -1;

        if (x1 < 0 && x2 < 0) break;
        if (i > 200) {
          // time out!
          break;
        }
      }
      if (Character.isDigit(word.charAt(0))) {
        return null;
      }
      Messages.log("Mouse click, word: " + word.trim());
      ASTGenerator astGenerator = editor.getErrorChecker().getASTGenerator();
      synchronized (astGenerator) {
        astGenerator.setLastClickedWord(line, word, xLS);
      }
      return word.trim();
    }
  }
Exemplo n.º 10
0
    /**
     * Set the fields from the ProjectionClass
     *
     * @param projClass projection class to use
     */
    private void setFieldsWithClassParams(ProjectionClass projClass) {

      // set the projection in the JComboBox
      String want = projClass.toString();
      for (int i = 0; i < projClassCB.getItemCount(); i++) {
        ProjectionClass pc = (ProjectionClass) projClassCB.getItemAt(i);
        if (pc.toString().equals(want)) {
          projClassCB.setSelectedItem((Object) pc);
          break;
        }
      }

      // set the parameter fields
      paramPanel.removeAll();
      paramPanel.setVisible(0 < projClass.paramList.size());

      List widgets = new ArrayList();
      for (int i = 0; i < projClass.paramList.size(); i++) {
        ProjectionParam pp = (ProjectionParam) projClass.paramList.get(i);
        // construct the label
        String name = pp.name;
        String text = "";
        // Create a decent looking label
        for (int cIdx = 0; cIdx < name.length(); cIdx++) {
          char c = name.charAt(cIdx);
          if (cIdx == 0) {
            c = Character.toUpperCase(c);
          } else {
            if (Character.isUpperCase(c)) {
              text += " ";
              c = Character.toLowerCase(c);
            }
          }
          text += c;
        }
        widgets.add(GuiUtils.rLabel(text + ": "));
        // text input field
        JTextField tf = new JTextField();
        pp.setTextField(tf);
        tf.setColumns(12);
        widgets.add(tf);
      }
      GuiUtils.tmpInsets = new Insets(4, 4, 4, 4);
      JPanel widgetPanel = GuiUtils.doLayout(widgets, 2, GuiUtils.WT_N, GuiUtils.WT_N);

      paramPanel.add("North", widgetPanel);
      paramPanel.add("Center", GuiUtils.filler());
    }
Exemplo n.º 11
0
    @Override
    public void insertString(final int offs, final String str, final AttributeSet a)
        throws BadLocationException {
      // NavigatorLogger.printMessage("Offset:"+offs+" STr:"+str+"L:"+getLength()+"attr:"+a);

      if ((getLength() + str.length()) <= maxLength) {
        final char[] source = str.toCharArray();
        final char[] result = new char[source.length];
        int j = 0;

        for (int i = 0; i < result.length; i++) {
          if (Character.isDigit(source[i])) {
            result[j++] = source[i];
          } else {
            toolkit.beep();
            if (log.isDebugEnabled()) {
              log.debug("insertString: " + source[i]); // NOI18N
            }
          }
        }
        super.insertString(offs, new String(result, 0, j), a);
        checked = false;
      } else {
        toolkit.beep();
      }
      if ((getLength()) == maxLength) { // getLength() ist schon aktualisiert
        if (bringFocus2Next == true) {
          checked = true;
          nextField.requestFocus();
        }
        // NavigatorLogger.printMessage("Sprung");
        // NavigatorLogger.printMessage(nextField);
      }
    }
Exemplo n.º 12
0
  String cleanupSource(String source) {
    if (source.isEmpty()) {
      return source.concat("\n");
    }

    int lastChIdx = source.length() - 1;
    if (source.charAt(lastChIdx) != '\n') {
      // Append a newline at the end
      source = source.concat("\n");
    } else {
      // Remove all newlines at the end but one
      while (lastChIdx >= 1) {
        Character ch1 = source.charAt(lastChIdx);
        if (ch1 == '\n' || Character.isWhitespace(ch1)) {
          source = source.substring(0, lastChIdx--);
        } else {
          break;
        }
      }

      source = source.concat("\n");
    }

    return source;
  }
Exemplo n.º 13
0
 /** Returns the contents of the next text field. */
 public String getNextString() {
   String theText;
   if (stringField == null) return "";
   TextField tf = (TextField) (stringField.elementAt(sfIndex));
   theText = tf.getText();
   if (macro) {
     String label = (String) labels.get((Object) tf);
     theText = Macro.getValue(macroOptions, label, theText);
     if (theText != null
         && (theText.startsWith("&") || label.toLowerCase(Locale.US).startsWith(theText))) {
       // Is the value a macro variable?
       if (theText.startsWith("&")) theText = theText.substring(1);
       Interpreter interp = Interpreter.getInstance();
       String s = interp != null ? interp.getVariableAsString(theText) : null;
       if (s != null) theText = s;
     }
   }
   if (recorderOn) {
     String s = theText;
     if (s != null
         && s.length() >= 3
         && Character.isLetter(s.charAt(0))
         && s.charAt(1) == ':'
         && s.charAt(2) == '\\')
       s = s.replaceAll("\\\\", "\\\\\\\\"); // replace "\" with "\\" in Windows file paths
     if (!smartRecording || !s.equals((String) defaultStrings.elementAt(sfIndex)))
       recordOption(tf, s);
     else if (Recorder.getCommandOptions() == null) Recorder.recordOption(" ");
   }
   sfIndex++;
   return theText;
 }
  @Override
  public void keyPressed(final KeyEvent e) {
    if (!(e.isAltDown() || e.isMetaDown() || e.isControlDown() || myPanel.isNodePopupActive())) {
      if (!Character.isLetter(e.getKeyChar())) {
        return;
      }

      final IdeFocusManager focusManager = IdeFocusManager.getInstance(myPanel.getProject());
      final ActionCallback firstCharTyped = new ActionCallback();
      focusManager.typeAheadUntil(firstCharTyped);
      myPanel.moveDown();
      //noinspection SSBasedInspection
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                final Robot robot = new Robot();
                final boolean shiftOn = e.isShiftDown();
                final int code = e.getKeyCode();
                if (shiftOn) {
                  robot.keyPress(KeyEvent.VK_SHIFT);
                }
                robot.keyPress(code);
                robot.keyRelease(code);

                // don't release Shift
                firstCharTyped.setDone();
              } catch (AWTException ignored) {
              }
            }
          });
    }
  }
Exemplo n.º 15
0
 // keyboard discovery code
 private void _mapKey(char charCode, int keyindex, boolean shift, boolean altgraph) {
   log("_mapKey: " + charCode);
   // if character is not in map, add it
   if (!charMap.containsKey(new Integer(charCode))) {
     log("Notified: " + (char) charCode);
     KeyEvent event =
         new KeyEvent(
             applet(),
             0,
             0,
             (shift ? KeyEvent.SHIFT_MASK : 0) + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
             ((Integer) vkKeys.get(keyindex)).intValue(),
             (char) charCode);
     charMap.put(new Integer(charCode), event);
     log("Mapped char " + (char) charCode + " to KeyEvent " + event);
     if (((char) charCode) >= 'a' && ((char) charCode) <= 'z') {
       // put shifted version of a-z in automatically
       int uppercharCode = (int) Character.toUpperCase((char) charCode);
       event =
           new KeyEvent(
               applet(),
               0,
               0,
               KeyEvent.SHIFT_MASK + (altgraph ? KeyEvent.ALT_GRAPH_MASK : 0),
               ((Integer) vkKeys.get(keyindex)).intValue(),
               (char) uppercharCode);
       charMap.put(new Integer(uppercharCode), event);
       log("Mapped char " + (char) uppercharCode + " to KeyEvent " + event);
     }
   }
 }
Exemplo n.º 16
0
  /**
   * This is the write() method of the stream. All Writer subclasses implement this. All other
   * versions of write() are variants of this one
   */
  public void write(char[] buffer, int index, int len) {
    synchronized (this.lock) {
      // Loop through all the characters passed to us
      for (int i = index; i < index + len; i++) {
        // If we haven't begun a page (or a new page), do that now.
        if (page == null) newpage();

        // If the character is a line terminator, then begin new line,
        // unless it is a \n immediately after a \r.
        if (buffer[i] == '\n') {
          if (!last_char_was_return) newline();
          continue;
        }
        if (buffer[i] == '\r') {
          newline();
          last_char_was_return = true;
          continue;
        } else last_char_was_return = false;

        // If it some other non-printing character, ignore it.
        if (Character.isWhitespace(buffer[i])
            && !Character.isSpaceChar(buffer[i])
            && (buffer[i] != '\t')) continue;

        // If no more characters will fit on the line, start a new line.
        if (charnum >= chars_per_line) {
          newline();
          if (page == null) newpage(); // and start a new page, if necessary
        }

        // Now print the character:
        // If it is a space, skip one space, without output.
        // If it is a tab, skip the necessary number of spaces.
        // Otherwise, print the character.
        // It is inefficient to draw only one character at a time, but
        // because our FontMetrics don't match up exactly to what the
        // printer uses we need to position each character individually.
        if (Character.isSpaceChar(buffer[i])) charnum++;
        else if (buffer[i] == '\t') charnum += 8 - (charnum % 8);
        else {
          page.drawChars(
              buffer, i, 1, x0 + charnum * charwidth, y0 + (linenum * lineheight) + lineascent);
          charnum++;
        }
      }
    }
  }
Exemplo n.º 17
0
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == from) {
      String tmpFrom = from.getText().trim();
      String tmpTo = to.getText().trim();
      if (tmpFrom.equals("MST") || tmpFrom.equals("mst")) findMinSpan();
      else {
        try { // check if from exists
          // String str = from.getText();
          // fixa så man kan skippa att skriva första med stor bokstav
          tmpFrom = Character.toUpperCase(tmpFrom.charAt(0)) + tmpFrom.substring(1);
          int pos = noderna.findLeading(tmpFrom).getNodeNo();
          route.setText(introText + "\n");
          from.setText(noderna.find(pos).toString());
        } catch (NullPointerException npe) {
          route.setText(felTextStart + "\n");
          return;
        }
        if (!tmpTo.equals("")) {
          findShort();
        }
      }
    } else if (e.getSource() == to) {
      String tmpFrom = from.getText().trim();
      String tmpTo = to.getText().trim();
      if (tmpTo.equals("MST") || tmpTo.equals("mst")) findMinSpan();
      else {
        try { // check if to exists
          // String str = to.getText();
          tmpTo = Character.toUpperCase(tmpTo.charAt(0)) + tmpTo.substring(1);
          int pos = noderna.findLeading(tmpTo).getNodeNo();
          route.setText(introText + "\n");
          to.setText(noderna.find(pos).toString());
        } catch (NullPointerException npe) {
          route.setText(felTextStart + "\n");
          return;
        }
        if (!tmpFrom.equals("")) {
          findShort();
        }
      }

      /*
      else if ( ! from.getText().equals("") )
      	findShort();
      */
    }
  }
  /** Handle a key typed event. This inserts the key into the text area. */
  public void keyTyped(KeyEvent evt) {
    int modifiers = evt.getModifiers();
    char c = evt.getKeyChar();

    // this is the apple/cmd key on macosx.. so menu commands
    // were being passed through as legit keys.. added this line
    // in an attempt to prevent.
    if ((modifiers & KeyEvent.META_MASK) != 0) return;

    if (c != KeyEvent.CHAR_UNDEFINED) // &&
    //                (modifiers & KeyEvent.ALT_MASK) == 0)
    {
      if (c >= 0x20 && c != 0x7f) {
        KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.toUpperCase(c));
        Object o = currentBindings.get(keyStroke);

        if (o instanceof Hashtable) {
          currentBindings = (Hashtable) o;
          return;
        } else if (o instanceof ActionListener) {
          currentBindings = bindings;
          executeAction((ActionListener) o, evt.getSource(), String.valueOf(c));
          return;
        }

        currentBindings = bindings;

        if (grabAction != null) {
          handleGrabAction(evt);
          return;
        }

        // 0-9 adds another 'digit' to the repeat number
        if (repeat && Character.isDigit(c)) {
          repeatCount *= 10;
          repeatCount += (c - '0');
          return;
        }

        executeAction(INSERT_CHAR, evt.getSource(), String.valueOf(evt.getKeyChar()));

        repeatCount = 0;
        repeat = false;
      }
    }
  }
Exemplo n.º 19
0
    public void processKeyEvent(KeyEvent evt) {
      evt = KeyEventWorkaround.processKeyEvent(evt);
      if (evt == null) return;

      switch (evt.getID()) {
        case KeyEvent.KEY_TYPED:
          char ch = evt.getKeyChar();
          if (!nonDigit && Character.isDigit(ch)) {
            super.processKeyEvent(evt);
            repeat = true;
            repeatCount = Integer.parseInt(action.getText());
          } else {
            nonDigit = true;
            if (repeat) {
              passToView(evt);
            } else super.processKeyEvent(evt);
          }
          break;
        case KeyEvent.KEY_PRESSED:
          int keyCode = evt.getKeyCode();
          if (evt.isActionKey()
              || evt.isControlDown()
              || evt.isAltDown()
              || evt.isMetaDown()
              || keyCode == KeyEvent.VK_BACK_SPACE
              || keyCode == KeyEvent.VK_DELETE
              || keyCode == KeyEvent.VK_ENTER
              || keyCode == KeyEvent.VK_TAB
              || keyCode == KeyEvent.VK_ESCAPE) {
            nonDigit = true;
            if (repeat) {
              passToView(evt);
              break;
            } else if (keyCode == KeyEvent.VK_TAB) {
              complete(true);
              evt.consume();
            } else if (keyCode == KeyEvent.VK_ESCAPE) {
              evt.consume();
              if (popup != null) {
                popup.dispose();
                popup = null;
                action.requestFocus();
              } else {
                if (temp) view.removeToolBar(ActionBar.this);
                view.getEditPane().focusOnTextArea();
              }
              break;
            } else if ((keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN)
                && popup != null) {
              popup.list.processKeyEvent(evt);
              break;
            }
          }
          super.processKeyEvent(evt);
          break;
      }
    }
  /**
   * Converts a string to a keystroke. The string should be of the form
   * <i>modifiers</i>+<i>shortcut</i> where <i>modifiers</i> is any combination of A for Alt, C for
   * Control, S for Shift or M for Meta, and <i>shortcut</i> is either a single character, or a
   * keycode name from the <code>KeyEvent</code> class, without the <code>VK_</code> prefix.
   *
   * @param keyStroke A string description of the key stroke
   */
  public static KeyStroke parseKeyStroke(String keyStroke) {
    if (keyStroke == null) return null;
    int modifiers = 0;
    int index = keyStroke.indexOf('+');
    if (index != -1) {
      for (int i = 0; i < index; i++) {
        switch (Character.toUpperCase(keyStroke.charAt(i))) {
          case 'A':
            modifiers |= InputEvent.ALT_MASK;
            break;
          case 'C':
            modifiers |= InputEvent.CTRL_MASK;
            break;
          case 'M':
            modifiers |= InputEvent.META_MASK;
            break;
          case 'S':
            modifiers |= InputEvent.SHIFT_MASK;
            break;
        }
      }
    }
    String key = keyStroke.substring(index + 1);
    if (key.length() == 1) {
      char ch = Character.toUpperCase(key.charAt(0));
      if (modifiers == 0) return KeyStroke.getKeyStroke(ch);
      else return KeyStroke.getKeyStroke(ch, modifiers);
    } else if (key.length() == 0) {
      System.err.println("Invalid key stroke: " + keyStroke);
      return null;
    } else {
      int ch;

      try {
        ch = KeyEvent.class.getField("VK_".concat(key)).getInt(null);
      } catch (Exception e) {
        System.err.println("Invalid key stroke: " + keyStroke);
        return null;
      }

      return KeyStroke.getKeyStroke(ch, modifiers);
    }
  }
Exemplo n.º 21
0
  /** Handle a key typed event. This inserts the key into the text area. */
  @Override
  @SuppressWarnings("unchecked")
  public void keyTyped(KeyEvent evt) {
    int modifiers = evt.getModifiers();
    char c = evt.getKeyChar();
    if (c != KeyEvent.CHAR_UNDEFINED && (modifiers & InputEvent.ALT_MASK) == 0) {
      if (c >= 0x20 && c != 0x7f) {
        KeyStroke keyStroke = KeyStroke.getKeyStroke(Character.toUpperCase(c));
        Object o = currentBindings.get(keyStroke);

        if (o instanceof Hashtable) {
          currentBindings = (Hashtable) o;
          return;
        } else if (o instanceof ActionListener) {
          currentBindings = bindings;
          executeAction((ActionListener) o, evt.getSource(), String.valueOf(c));
          return;
        }

        currentBindings = bindings;

        if (grabAction != null) {
          handleGrabAction(evt);
          return;
        }

        // 0-9 adds another 'digit' to the repeat number
        if (repeat && Character.isDigit(c)) {
          repeatCount *= 10;
          repeatCount += (c - '0');
          return;
        }

        executeAction(INSERT_CHAR, evt.getSource(), String.valueOf(evt.getKeyChar()));

        repeatCount = 0;
        repeat = false;
      }
    }
  }
Exemplo n.º 22
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
Exemplo n.º 23
0
 private boolean isNameAddress(String text) {
   boolean maybe = false;
   if (text != null) {
     for (int i = 0; i < text.length(); i++) {
       char c = text.charAt(i);
       if (Character.getType(c) == Character.OTHER_LETTER) {
         maybe = true;
         break;
       }
     }
   }
   return maybe;
 }
Exemplo n.º 24
0
  /**
   * Handles info messages resulting from a query execution.
   *
   * @param msg info message
   * @return true if error was found
   */
  private boolean error(final String msg) {
    final String line = msg.replaceAll("[\\r\\n].*", "");
    Matcher m = XQERROR.matcher(line);
    int el, ec = 2;
    if (!m.matches()) {
      m = XMLERROR.matcher(line);
      if (!m.matches()) return true;
      el = Integer.parseInt(m.group(1));
      errFile = getEditor().file.path();
    } else {
      el = Integer.parseInt(m.group(1));
      ec = Integer.parseInt(m.group(2));
      errFile = m.group(3);
    }

    final EditorArea edit = find(IO.get(errFile), false);
    if (edit == null) return true;

    // find approximate error position
    final int ll = edit.last.length;
    int ep = ll;
    for (int e = 1, l = 1, c = 1; e < ll; ++c, e += cl(edit.last, e)) {
      if (l > el || l == el && c == ec) {
        ep = e;
        break;
      }
      if (edit.last[e] == '\n') {
        ++l;
        c = 0;
      }
    }
    if (ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
      while (ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
    }
    edit.error(ep);
    errPos = ep;
    return true;
  }
Exemplo n.º 25
0
  /** Handle remove. */
  public void remove(int offs, int length) throws BadLocationException {
    int sourceLength = getLength();

    // Allow user to restore uninitialized state again by removing all

    if (offs == 0 && sourceLength == length) {
      super.remove(0, sourceLength);
      return;
    }

    // Do custom remove

    String sourceText = getText(0, sourceLength);
    StringBuffer strBuffer = new StringBuffer(sourceText.substring(0, offs));
    int counter;

    for (counter = offs; counter < offs + length; counter++) {
      // Only remove digits and intDelims

      char currChar = sourceText.charAt(counter);

      if (Character.isDigit(currChar) || currChar == intDelim) {
        continue;
      }

      strBuffer.append(currChar);
    }

    // Append last part of sourceText

    if (counter < sourceLength) {
      strBuffer.append(sourceText.substring(counter));
    }

    // Set text in field

    super.remove(0, sourceLength);
    insertString(0, strBuffer.toString(), (AttributeSet) getDefaultRootElement());

    // Set caret pos

    int newDiff = sourceLength - getLength() - 1;
    if (newDiff < 0) {
      newDiff = 0;
    }
    if (offs - newDiff < 0) {
      newDiff = 0;
    }
    textField.setCaretPosition(offs - newDiff);
  }
Exemplo n.º 26
0
 public void paintComponent(Graphics g) {
   super.paintComponent(g);
   map.drawMap(g);
   gs.imitate(shapes.get(0), map);
   gs.draw(g);
   if (shapes.size() > 0) shapes.get(0).draw(g);
   character.putCharacter(g); // draws the character
   for (int i = 0; i < weaponList.size(); i++) {
     weaponList.get(i).draw(g); // draws each weapon object
   }
   water.draw(g); // draws the water image
   g.setColor(Color.black);
   g.drawString("score: ", 300, 350);
 }
Exemplo n.º 27
0
  public void keyPressed(KeyEvent e) {
    int l_keyCode = e.getKeyCode();
    char l_keyChar = e.getKeyChar();

    // System.out.println(e.paramString());

    if (m_ac.isGameInProgress() && m_inputControls.isWeaponEvent(l_keyChar)) {
      Weapon l_weapon = null;

      int l_weaponSlot = Character.digit(l_keyChar, 10);
      l_weapon = (Weapon) m_inventory.getAndRemoveItemAt(l_weaponSlot);

      if (null != l_weapon) {
        m_ac.useWeapon(l_weapon);
      }
    } else {
      Integer l_btEvent = m_inputControls.getEventForKey(l_keyCode);

      // System.out.println("BTEvent="+l_btEvent);

      if (null != l_btEvent) {
        int l_btEventInt = l_btEvent.intValue();

        switch (l_btEventInt) {
          case BattleTrisKeyEvents.MOVE_LEFT:
            m_pc.moveLeft();
            break;
          case BattleTrisKeyEvents.MOVE_RIGHT:
            m_pc.moveRight();
            break;
          case BattleTrisKeyEvents.DROP:
            m_pc.drop();
            break;
          case BattleTrisKeyEvents.ROTATE_CCW:
            // Disallow this until we can fix rotation
            // m_pc.rotateCCW();
            break;
          case BattleTrisKeyEvents.ROTATE_CW:
            m_pc.rotateCW();
            break;
          case BattleTrisKeyEvents.PAUSE:
            // TODO: Put pause back as a synchronized event
            // only when both players have it enabled
            // m_ac.pauseGame();
            break;
        }
      }
    }
  }
Exemplo n.º 28
0
 public void printLocation() {
   txtTranscript.insert(
       "You are at location "
           + row
           + ","
           + col
           + " in terrain: "
           + myMap.terrainTypes.get(Character.toString(myMap.terrain(row, col)))
           + "\n",
       txtTranscript.getText().length());
   if (myMap.terrain(row, col) == '*') {
     Dragon found = new Dragon();
     found.Dragon();
   }
 }
Exemplo n.º 29
0
  // Initialize Board
  public void init() {
    // Create cells and handlers
    cells = new JTextField[gameBoard.boardSize * gameBoard.boardSize + 1];

    // Redraw Panel
    boardPanel.removeAll();
    boardPanel.setLayout(new GridLayout(gameBoard.boardSize, gameBoard.boardSize)); // Set layout

    JTextFilter TextFilter = new JTextFilter(3);
    JTextDocumentListener JTextDocFilter = new JTextDocumentListener();

    for (int i = 1; i <= gameBoard.boardSize * gameBoard.boardSize; i++) {
      cells[i] = new JTextField();

      ((AbstractDocument) cells[i].getDocument()).setDocumentFilter(TextFilter);
      ((AbstractDocument) cells[i].getDocument()).addDocumentListener(JTextDocFilter);
      ((AbstractDocument) cells[i].getDocument()).putProperty("index", i);

      cells[i].setHorizontalAlignment(JTextField.CENTER);
      cells[i].setFont(new Font("Agency FB", Font.BOLD, 24));

      // Add elements to the grid content pane
      boardPanel.add(cells[i]);
    }

    // Initialize booleans
    gameOver = false;

    // Clear Board
    for (int i = 1; i <= (gameBoard.boardSize * gameBoard.boardSize); i++) {
      String ch = Integer.toString(this.gameBoard.cells[i]);
      char chr = '-';
      if (ch.compareTo("0") == 0 || ch == Character.toString(chr)) {
        cells[i].setText("");
      } else {
        cells[i].setText(ch);
        cells[i].setBackground(Color.lightGray);
      }
    }
    // gameBoard.out();

    setVisible(true);
    this.boardPanel.repaint();

    this.gameTimer.reset();
    jButtonSOLVE.setEnabled(true);
  }
Exemplo n.º 30
0
 private boolean isTelephoneZip(String text) {
   boolean maybe = true;
   if (text != null) {
     for (int i = 0; i < text.length(); i++) {
       char c = text.charAt(i);
       int type = Character.getType(c);
       if (type == Character.DECIMAL_DIGIT_NUMBER || c == '-' || c == '(' || c == ')') {
         continue;
       } else {
         maybe = false;
         break;
       }
     }
     return maybe;
   }
   return false;
 }