コード例 #1
0
 private void init() {
   getActionMap().put("startEditing", new StartEditingAction()); // NOI18N
   getActionMap().put("cancel", new CancelEditingAction()); // NOI18N
   addMouseListener(new MouseListener());
   getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "startEditing"); // NOI18N
   getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
       .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); // NOI18N
   putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); // NOI18N
 }
コード例 #2
0
  private JPanel createContentPane() {
    JPanel panel = new JPanel();

    combo1 = new JComboBox<>(numData);
    panel.add(combo1);
    combo2 = new JComboBox<>(dayData);
    combo2.setEditable(true);
    panel.add(combo2);
    panel.setSize(300, 200);

    popupMenu = new JPopupMenu();
    JMenuItem item;
    for (int i = 0; i < dayData.length; i++) {
      item = popupMenu.add(new JMenuItem(dayData[i], mnDayData[i]));
      item.addActionListener(this);
    }
    panel.addMouseListener(new PopupListener(popupMenu));

    JTextField field = new JTextField("CTRL+down for Popup");
    // CTRL-down will show the popup.
    field
        .getInputMap()
        .put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.CTRL_MASK), "OPEN_POPUP");
    field.getActionMap().put("OPEN_POPUP", new PopupHandler());

    panel.add(field);

    return panel;
  }
コード例 #3
0
  public TaskbarPositionTest() {
    super("Use CTRL-down to show a JPopupMenu");
    setContentPane(panel = createContentPane());
    setJMenuBar(createMenuBar("1 - First Menu", true));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // CTRL-down will show the popup.
    panel
        .getInputMap()
        .put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.CTRL_MASK), "OPEN_POPUP");
    panel.getActionMap().put("OPEN_POPUP", new PopupHandler());

    pack();

    Toolkit toolkit = Toolkit.getDefaultToolkit();
    fullScreenBounds = new Rectangle(new Point(), toolkit.getScreenSize());
    screenBounds = new Rectangle(new Point(), toolkit.getScreenSize());

    // Place the frame near the bottom. This is a pretty wild guess.
    this.setLocation(0, (int) screenBounds.getHeight() - 2 * this.getHeight());

    // Reduce the screen bounds by the insets.
    GraphicsConfiguration gc = this.getGraphicsConfiguration();
    if (gc != null) {
      Insets screenInsets = toolkit.getScreenInsets(gc);
      screenBounds = gc.getBounds();
      screenBounds.width -= (screenInsets.left + screenInsets.right);
      screenBounds.height -= (screenInsets.top + screenInsets.bottom);
      screenBounds.x += screenInsets.left;
      screenBounds.y += screenInsets.top;
    }

    setVisible(true);
  }
コード例 #4
0
 public UndoItem(WindowsMenu menu, ScorePanel p) {
   super("Undo");
   setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK));
   addActionListener(this);
   this.menu = menu;
   this.p = p;
 }
コード例 #5
0
 /**
  * This method updates the input and action maps with new ToggleAction.
  *
  * @param isToggleDynamic
  * @param isToggleLarger
  * @param key
  * @param keyStroke
  */
 private void installToggleAction(
     boolean isToggleDynamic, boolean isToggleLarger, String key, String keyStroke) {
   Action action = new ToggleAction(isToggleDynamic, isToggleLarger);
   KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
   table.getInputMap().put(ks, key);
   table.getActionMap().put(key, action);
 }
コード例 #6
0
 /**
  * This method updates the input and action maps with a new ColumnAction.
  *
  * @param isSelectedColumn
  * @param isAdjust
  * @param key
  * @param keyStroke
  */
 private void installColumnAction(
     boolean isSelectedColumn, boolean isAdjust, String key, String keyStroke) {
   Action action = new ColumnAction(isSelectedColumn, isAdjust);
   KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
   table.getInputMap().put(ks, key);
   table.getActionMap().put(key, action);
 }
コード例 #7
0
ファイル: InterpreterFrame.java プロジェクト: DavePearce/jkit
 public void unbindKey(String keySequence) {
   KeyStroke ks = KeyStroke.getKeyStroke(keySequence);
   if (ks == null) {
     throw new Error("Invalid key sequence \"" + keySequence + "\"");
   }
   textView.getKeymap().removeKeyStrokeBinding(ks);
 }
コード例 #8
0
 // Adds a new keybinding equal to the character provided and the default super key (ctrl/cmd)
 private static void bind(int Character) {
   frame
       .getRootPane()
       .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
       .put(
           KeyStroke.getKeyStroke(Character, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
           "console");
 }
コード例 #9
0
ファイル: InterpreterFrame.java プロジェクト: DavePearce/jkit
 public void bindKeyToCommand(String keySequence, LispExpr cmd) {
   // 	see Java API for info on keySequence format
   KeyStroke ks = KeyStroke.getKeyStroke(keySequence);
   if (ks == null) {
     throw new Error("Invalid key sequence \"" + keySequence + "\"");
   }
   textView.getKeymap().addActionForKeyStroke(ks, new KeyAction(cmd));
 }
コード例 #10
0
ファイル: MenuTools.java プロジェクト: nivit/FidoCadJ
  /**
   * Define the main Circuit menu.
   *
   * @param al the action listener to associate to the menu.
   * @return the menu.
   */
  public JMenu defineCircuitMenu(ActionListener al) {
    JMenu circuitMenu = new JMenu(Globals.messages.getString("Circuit"));
    JMenuItem defineCircuit = new JMenuItem(Globals.messages.getString("Define"));

    defineCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, Globals.shortcutKey));

    circuitMenu.add(defineCircuit);

    JMenuItem updateLibraries = new JMenuItem(Globals.messages.getString("LibraryUpdate"));

    updateLibraries.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, Globals.shortcutKey));

    circuitMenu.add(updateLibraries);
    defineCircuit.addActionListener(al);
    updateLibraries.addActionListener(al);

    return circuitMenu;
  }
コード例 #11
0
ファイル: MenuTools.java プロジェクト: nivit/FidoCadJ
  /**
   * Define the main View menu.
   *
   * @param al the action listener to associate to the menu.
   * @return the menu.
   */
  public JMenu defineViewMenu(ActionListener al) {
    JMenu viewMenu = new JMenu(Globals.messages.getString("View"));
    JMenuItem layerOptions = new JMenuItem(Globals.messages.getString("Layer_opt"));

    layerOptions.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Globals.shortcutKey));

    viewMenu.add(layerOptions);

    layerOptions.addActionListener(al);
    return viewMenu;
  }
コード例 #12
0
    ButtonAction(
        String name,
        String mnemonic,
        String accelerator,
        String image,
        String shortDescription,
        String longDescription,
        int actionId) {
      if (name != null) {
        putValue(Action.NAME, bundle.getString(name));
      }

      if (mnemonic != null) {
        String mnemonicString = bundle.getString(mnemonic);
        if (mnemonicString != null && mnemonicString.length() > 0) {
          putValue(Action.MNEMONIC_KEY, new Integer(bundle.getString(mnemonic).charAt(0)));
        }
      }

      if (accelerator != null) {
        String acceleratorString = bundle.getString(accelerator);
        if (accelerator != null && acceleratorString.length() > 0) {
          putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(acceleratorString));
        }
      }

      if (image != null) {
        String imageName = bundle.getString(image);
        if (imageName != null && imageName.length() > 0) {
          imageName = "images/" + imageName + SMALL;
          URL url = this.getClass().getResource(imageName);
          if (url != null) {
            putValue(Action.SMALL_ICON, new ImageIcon(url));
          }
        }
      }

      if (shortDescription != null) {
        String shortString = bundle.getString(shortDescription);
        if (shortString != null & shortString.length() > 0) {
          putValue(Action.SHORT_DESCRIPTION, shortString);
        }
      }

      if (longDescription != null) {
        String longString = bundle.getString(longDescription);
        if (longString != null && longString.length() > 0) {
          putValue(Action.LONG_DESCRIPTION, longString);
        }
      }

      putValue("buttonAction", new Integer(actionId));
    }
コード例 #13
0
  // ------------------------------------------------------------------
  // from Java Swing 1.2 Orielly - Robert Eckstein
  // ------------------------------------------------------------------
  protected JTextComponent updateKeymapForWord(JTextComponent textComp) {
    // create a new child keymap
    Keymap map = JTextComponent.addKeymap("NslmMap", textComp.getKeymap());

    // define the keystrokeds to be added
    KeyStroke next = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK, false);
    // add the new mappings used DefaultEditorKit actions
    map.addActionForKeyStroke(next, getAction(DefaultEditorKit.nextWordAction));

    KeyStroke prev = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(prev, getAction(DefaultEditorKit.previousWordAction));

    KeyStroke selNext =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(selNext, getAction(DefaultEditorKit.selectionNextWordAction));
    KeyStroke selPrev =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_LEFT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(selPrev, getAction(DefaultEditorKit.selectionPreviousWordAction));

    KeyStroke find = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(find, getAction("find"));

    KeyStroke findAgain = KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(findAgain, getAction("findAgain"));

    // set the keymap for the text component
    textComp.setKeymap(map);
    return (textComp);
  } // end updateKeymapForWord
コード例 #14
0
  // Private helper methods
  private void createMenuBar() {
    menuBar = new JMenuBar();
    fileMenu = new JMenu("File");

    miOpen = new JMenuItem("Open...");
    miOpen.setAccelerator(
        KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Event.META_MASK));
    fileMenu.add(miOpen).setEnabled(false);
    miOpen.addActionListener(new MenuActionListener());

    miSave = new JMenuItem("Save Selected...");
    miSave.setAccelerator(
        KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.META_MASK));
    fileMenu.add(miSave).setEnabled(false);
    miSave.addActionListener(new MenuActionListener());

    miSaveAll = new JMenuItem("Save All...");
    fileMenu.add(miSaveAll).setEnabled(false);
    miSaveAll.addActionListener(new MenuActionListener());

    menuBar.add(fileMenu);
  }
コード例 #15
0
  public TextAreaCellEditor() {
    super();
    scroll = new JScrollPane(this);
    scroll.setBorder(BorderFactory.createEmptyBorder());
    // scroll.setViewportBorder(BorderFactory.createEmptyBorder());

    setLineWrap(true);
    setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));

    KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK);
    getInputMap(JComponent.WHEN_FOCUSED).put(enter, KEY);
    getActionMap()
        .put(
            KEY,
            new AbstractAction() {
              @Override
              public void actionPerformed(ActionEvent e) {
                stopCellEditing();
              }
            });
  }
コード例 #16
0
  static {
    // Set up the input map that will be shared by all instances

    inputMap.put(KeyStroke.getKeyStroke("BACK_SPACE"), "setNullDate");
    inputMap.put(KeyStroke.getKeyStroke("DELETE"), "setNullDate");
    inputMap.put(KeyStroke.getKeyStroke("shift LEFT"), "yearBackward");
    inputMap.put(KeyStroke.getKeyStroke("shift RIGHT"), "yearForward");
    inputMap.put(KeyStroke.getKeyStroke("LEFT"), "monthBackward");
    inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "monthForward");

    actionMap.put("setNullDate", setNullDate);
    actionMap.put("yearBackward", yearBackward);
    actionMap.put("yearForward", yearForward);
    actionMap.put("monthBackward", monthBackward);
    actionMap.put("monthForward", monthForward);
  }
コード例 #17
0
  public TextFieldDemo() {
    initComponents();

    InputStream in = getClass().getResourceAsStream("content.txt");
    try {
      textArea.read(new InputStreamReader(in), null);
    } catch (IOException e) {
      e.printStackTrace();
    }

    hilit = new DefaultHighlighter();
    painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
    textArea.setHighlighter(hilit);

    entryBg = entry.getBackground();
    entry.getDocument().addDocumentListener(this);

    InputMap im = entry.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap am = entry.getActionMap();
    im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
    am.put(CANCEL_ACTION, new CancelAction());
  }
コード例 #18
0
  /**
   * This method is called when the focused component (and none of its ancestors) want the key
   * event. This will look up the keystroke to see if any chidren (or subchildren) of the specified
   * container want a crack at the event. If one of them wants it, then it will "DO-THE-RIGHT-THING"
   */
  public boolean fireKeyboardAction(KeyEvent e, boolean pressed, Container topAncestor) {

    if (e.isConsumed()) {
      System.out.println("Acquired pre-used event!");
      Thread.dumpStack();
    }

    // There may be two keystrokes associated with a low-level key event;
    // in this case a keystroke made of an extended key code has a priority.
    KeyStroke ks;
    KeyStroke ksE = null;

    if (e.getID() == KeyEvent.KEY_TYPED) {
      ks = KeyStroke.getKeyStroke(e.getKeyChar());
    } else {
      if (e.getKeyCode() != e.getExtendedKeyCode()) {
        ksE = KeyStroke.getKeyStroke(e.getExtendedKeyCode(), e.getModifiers(), !pressed);
      }
      ks = KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed);
    }

    Hashtable keyMap = containerMap.get(topAncestor);
    if (keyMap != null) { // this container isn't registered, so bail

      Object tmp = null;
      // extended code has priority
      if (ksE != null) {
        tmp = keyMap.get(ksE);
        if (tmp != null) {
          ks = ksE;
        }
      }
      if (tmp == null) {
        tmp = keyMap.get(ks);
      }

      if (tmp == null) {
        // don't do anything
      } else if (tmp instanceof JComponent) {
        JComponent c = (JComponent) tmp;
        if (c.isShowing() && c.isEnabled()) { // only give it out if enabled and visible
          fireBinding(c, ks, e, pressed);
        }
      } else if (tmp instanceof Vector) { // more than one comp registered for this
        Vector v = (Vector) tmp;
        // There is no well defined order for WHEN_IN_FOCUSED_WINDOW
        // bindings, but we give precedence to those bindings just
        // added. This is done so that JMenus WHEN_IN_FOCUSED_WINDOW
        // bindings are accessed before those of the JRootPane (they
        // both have a WHEN_IN_FOCUSED_WINDOW binding for enter).
        for (int counter = v.size() - 1; counter >= 0; counter--) {
          JComponent c = (JComponent) v.elementAt(counter);
          // System.out.println("Trying collision: " + c + " vector = "+ v.size());
          if (c.isShowing() && c.isEnabled()) { // don't want to give these out
            fireBinding(c, ks, e, pressed);
            if (e.isConsumed()) return true;
          }
        }
      } else {
        System.out.println("Unexpected condition in fireKeyboardAction " + tmp);
        // This means that tmp wasn't null, a JComponent, or a Vector.  What is it?
        Thread.dumpStack();
      }
    }

    if (e.isConsumed()) {
      return true;
    }
    // if no one else handled it, then give the menus a crack
    // The're handled differently.  The key is to let any JMenuBars
    // process the event
    if (keyMap != null) {
      Vector v = (Vector) keyMap.get(JMenuBar.class);
      if (v != null) {
        Enumeration iter = v.elements();
        while (iter.hasMoreElements()) {
          JMenuBar mb = (JMenuBar) iter.nextElement();
          if (mb.isShowing() && mb.isEnabled()) { // don't want to give these out
            boolean extended = (ksE != null) && !ksE.equals(ks);
            if (extended) {
              fireBinding(mb, ksE, e, pressed);
            }
            if (!extended || !e.isConsumed()) {
              fireBinding(mb, ks, e, pressed);
            }
            if (e.isConsumed()) {
              return true;
            }
          }
        }
      }
    }

    return e.isConsumed();
  }
コード例 #19
0
ファイル: EditFrame.java プロジェクト: BrotherPhil/ROPE
  EditFrame(RopeFrame parent) {
    super(parent);

    // Implement a smarter way to set the initial frame position and size
    setLocation(0, 0);
    setSize(670, 705);

    try {
      jbInit();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    sourceArea.addCaretListener(this);
    browseButton.addActionListener(this);
    optionsButton.addActionListener(this);
    assembleButton.addActionListener(this);
    saveButton.addActionListener(this);

    messageList.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent event) {
            highlightError(messageList.locationToIndex(event.getPoint()));
          }
        });

    undoMgr = new CompoundUndoManager(sourceArea);

    undoAction = undoMgr.getUndoAction();
    redoAction = undoMgr.getRedoAction();

    undoMgr.updateUndoAction = new UpdateUndoAction();
    undoMgr.updateRedoAction = new UpdateRedoAction();

    document = sourceArea.getDocument();

    ActionMap am = sourceArea.getActionMap();
    InputMap im = sourceArea.getInputMap(JComponent.WHEN_FOCUSED);

    // Remove automatic key bindings because we want them controlled by menu items
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, RopeHelper.modifierMaks), "none");
    im.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, RopeHelper.modifierMaks + InputEvent.SHIFT_MASK),
        "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, RopeHelper.modifierMaks), "none");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_L, RopeHelper.modifierMaks), "none");

    // Set custom binding action for tab key
    String action = "tabKeyAction";
    im.put(KeyStroke.getKeyStroke("TAB"), action);
    am.put(
        action,
        new AbstractAction() {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int endLine = sourceArea.getLineEndOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos >= 39 && linePos < 79) {
                caretPos = startLine + linePos + 10 - ((linePos + 1) % 10);
              } else if (linePos >= 20 && linePos <= 39) {
                caretPos = startLine + 39;
              } else if (linePos >= 15 && linePos <= 19) {
                caretPos = startLine + 20;
              } else if (linePos >= 5 && linePos <= 14) {
                caretPos = startLine + 15;
              } else {
                caretPos = startLine + 5;
              }

              // If the line is shorter than the new position fo the caret add enough spaces...
              if (caretPos > endLine) {
                StringBuilder str = new StringBuilder();
                int size = caretPos - endLine;
                while (size-- >= 0) {
                  str.append(' ');
                }
                document.insertString(endLine - 1, str.toString(), null);
              }

              sourceArea.setCaretPosition(caretPos);
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    // Set custom binding action for return/enter key
    String actionKey = "backspaceKeyAction";
    im.put(KeyStroke.getKeyStroke("BACK_SPACE"), actionKey);
    am.put(
        actionKey,
        new AbstractAction()
        // How can I get the original action?
        {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int endLine = sourceArea.getLineEndOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos == 15) {
                int endPos = 5;
                int charPos = linePos;
                for (; charPos > endPos; charPos--) {
                  char ch = sourceArea.getText().charAt((startLine + charPos) - 1);
                  if (!Character.isWhitespace(ch)) {
                    break;
                  }
                }

                sourceArea.setCaretPosition(startLine + charPos);
              } else {
                int startSel = sourceArea.getSelectionStart();
                int endSel = sourceArea.getSelectionEnd();
                if (startSel == endSel) {
                  startSel = caretPos - 1;
                  endSel = caretPos;
                }

                StringBuilder sb = new StringBuilder(sourceArea.getText());
                sb.replace(startSel, endSel, "");
                sourceArea.setText(sb.toString());
                sourceArea.setCaretPosition(startSel);
              }
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    // Set custom binding action for return/enter key
    action = "enterKeyAction";
    im.put(KeyStroke.getKeyStroke("ENTER"), action);
    am.put(
        action,
        new AbstractAction() {
          private static final long serialVersionUID = 1L;

          @Override
          public void actionPerformed(ActionEvent e) {
            try {
              int caretPos = sourceArea.getCaretPosition();
              int lineNum = sourceArea.getLineOfOffset(caretPos);
              int startLine = sourceArea.getLineStartOffset(lineNum);
              int linePos = caretPos - startLine;

              if (linePos >= 5) {
                document.insertString(caretPos, "\n     ", null);
              } else {
                document.insertString(caretPos, "\n", null);
              }
            } catch (BadLocationException ex) {
              ex.printStackTrace();
            }
          }
        });

    document.addDocumentListener(
        new DocumentListener() {
          @Override
          public void insertUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }

          @Override
          public void removeUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }

          @Override
          public void changedUpdate(DocumentEvent e) {
            setSourceChanged(true);
          }
        });
  }
コード例 #20
0
  /**
   * Constructor, initialises the editor components.
   *
   * @param initialText The initial text to be displayed in the editor.
   * @param handler The GUI handler for this component.
   */
  public GUITextModelEditor(String initialText, GUIMultiModelHandler handler) {
    this.handler = handler;
    setLayout(new BorderLayout());

    // Setup the editor with it's custom editor kits. To switch between
    // editor kits just use setContentType() for the desired content type.
    editor =
        new JEditorPane() {
          @Override
          public String getToolTipText(MouseEvent event) {
            if (parseError != null) {
              try {
                int offset = this.viewToModel(new Point(event.getX(), event.getY()));

                int startOffset =
                    computeDocumentOffset(parseError.getBeginLine(), parseError.getBeginColumn());
                int endOffset =
                    computeDocumentOffset(parseError.getEndLine(), parseError.getEndColumn()) + 1;

                if (offset >= startOffset && offset <= endOffset) return parseError.getMessage();
              } catch (BadLocationException e) {
              }
            }

            return null;
          }
        };

    editor.setToolTipText("dummy");

    editor.setEditorKitForContentType("text/prism", new PrismEditorKit(handler));
    editor.setEditorKitForContentType("text/pepa", new PepaEditorKit(handler));
    // The default editor kit is the Prism one.
    editor.setContentType("text/prism");
    editor.setBackground(Color.white);
    editor.addMouseListener(editorMouseListener);
    editor.setEditable(true);
    editor.setText(initialText);
    editor.getDocument().addDocumentListener(this);
    editor.addCaretListener(
        new CaretListener() {
          public void caretUpdate(CaretEvent e) {
            GUITextModelEditor.this
                .handler
                .getGUIPlugin()
                .getSelectionChangeHandler()
                .notifyListeners(new GUIEvent(1));
          }
        });
    editor.getDocument().putProperty(PlainDocument.tabSizeAttribute, new Integer(4));

    editor.addMouseListener(this);
    errorHighlightPainter =
        new DefaultHighlighter.DefaultHighlightPainter(new Color(255, 192, 192));
    undoManager = new GUIUndoManager(GUIPrism.getGUI());
    undoManager.setLimit(200);

    // Setup the scrollpane
    editorScrollPane = new JScrollPane(editor);
    add(editorScrollPane, BorderLayout.CENTER);
    gutter = new GUITextModelEditorGutter(editor);

    // Get the 'show line numbers' setting to determine
    // if the line numbers should be shown.
    showLineNumbersSetting =
        handler
            .getGUIPlugin()
            .getPrism()
            .getSettings()
            .getBoolean(PrismSettings.MODEL_SHOW_LINE_NUMBERS);
    if (showLineNumbersSetting) {
      editorScrollPane.setRowHeaderView(gutter);
    }

    // Add a Prism settings listener to catch changes made to the
    // 'show line numbers' setting.
    handler
        .getGUIPlugin()
        .getPrism()
        .getSettings()
        .addSettingsListener(
            new PrismSettingsListener() {
              public void notifySettings(PrismSettings settings) {
                // Check if the setting has changed.
                if (settings.getBoolean(PrismSettings.MODEL_SHOW_LINE_NUMBERS)
                    != showLineNumbersSetting) {
                  showLineNumbersSetting = !showLineNumbersSetting;
                  if (showLineNumbersSetting) {
                    editorScrollPane.setRowHeaderView(gutter);
                  } else {
                    editorScrollPane.setRowHeaderView(null);
                  }
                }
              }
            });

    // initialize the actions for the context menu
    initActions();

    // method to initialize the context menu popup
    initContextMenu();

    InputMap inputMap = editor.getInputMap();
    inputMap.clear();

    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_undo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_undo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_redo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_selectall");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_delete");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_cut");
    inputMap.put(
        KeyStroke.getKeyStroke(
            KeyEvent.VK_Z,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
                | java.awt.event.InputEvent.SHIFT_MASK),
        "prism_redo");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_paste");
    inputMap.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
        "prism_jumperr");

    ActionMap actionMap = editor.getActionMap();
    actionMap.put("prism_undo", GUIPrism.getClipboardPlugin().getUndoAction());
    actionMap.put("prism_redo", GUIPrism.getClipboardPlugin().getRedoAction());
    actionMap.put("prism_selectall", GUIPrism.getClipboardPlugin().getSelectAllAction());
    actionMap.put("prism_cut", GUIPrism.getClipboardPlugin().getCutAction());
    actionMap.put("prism_copy", GUIPrism.getClipboardPlugin().getCopyAction());
    actionMap.put("prism_paste", GUIPrism.getClipboardPlugin().getPasteAction());
    actionMap.put("prism_delete", GUIPrism.getClipboardPlugin().getDeleteAction());
    actionMap.put("prism_jumperr", actionJumpToError);

    // Attempt to programmatically allow all accelerators
    /*ArrayList plugins = ((GUIMultiModel)handler.getGUIPlugin()).getGUI().getPlugins();
    Iterator it = plugins.iterator();

    while (it.hasNext())
    {
    	GUIPlugin plugin = ((GUIPlugin)it.next());
    	System.out.println(plugin.getName());
    	JMenu firstMenu = plugin.getMenu();

    	Stack<MenuElement> menuStack = new Stack<MenuElement>();

    	menuStack.add(firstMenu);

    	while (!menuStack.empty())
    	{
    		MenuElement menu = menuStack.pop();

    		if (menu instanceof JMenuItem)
    		{
    			JMenuItem menuItem = ((JMenuItem)menu);

    			KeyStroke accelerator = menuItem.getAccelerator();
    			Action action = menuItem.getAction();

    			if (action != null && accelerator != null && menuItem.getText() != null)
    			{
    				System.out.println(menuItem.getText() + " " + menuItem.getName());
    				inputMap.put(accelerator, "prism_" + menuItem.getText());
    				actionMap.put("prism_" + menuItem.getText(), action);
    			}
    		}

    		MenuElement[] subelements = menu.getSubElements();

    		if (subelements != null)
    		{
    			for (int i = 0; i < subelements.length; i++)
    				menuStack.push(subelements[i]);
    		}
    	}
    }*/

    editor.getDocument().addUndoableEditListener(undoManager);
    editor
        .getDocument()
        .addUndoableEditListener(
            new UndoableEditListener() {
              public void undoableEditHappened(UndoableEditEvent e) {
                System.out.println("adding undo edit");
              }
            });
  }
コード例 #21
0
  /** Helper method to initialize the actions used for the buttons. */
  private void initActions() {

    /*actionUndo = new AbstractAction() {
    	public void actionPerformed(ActionEvent ae) {
    		try {
    			// do redo
    			undoManager.undo();

    			// notify undo manager/toolbar of change
    			GUIPrism.getGUI().notifyEventListeners(
    					new GUIClipboardEvent(GUIClipboardEvent.UNDOMANAGER_CHANGE,
    							GUIPrism.getGUI().getFocussedPlugin().getFocussedComponent()));
    		} catch (CannotUndoException ex) {
    			//GUIPrism.getGUI().getMultiLogger().logMessage(PrismLogLevel.PRISM_ERROR, ex.getMessage());
    		}
    	}
    };
    actionUndo.putValue(Action.LONG_DESCRIPTION, "Undo the most recent action.");
    actionUndo.putValue(Action.NAME, "Undo");
    actionUndo.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("smallUndo.png"));

    actionRedo = new AbstractAction() {
    	public void actionPerformed(ActionEvent ae) {
    		try {
    			// do redo
    			undoManager.redo();

    			// notify undo manager/toolbar of change
    			GUIPrism.getGUI().notifyEventListeners(
    					new GUIClipboardEvent(GUIClipboardEvent.UNDOMANAGER_CHANGE,
    							GUIPrism.getGUI().getFocussedPlugin().getFocussedComponent()));
    		} catch (CannotRedoException ex) {
    			//GUIPrism.getGUI().getMultiLogger().logMessage(PrismLogLevel.PRISM_ERROR, ex.getMessage());
    		}
    	}
    };


    actionRedo.putValue(Action.LONG_DESCRIPTION, "Redos the most recent undo");
    actionRedo.putValue(Action.NAME, "Redo");
    actionRedo.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("smallRedo.png"));
    */
    actionJumpToError =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            jumpToError();
          }
        };

    actionJumpToError.putValue(Action.NAME, "Jump to error");
    actionJumpToError.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("tinyError.png"));
    actionJumpToError.putValue(
        Action.ACCELERATOR_KEY,
        KeyStroke.getKeyStroke(
            KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    // search and replace action
    actionSearch =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            /*
                		// System.out.println("search button pressed");
                		if (GUIMultiModelHandler.isDoingSearch()) {

            } else {
            	try {
            		GUIMultiModelHandler.setDoingSearch(true);
            		FindReplaceForm.launch(GUIPrism.getGUI().getMultiModel());
            	} catch (PluginNotFoundException pnfe) {
            		GUIPrism.getGUI().getMultiLogger().logMessage(prism.log.PrismLogLevel.PRISM_ERROR,
            				pnfe.getMessage());
            	}
            }
            */
          }
        };
    actionSearch.putValue(Action.LONG_DESCRIPTION, "Opens a find and replace dialog.");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    actionSearch.putValue(Action.NAME, "Find/Replace");
    // actionSearch.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R,
    // Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    insertDTMC =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "dtmc", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertDTMC.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Discrete-Time Markov Chain\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertDTMC.putValue(Action.NAME, "Probabilistic (DTMC)");

    insertCTMC =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "ctmc", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertCTMC.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Continous-Time Markov Chain\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertCTMC.putValue(Action.NAME, "Stochastic (CTMC)");

    insertMDP =
        new AbstractAction() {
          public void actionPerformed(ActionEvent ae) {
            int caretPosition = editor.getCaretPosition();
            try {
              editor.getDocument().insertString(caretPosition, "mdp", new SimpleAttributeSet());
            } catch (BadLocationException ble) {
              // todo log?
            }
          }
        };

    insertMDP.putValue(
        Action.LONG_DESCRIPTION, "Marks this model as a \"Markov Decision Process\"");
    // actionSearch.putValue(Action.SMALL_ICON, GUIPrism.getIconFromImage("find.png"));
    insertMDP.putValue(Action.NAME, "Non-deterministic (MDP)");
  }
コード例 #22
0
  /**
   * Set up the calendar panel with the basic layout and components. These are not date specific.
   */
  private void createCalendarComponents() {
    // The date panel will hold the calendar and/or the time spinner

    JPanel datePanel = new JPanel(new BorderLayout(2, 2));

    // Create the calendar if we are displaying a calendar

    if ((selectedComponents & DISPLAY_DATE) > 0) {
      formatMonth = new SimpleDateFormat("MMM", locale);
      formatWeekDay = new SimpleDateFormat("EEE", locale);

      // Set up the shared keyboard bindings

      setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, inputMap);
      setActionMap(actionMap);

      // Set up the decrement buttons

      yearDecrButton =
          new JButton(
              new ButtonAction(
                  "YearDecrButton",
                  "YearDecrButtonMnemonic",
                  "YearDecrButtonAccelerator",
                  "YearDecrButtonImage",
                  "YearDecrButtonShort",
                  "YearDecrButtonLong",
                  YEAR_DECR_BUTTON));
      monthDecrButton =
          new JButton(
              new ButtonAction(
                  "MonthDecrButton",
                  "MonthDecrButtonMnemonic",
                  "MonthDecrButtonAccelerator",
                  "MonthDecrButtonImage",
                  "MonthDecrButtonShort",
                  "MonthDecrButtonLong",
                  MONTH_DECR_BUTTON));
      JPanel decrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
      decrPanel.add(yearDecrButton);
      decrPanel.add(monthDecrButton);

      // Set up the month/year label

      monthYearLabel = new JLabel();
      monthYearLabel.setHorizontalAlignment(JLabel.CENTER);

      // Set up the increment buttons

      monthIncrButton =
          new JButton(
              new ButtonAction(
                  "MonthIncrButton",
                  "MonthIncrButtonMnemonic",
                  "MonthIncrButtonAccelerator",
                  "MonthIncrButtonImage",
                  "MonthIncrButtonShort",
                  "MonthIncrButtonLong",
                  MONTH_INCR_BUTTON));
      yearIncrButton =
          new JButton(
              new ButtonAction(
                  "YearIncrButton",
                  "YearIncrButtonMnemonic",
                  "YearIncrButtonAccelerator",
                  "YearIncrButtonImage",
                  "YearIncrButtonShort",
                  "YearIncrButtonLong",
                  YEAR_INCR_BUTTON));
      JPanel incrPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
      incrPanel.add(monthIncrButton);
      incrPanel.add(yearIncrButton);

      // Put them all together

      JPanel monthYearNavigator = new JPanel(new BorderLayout(2, 2));
      monthYearNavigator.add(decrPanel, BorderLayout.WEST);
      monthYearNavigator.add(monthYearLabel);
      monthYearNavigator.add(incrPanel, BorderLayout.EAST);

      // Set up the day panel

      JPanel dayPanel = new JPanel(new GridLayout(7, 7));
      int firstDay = displayCalendar.getFirstDayOfWeek();

      // Get the week day labels. The following technique is used so
      // that we can start the calendar on the right day of the week and
      // we can get the week day labels properly localized

      Calendar temp = Calendar.getInstance(locale);
      temp.set(2000, Calendar.MARCH, 15);
      while (temp.get(Calendar.DAY_OF_WEEK) != firstDay) {
        temp.add(Calendar.DATE, 1);
      }
      dayOfWeekLabels = new JLabel[7];
      for (int i = 0; i < 7; i++) {
        Date date = temp.getTime();
        String dayOfWeek = formatWeekDay.format(date);
        dayOfWeekLabels[i] = new JLabel(dayOfWeek);
        dayOfWeekLabels[i].setHorizontalAlignment(JLabel.CENTER);
        dayPanel.add(dayOfWeekLabels[i]);
        temp.add(Calendar.DATE, 1);
      }

      // Add all the day buttons

      dayButtons = new JToggleButton[6][7];
      dayGroup = new ButtonGroup();
      DayListener dayListener = new DayListener();
      for (int row = 0; row < 6; row++) {
        for (int day = 0; day < 7; day++) {
          dayButtons[row][day] = new JToggleButton();
          dayButtons[row][day].addItemListener(dayListener);
          dayPanel.add(dayButtons[row][day]);
          dayGroup.add(dayButtons[row][day]);
        }
      }

      // We add this special button to the button group, so we have a
      // way of unselecting all the visible buttons

      offScreenButton = new JToggleButton("X");
      dayGroup.add(offScreenButton);

      // Combine the navigators and days

      datePanel.add(monthYearNavigator, BorderLayout.NORTH);
      datePanel.add(dayPanel);
    }

    // Create the time spinner field if we are displaying the time

    if ((selectedComponents & DISPLAY_TIME) > 0) {

      // Create the time component

      spinnerDateModel = new SpinnerDateModel();
      spinnerDateModel.addChangeListener(new TimeListener());
      spinner = new JSpinner(spinnerDateModel);

      JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(spinner, timePattern);
      dateEditor.getTextField().setEditable(false);
      dateEditor.getTextField().setHorizontalAlignment(JTextField.CENTER);
      spinner.setEditor(dateEditor);

      // Set the input/action maps for the spinner. (Only BACK_SPACE
      // seems to work!)

      InputMap sim = new InputMap();
      sim.put(KeyStroke.getKeyStroke("BACK_SPACE"), "setNullDate");
      sim.put(KeyStroke.getKeyStroke("DELETE"), "setNullDate");
      sim.setParent(spinner.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));

      ActionMap sam = new ActionMap();
      sam.put(
          "setNullDate",
          new AbstractAction("setNullDate") {
            public void actionPerformed(ActionEvent e) {
              JCalendar.this.setDate(null);
            }
          });
      sam.setParent(spinner.getActionMap());

      spinner.setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, sim);
      spinner.setActionMap(sam);

      // Create a special panel for the time display

      JPanel timePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 2, 2));
      timePanel.add(spinner);

      // Now add it to the bottom

      datePanel.add(timePanel, BorderLayout.SOUTH);
    }

    setLayout(new BorderLayout(2, 2));
    add(datePanel);

    // Add today's date at the bottom of the calendar/time, if needed

    if (isTodayDisplayed) {
      Object[] args = {new Date()};
      String todaysDate = MessageFormat.format(bundle.getString("Today"), args);
      todaysLabel = new JLabel(todaysDate);
      todaysLabel.setHorizontalAlignment(JLabel.CENTER);

      // Add today's date at the very bottom

      add(todaysLabel, BorderLayout.SOUTH);
    }
  }
コード例 #23
0
  // ------------------------------------------------------------------
  // from Java Swing 1.2 Orielly - Robert Eckstein
  // ------------------------------------------------------------------
  protected JTextComponent updateKeymapForEmacs(JTextComponent textComp) {
    // note: it does not look like a key can do more than one action
    // thus no modes.
    // todo: not all of these are correct. such as ctrlK
    // todo: add saving - ctrlXS

    // create a new child keymap
    Keymap map = JTextComponent.addKeymap("NslmMap", textComp.getKeymap());

    KeyStroke selNext =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_RIGHT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(selNext, getAction(DefaultEditorKit.selectionNextWordAction));

    KeyStroke selPrev =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_LEFT, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(selPrev, getAction(DefaultEditorKit.selectionPreviousWordAction));

    KeyStroke next = KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(next, getAction(DefaultEditorKit.forwardAction));
    KeyStroke prev = KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(prev, getAction(DefaultEditorKit.backwardAction));

    KeyStroke selectionDown = KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(selectionDown, getAction(DefaultEditorKit.downAction));
    KeyStroke selectionUp = KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(selectionUp, getAction(DefaultEditorKit.upAction));

    KeyStroke pageDown = KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(pageDown, getAction(DefaultEditorKit.pageDownAction));

    KeyStroke pageUp = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(pageUp, getAction(DefaultEditorKit.pageUpAction));

    KeyStroke endDoc =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_GREATER, InputEvent.META_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(endDoc, getAction(DefaultEditorKit.endAction));
    KeyStroke beginingDoc =
        KeyStroke.getKeyStroke(
            KeyEvent.VK_LESS, InputEvent.META_MASK | InputEvent.SHIFT_MASK, false);
    map.addActionForKeyStroke(beginingDoc, getAction(DefaultEditorKit.beginAction));

    // the VK_SPACE and VK_W not working as in Emacs - space deleting
    // KeyStroke
    // selectionStart=KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,InputEvent.CTRL_MASK,false);
    // map.addActionForKeyStroke(selectionStart,getAction(DefaultEditorKit.selectionForwardAction));
    // //todo: setCharPosAction
    // this is doing nothing because only one char to can be assigned to cut
    // KeyStroke cut1=KeyStroke.getKeyStroke(KeyEvent.VK_W,InputEvent.CTRL_MASK,false);
    // map.addActionForKeyStroke(cut1,getAction(DefaultEditorKit.cutAction));

    // if we do save as XS, this will have to change
    KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(cut, getAction(DefaultEditorKit.cutAction));

    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(paste, getAction(DefaultEditorKit.pasteAction));

    KeyStroke moveToEndLine = KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(moveToEndLine, getAction(DefaultEditorKit.endLineAction));

    // not emacs like
    KeyStroke selWord = KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(selWord, getAction(DefaultEditorKit.selectWordAction));

    KeyStroke selLine = KeyStroke.getKeyStroke(KeyEvent.VK_K, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(selLine, getAction(DefaultEditorKit.selectLineAction));

    KeyStroke delNext = KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(delNext, getAction(DefaultEditorKit.deleteNextCharAction));

    KeyStroke insertLine = KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(insertLine, getAction(DefaultEditorKit.insertBreakAction));

    KeyStroke searchBackward = KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(searchBackward, getAction("findAgain"));

    KeyStroke searchForward = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK, false);
    map.addActionForKeyStroke(searchForward, getAction("findAgain"));

    // set the keymap for the text component
    textComp.setKeymap(map);
    return (textComp);
  } // end updateKeymapForEmacs
コード例 #24
0
  /**
   * Returns the message to display from the JOptionPane the receiver is providing the look and feel
   * for.
   */
  protected Object getMessage() {
    inputComponent = null;
    if (optionPane != null) {
      if (optionPane.getWantsInput()) {
        /* Create a user component to capture the input. If the
        selectionValues are non null the component and there
        are < 20 values it'll be a combobox, if non null and
        >= 20, it'll be a list, otherwise it'll be a textfield. */
        Object message = optionPane.getMessage();
        Object[] sValues = optionPane.getSelectionValues();
        Object inputValue = optionPane.getInitialSelectionValue();
        JComponent toAdd;

        if (sValues != null) {
          if (sValues.length < 20) {
            JComboBox cBox = new JComboBox();

            cBox.setName("OptionPane.comboBox");
            for (int counter = 0, maxCounter = sValues.length; counter < maxCounter; counter++) {
              cBox.addItem(sValues[counter]);
            }
            if (inputValue != null) {
              cBox.setSelectedItem(inputValue);
            }
            inputComponent = cBox;
            toAdd = cBox;

          } else {
            JList list = new JList(sValues);
            JScrollPane sp = new JScrollPane(list);

            sp.setName("OptionPane.scrollPane");
            list.setName("OptionPane.list");
            list.setVisibleRowCount(10);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            if (inputValue != null) list.setSelectedValue(inputValue, true);
            list.addMouseListener(getHandler());
            toAdd = sp;
            inputComponent = list;
          }

        } else {
          MultiplexingTextField tf = new MultiplexingTextField(20);

          tf.setName("OptionPane.textField");
          tf.setKeyStrokes(new KeyStroke[] {KeyStroke.getKeyStroke("ENTER")});
          if (inputValue != null) {
            String inputString = inputValue.toString();
            tf.setText(inputString);
            tf.setSelectionStart(0);
            tf.setSelectionEnd(inputString.length());
          }
          tf.addActionListener(getHandler());
          toAdd = inputComponent = tf;
        }

        Object[] newMessage;

        if (message == null) {
          newMessage = new Object[1];
          newMessage[0] = toAdd;

        } else {
          newMessage = new Object[2];
          newMessage[0] = message;
          newMessage[1] = toAdd;
        }
        return newMessage;
      }
      return optionPane.getMessage();
    }
    return null;
  }
コード例 #25
0
    public static void makeMenuBar(JFrame frame, final AirspaceBuilderController controller) {
      JMenuBar menuBar = new JMenuBar();
      final JCheckBoxMenuItem resizeNewShapesItem;
      final JCheckBoxMenuItem enableEditItem;

      JMenu menu = new JMenu("File");
      {
        JMenuItem item = new JMenuItem("Open...");
        item.setAccelerator(
            KeyStroke.getKeyStroke(
                KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        item.setActionCommand(OPEN);
        item.addActionListener(controller);
        menu.add(item);

        item = new JMenuItem("Open URL...");
        item.setActionCommand(OPEN_URL);
        item.addActionListener(controller);
        menu.add(item);

        item = new JMenuItem("Save...");
        item.setAccelerator(
            KeyStroke.getKeyStroke(
                KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        item.setActionCommand(SAVE);
        item.addActionListener(controller);
        menu.add(item);

        menu.addSeparator();

        item = new JMenuItem("Load Demo Shapes");
        item.setActionCommand(OPEN_DEMO_AIRSPACES);
        item.addActionListener(controller);
        menu.add(item);
      }
      menuBar.add(menu);

      menu = new JMenu("Shape");
      {
        JMenu subMenu = new JMenu("New");
        for (final AirspaceFactory factory : defaultAirspaceFactories) {
          JMenuItem item = new JMenuItem(factory.toString());
          item.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  controller.createNewEntry(factory);
                }
              });
          subMenu.add(item);
        }
        menu.add(subMenu);

        resizeNewShapesItem = new JCheckBoxMenuItem("Fit new shapes to viewport");
        resizeNewShapesItem.setActionCommand(SIZE_NEW_SHAPES_TO_VIEWPORT);
        resizeNewShapesItem.addActionListener(controller);
        resizeNewShapesItem.setState(controller.isResizeNewShapesToViewport());
        menu.add(resizeNewShapesItem);

        enableEditItem = new JCheckBoxMenuItem("Enable shape editing");
        enableEditItem.setActionCommand(ENABLE_EDIT);
        enableEditItem.addActionListener(controller);
        enableEditItem.setState(controller.isEnableEdit());
        menu.add(enableEditItem);
      }
      menuBar.add(menu);

      menu = new JMenu("Selection");
      {
        JMenuItem item = new JMenuItem("Deselect");
        item.setAccelerator(
            KeyStroke.getKeyStroke(
                KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
        item.setActionCommand(CLEAR_SELECTION);
        item.addActionListener(controller);
        menu.add(item);

        item = new JMenuItem("Delete");
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
        item.setActionCommand(REMOVE_SELECTED);
        item.addActionListener(controller);
        menu.add(item);
      }
      menuBar.add(menu);

      frame.setJMenuBar(menuBar);

      controller.addPropertyChangeListener(
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
              if (SIZE_NEW_SHAPES_TO_VIEWPORT.equals((e.getPropertyName()))) {
                resizeNewShapesItem.setSelected(controller.isResizeNewShapesToViewport());
              } else if (ENABLE_EDIT.equals(e.getPropertyName())) {
                enableEditItem.setSelected(controller.isEnableEdit());
              }
            }
          });
    }
コード例 #26
0
  /** Adds the menu items to the menuber. */
  protected void arrangeMenu() {

    // Build the first menu.
    fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);

    viewMenu = new JMenu("View");
    viewMenu.setMnemonic(KeyEvent.VK_V);
    menuBar.add(viewMenu);

    runMenu = new JMenu("Run");
    runMenu.setMnemonic(KeyEvent.VK_R);
    menuBar.add(runMenu);

    // Build the second menu.
    helpMenu = new JMenu("Help");
    helpMenu.setMnemonic(KeyEvent.VK_H);
    menuBar.add(helpMenu);

    programMenuItem = new JMenuItem("Load Program", KeyEvent.VK_O);
    programMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            programMenuItem_actionPerformed();
          }
        });
    fileMenu.add(programMenuItem);

    scriptMenuItem = new JMenuItem("Load Script", KeyEvent.VK_P);
    scriptMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            scriptMenuItem_actionPerformed();
          }
        });
    fileMenu.add(scriptMenuItem);
    fileMenu.addSeparator();

    exitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
    exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.ALT_MASK));
    exitMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            exitMenuItem_actionPerformed();
          }
        });
    fileMenu.add(exitMenuItem);

    viewMenu.addSeparator();

    ButtonGroup animationRadioButtons = new ButtonGroup();

    animationSubMenu = new JMenu("Animate");
    animationSubMenu.setMnemonic(KeyEvent.VK_A);
    viewMenu.add(animationSubMenu);

    partAnimMenuItem = new JRadioButtonMenuItem("Program flow");
    partAnimMenuItem.setMnemonic(KeyEvent.VK_P);
    partAnimMenuItem.setSelected(true);
    partAnimMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            partAnimMenuItem_actionPerformed();
          }
        });
    animationRadioButtons.add(partAnimMenuItem);
    animationSubMenu.add(partAnimMenuItem);

    fullAnimMenuItem = new JRadioButtonMenuItem("Program & data flow");
    fullAnimMenuItem.setMnemonic(KeyEvent.VK_D);
    fullAnimMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            fullAnimMenuItem_actionPerformed();
          }
        });
    animationRadioButtons.add(fullAnimMenuItem);
    animationSubMenu.add(fullAnimMenuItem);

    noAnimMenuItem = new JRadioButtonMenuItem("No Animation");
    noAnimMenuItem.setMnemonic(KeyEvent.VK_N);
    noAnimMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            noAnimMenuItem_actionPerformed();
          }
        });
    animationRadioButtons.add(noAnimMenuItem);
    animationSubMenu.add(noAnimMenuItem);

    ButtonGroup additionalDisplayRadioButtons = new ButtonGroup();

    additionalDisplaySubMenu = new JMenu("View");
    additionalDisplaySubMenu.setMnemonic(KeyEvent.VK_V);
    viewMenu.add(additionalDisplaySubMenu);

    scriptDisplayMenuItem = new JRadioButtonMenuItem("Script");
    scriptDisplayMenuItem.setMnemonic(KeyEvent.VK_S);
    scriptDisplayMenuItem.setSelected(true);
    scriptDisplayMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            scriptDisplayMenuItem_actionPerformed();
          }
        });
    additionalDisplayRadioButtons.add(scriptDisplayMenuItem);
    additionalDisplaySubMenu.add(scriptDisplayMenuItem);

    outputMenuItem = new JRadioButtonMenuItem("Output");
    outputMenuItem.setMnemonic(KeyEvent.VK_O);
    outputMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            outputMenuItem_actionPerformed();
          }
        });
    additionalDisplayRadioButtons.add(outputMenuItem);
    additionalDisplaySubMenu.add(outputMenuItem);

    compareMenuItem = new JRadioButtonMenuItem("Compare");
    compareMenuItem.setMnemonic(KeyEvent.VK_C);
    compareMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            compareMenuItem_actionPerformed();
          }
        });
    additionalDisplayRadioButtons.add(compareMenuItem);
    additionalDisplaySubMenu.add(compareMenuItem);

    noAdditionalDisplayMenuItem = new JRadioButtonMenuItem("Screen");
    noAdditionalDisplayMenuItem.setMnemonic(KeyEvent.VK_N);
    noAdditionalDisplayMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            noAdditionalDisplayMenuItem_actionPerformed();
          }
        });
    additionalDisplayRadioButtons.add(noAdditionalDisplayMenuItem);
    additionalDisplaySubMenu.add(noAdditionalDisplayMenuItem);

    ButtonGroup formatRadioButtons = new ButtonGroup();

    numericFormatSubMenu = new JMenu("Format");
    numericFormatSubMenu.setMnemonic(KeyEvent.VK_F);
    viewMenu.add(numericFormatSubMenu);

    decMenuItem = new JRadioButtonMenuItem("Decimal");
    decMenuItem.setMnemonic(KeyEvent.VK_D);
    decMenuItem.setSelected(true);
    decMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            decMenuItem_actionPerformed();
          }
        });
    formatRadioButtons.add(decMenuItem);
    numericFormatSubMenu.add(decMenuItem);

    hexaMenuItem = new JRadioButtonMenuItem("Hexadecimal");
    hexaMenuItem.setMnemonic(KeyEvent.VK_H);
    hexaMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            hexaMenuItem_actionPerformed();
          }
        });
    formatRadioButtons.add(hexaMenuItem);
    numericFormatSubMenu.add(hexaMenuItem);

    binMenuItem = new JRadioButtonMenuItem("Binary");
    binMenuItem.setMnemonic(KeyEvent.VK_B);
    binMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            binMenuItem_actionPerformed();
          }
        });
    formatRadioButtons.add(binMenuItem);
    numericFormatSubMenu.add(binMenuItem);

    viewMenu.addSeparator();

    singleStepMenuItem = new JMenuItem("Single Step", KeyEvent.VK_S);
    singleStepMenuItem.setAccelerator(KeyStroke.getKeyStroke("F11"));
    singleStepMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            singleStepMenuItem_actionPerformed();
          }
        });
    runMenu.add(singleStepMenuItem);

    ffwdMenuItem = new JMenuItem("Run", KeyEvent.VK_F);
    ffwdMenuItem.setAccelerator(KeyStroke.getKeyStroke("F5"));
    ffwdMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ffwdMenuItem_actionPerformed();
          }
        });
    runMenu.add(ffwdMenuItem);

    stopMenuItem = new JMenuItem("Stop", KeyEvent.VK_T);
    stopMenuItem.setAccelerator(KeyStroke.getKeyStroke("shift F5"));
    stopMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            stopMenuItem_actionPerformed();
          }
        });
    runMenu.add(stopMenuItem);

    rewindMenuItem = new JMenuItem("Reset", KeyEvent.VK_R);
    rewindMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            rewindMenuItem_actionPerformed();
          }
        });
    runMenu.add(rewindMenuItem);

    runMenu.addSeparator();

    breakpointsMenuItem = new JMenuItem("Breakpoints", KeyEvent.VK_B);
    breakpointsMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            breakpointsMenuItem_actionPerformed();
          }
        });
    runMenu.add(breakpointsMenuItem);

    profilerMenuItem = new JMenuItem("Profiler", KeyEvent.VK_I);
    profilerMenuItem.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            showProfiler();
          }
        });
    profilerMenuItem.setEnabled(false);
    runMenu.add(profilerMenuItem);

    usageMenuItem = new JMenuItem("Usage", KeyEvent.VK_U);
    usageMenuItem.setAccelerator(KeyStroke.getKeyStroke("F1"));
    usageMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            usageMenuItem_actionPerformed();
          }
        });
    helpMenu.add(usageMenuItem);

    aboutMenuItem = new JMenuItem("About ...", KeyEvent.VK_A);
    aboutMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            aboutMenuItem_actionPerformed();
          }
        });
    helpMenu.add(aboutMenuItem);
  }
コード例 #27
0
  /** コンポーンントにリスナを登録し接続する。 */
  private void connect() {

    // ColumnHelperでカラム変更関連イベントを設定する
    columnHelper.connect();

    EventAdapter adp = new EventAdapter(view.getKeywordFld(), view.getTable());

    // 自動IME ボタン
    view.getAutoIme()
        .addActionListener(
            new ActionListener() {

              @Override
              public void actionPerformed(ActionEvent e) {
                JCheckBox check = (JCheckBox) e.getSource();
                boolean selected = check.isSelected();
                Project.setBoolean("autoIme", selected);

                if (selected) {
                  // 選択されたらIME ON
                  view.getKeywordFld().addFocusListener(AutoKanjiListener.getInstance());
                } else {
                  // されなければ OFF
                  view.getKeywordFld().addFocusListener(AutoRomanListener.getInstance());
                }
              }
            });

    // Sort アイテム
    view.getSortItem()
        .addItemListener(
            new ItemListener() {

              @Override
              public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                  JComboBox cb = (JComboBox) e.getSource();
                  sortItem = cb.getSelectedIndex();
                  Project.setInt("sortItem", sortItem);
                }
              }
            });

    // カレンダによる日付検索を設定する
    PopupListener pl = new PopupListener(view.getKeywordFld());

    // コンテキストメニューを設定する
    view.getTable().addMouseListener(new ContextListener());

    keyBlocker = new KeyBlocker(view.getKeywordFld());

    // -----------------------------------------------
    // Copy 機能を実装する
    // -----------------------------------------------
    KeyStroke copy =
        KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    copyAction =
        new AbstractAction("コピー") {

          @Override
          public void actionPerformed(ActionEvent ae) {
            copyRow();
          }
        };
    view.getTable().getInputMap().put(copy, "Copy");
    view.getTable().getActionMap().put("Copy", copyAction);

    // minagawa^ 仮保存カルテ取得対応
    view.getTmpKarteButton()
        .addActionListener(
            new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                getTmpKarte();
              }
            });
    // minagawa$

    //        //-----------------------------------------------
    //        // 家族カルテ機能 DnD ^
    //        //-----------------------------------------------
    //        view.getTable().setDragEnabled(true);
    //        view.getTable().setTransferHandler(new PatientSearchTransferHandler());
  }
コード例 #28
0
ファイル: ShowSavedResults.java プロジェクト: pjotrp/EMBOSS
  /**
   * Show the results sent to a batch queue.
   *
   * @param mysettings jemboss settings
   * @param epr pending results
   * @throws JembossSoapException when server connection fails
   */
  public ShowSavedResults(final JembossParams mysettings, final PendingResults epr)
      throws JembossSoapException {
    this("Current Sessions Results");

    Dimension d = new Dimension(270, 100);
    ss.setPreferredSize(d);
    //  ss.setMaximumSize(d);

    JMenu resFileMenu = new JMenu("File");
    resMenu.add(resFileMenu);

    JButton refresh = new JButton(rfii);
    refresh.setMargin(new Insets(0, 1, 0, 1));
    refresh.setToolTipText("Refresh");
    resMenu.add(refresh);
    refresh.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            setCursor(cbusy);
            epr.updateStatus();
            setCursor(cdone);
            datasets.removeAllElements();
            Enumeration enumer = epr.descriptionHash().keys();
            while (enumer.hasMoreElements()) {
              String image = convertToPretty((String) enumer.nextElement());
              datasets.addElement(image);
            }
          }
        });

    JMenuItem resFileMenuExit = new JMenuItem("Close");
    resFileMenuExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));

    resFileMenuExit.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        });
    resFileMenu.add(resFileMenuExit);
    setJMenuBar(resMenu);

    // set up the results list in the gui
    Enumeration enumer = epr.descriptionHash().keys();
    while (enumer.hasMoreElements())
      datasets.addElement(convertToPretty((String) enumer.nextElement()));

    final JList st = new JList(datasets);
    st.setCellRenderer(new TabListCellRenderer());
    st.addListSelectionListener(
        new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;

            JList theList = (JList) e.getSource();
            if (!theList.isSelectionEmpty()) {
              int index = theList.getSelectedIndex();
              String thisdata = convertToOriginal(datasets.elementAt(index));
              aboutRes.setText((String) epr.descriptionHash().get(thisdata));
              aboutRes.setCaretPosition(0);
              aboutRes.setEditable(false);
            }
          }
        });

    st.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              try {
                setCursor(cbusy);
                String project = convertToOriginal(st.getSelectedValue());
                ResultList thisres = new ResultList(mysettings, project, "show_saved_results");
                setCursor(cdone);
                if (thisres.getStatus().equals("0"))
                  new ShowResultSet(thisres.hash(), project, mysettings);
                else
                  JOptionPane.showMessageDialog(
                      null, thisres.getStatusMsg(), "Soap Error", JOptionPane.ERROR_MESSAGE);

              } catch (JembossSoapException eae) {
                AuthPopup ap = new AuthPopup(mysettings, null);
                ap.setBottomPanel();
                ap.setSize(380, 170);
                ap.pack();
                ap.setVisible(true);
              }
            }
          }
        });
    sp.add(st);

    // display retrieves all the files and shows them in a window

    JPanel resButtonPanel = new JPanel();
    JButton showResButton = new JButton("Display");
    showResButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (st.getSelectedValue() != null) {
              try {
                setCursor(cbusy);
                String project = convertToOriginal(st.getSelectedValue());
                ResultList thisres = new ResultList(mysettings, project, "show_saved_results");
                setCursor(cdone);
                if (thisres.getStatus().equals("0"))
                  new ShowResultSet(thisres.hash(), project, mysettings);
                else
                  JOptionPane.showMessageDialog(
                      null, thisres.getStatusMsg(), "Soap Error", JOptionPane.ERROR_MESSAGE);
              } catch (JembossSoapException eae) {
                setCursor(cdone);
                AuthPopup ap = new AuthPopup(mysettings, null);
                ap.setBottomPanel();
                ap.setSize(380, 170);
                ap.pack();
                ap.setVisible(true);
              }
            }
          }
        });

    // delete removes the file on the server and edits the list
    JButton delResButton = new JButton("Delete");
    delResButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            Object sel[] = st.getSelectedValues();
            if (sel != null) {
              String selList = new String("");
              for (int i = 0; i < sel.length; i++) selList = selList.concat(sel[i] + "\n");

              int ok = JOptionPane.OK_OPTION;
              if (sel.length > 1)
                ok =
                    JOptionPane.showConfirmDialog(
                        null,
                        "Delete the following results:\n" + selList,
                        "Confirm Deletion",
                        JOptionPane.YES_NO_OPTION);

              if (ok == JOptionPane.OK_OPTION) {

                try {
                  setCursor(cbusy);
                  selList = convertToOriginal(selList);
                  new ResultList(mysettings, selList, "delete_saved_results");
                  setCursor(cdone);

                  for (int i = 0; i < sel.length; i++) {
                    JembossProcess jp = epr.getResult(convertToOriginal(sel[i]));
                    epr.removeResult(jp);
                    datasets.removeElement(sel[i]); // amend the list
                  }
                  statusField.setText("Deleted " + sel.length + "  result(s)");
                  aboutRes.setText("");
                  st.setSelectedIndex(-1);
                } catch (JembossSoapException eae) {
                  // shouldn't happen
                  AuthPopup ap = new AuthPopup(mysettings, null);
                  ap.setBottomPanel();
                  ap.setSize(380, 170);
                  ap.pack();
                  ap.setVisible(true);
                }
              }
            }
          }
        });
    resButtonPanel.add(delResButton);
    resButtonPanel.add(showResButton);
    resButtonStatus.add(resButtonPanel, BorderLayout.CENTER);
    resButtonStatus.add(statusField, BorderLayout.SOUTH);

    Container c = getContentPane();
    c.add(ss, BorderLayout.WEST);
    c.add(aboutScroll, BorderLayout.CENTER);
    c.add(resButtonStatus, BorderLayout.SOUTH);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    pack();
    setVisible(true);

    // add in automatic updates
    String freq = (String) AdvancedOptions.jobMgr.getSelectedItem();
    int ind = freq.indexOf(" ");
    new ResultsUpdateTimer(Integer.parseInt(freq.substring(0, ind)), datasets, this);
    statusField.setText("Window refresh rate " + freq);
  }
コード例 #29
0
ファイル: ShowSavedResults.java プロジェクト: pjotrp/EMBOSS
  /**
   * Show the saved results on the server.
   *
   * @param mysettings jemboss settings
   * @param frameName title name for frame
   */
  public ShowSavedResults(final JembossParams mysettings, final JFrame f) {

    this("Saved results list" + (Jemboss.withSoap ? " on server" : ""));

    try {
      final ResultList reslist = new ResultList(mysettings);
      JMenu resFileMenu = new JMenu("File");
      resMenu.add(resFileMenu);

      final JCheckBoxMenuItem listByProgram = new JCheckBoxMenuItem("List by program");
      listByProgram.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              listByProgramName();
            }
          });
      resFileMenu.add(listByProgram);

      JCheckBoxMenuItem listByDate = new JCheckBoxMenuItem("List by date", true);
      listByDate.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              listByDateRun(reslist, false);
            }
          });
      resFileMenu.add(listByDate);

      ButtonGroup group = new ButtonGroup();
      group.add(listByProgram);
      group.add(listByDate);

      JButton refresh = new JButton(rfii);
      refresh.setMargin(new Insets(0, 1, 0, 1));
      refresh.setToolTipText("Refresh");
      resMenu.add(refresh);

      refresh.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              try {
                setCursor(cbusy);
                ResultList newlist = new ResultList(mysettings);
                setCursor(cdone);
                if (newlist.getStatus().equals("0")) {
                  reslist.updateRes(newlist.hash());
                  datasets.removeAllElements();

                  StringTokenizer tok = new StringTokenizer((String) reslist.get("list"), "\n");
                  while (tok.hasMoreTokens()) datasets.addElement(convertToPretty(tok.nextToken()));

                  if (listByProgram.isSelected()) listByProgramName();
                  else listByDateRun(reslist, false);
                } else {
                  JOptionPane.showMessageDialog(
                      null, newlist.getStatusMsg(), "Soap Error", JOptionPane.ERROR_MESSAGE);
                }
              } catch (JembossSoapException eae) {
                AuthPopup ap = new AuthPopup(mysettings, f);
                ap.setBottomPanel();
                ap.setSize(380, 170);
                ap.pack();
                ap.setVisible(true);
              }
            }
          });

      resFileMenu.addSeparator();
      JMenuItem resFileMenuExit = new JMenuItem("Close");
      resFileMenuExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));

      resFileMenuExit.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              dispose();
            }
          });
      resFileMenu.add(resFileMenuExit);
      setJMenuBar(resMenu);

      // this is the list of saved results
      listByDateRun(reslist, true);

      final JList st = new JList(datasets);
      st.setCellRenderer(new TabListCellRenderer());

      st.addListSelectionListener(
          new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
              if (e.getValueIsAdjusting()) return;

              JList theList = (JList) e.getSource();
              if (theList.isSelectionEmpty()) {
                System.out.println("Empty selection");
              } else {
                int index = theList.getSelectedIndex();
                String thisdata = convertToOriginal(datasets.elementAt(index));
                aboutRes.setText((String) reslist.get(thisdata));
                aboutRes.setCaretPosition(0);
              }
            }
          });

      st.addMouseListener(
          new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
              if (e.getClickCount() == 2) {
                try {
                  setCursor(cbusy);
                  String project = convertToOriginal(st.getSelectedValue());
                  ResultList thisres = new ResultList(mysettings, project, "show_saved_results");
                  new ShowResultSet(thisres.hash(), project, mysettings);
                  setCursor(cdone);
                } catch (JembossSoapException eae) {
                  AuthPopup ap = new AuthPopup(mysettings, f);
                  ap.setBottomPanel();
                  ap.setSize(380, 170);
                  ap.pack();
                  ap.setVisible(true);
                }
              }
            }
          });
      sp.add(st);

      // display retrieves all files and shows them in a window
      JPanel resButtonPanel = new JPanel();
      JButton showResButton = new JButton("Display");
      showResButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              String sel = convertToOriginal(st.getSelectedValue());
              if (sel != null) {
                try {
                  setCursor(cbusy);
                  ResultList thisres = new ResultList(mysettings, sel, "show_saved_results");
                  if (thisres.hash().size() == 0)
                    JOptionPane.showMessageDialog(
                        sp,
                        "This application launch '" + sel + "' didn't produce any result files.");
                  else new ShowResultSet(thisres.hash(), sel, mysettings);
                  setCursor(cdone);
                } catch (JembossSoapException eae) {
                  AuthPopup ap = new AuthPopup(mysettings, f);
                  ap.setBottomPanel();
                  ap.setSize(380, 170);
                  ap.pack();
                  ap.setVisible(true);
                }
              } else {
                statusField.setText("Nothing selected to be displayed.");
              }
            }
          });

      // add a users note for that project
      JButton addNoteButton = new JButton("Edit Notes");
      addNoteButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              String sel = convertToOriginal(st.getSelectedValue());
              if (sel != null) {
                try {
                  setCursor(cbusy);
                  ResultList thisres =
                      new ResultList(mysettings, sel, "Notes", "show_saved_results");
                  new ShowResultSet(thisres.hash(), sel, mysettings);
                  setCursor(cdone);
                } catch (JembossSoapException eae) {
                  AuthPopup ap = new AuthPopup(mysettings, f);
                  ap.setBottomPanel();
                  ap.setSize(380, 170);
                  ap.pack();
                  ap.setVisible(true);
                }
              } else {
                statusField.setText("Selected a project!");
              }
            }
          });

      // delete removes the file on the server & edits the list
      JButton delResButton = new JButton("Delete");
      delResButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              Object sel[] = st.getSelectedValues();
              if (sel != null) {
                String selList = new String("");
                JTextPane delList = new JTextPane();
                FontMetrics fm = delList.getFontMetrics(delList.getFont());
                int maxWidth = 0;
                for (int i = 0; i < sel.length; i++) {
                  if (i == sel.length - 1) selList = selList.concat((String) sel[i]);
                  else selList = selList.concat(sel[i] + "\n");

                  int width = fm.stringWidth((String) sel[i]);
                  if (width > maxWidth) maxWidth = width;
                }
                int ok = JOptionPane.OK_OPTION;
                if (sel.length > 1) {
                  JScrollPane scrollDel = new JScrollPane(delList);
                  delList.setText(selList);
                  delList.setEditable(false);
                  delList.setCaretPosition(0);

                  Dimension d1 = delList.getPreferredSize();
                  int maxHeight = (int) d1.getHeight() + 5;
                  if (maxHeight > 350) maxHeight = 350;
                  else if (maxHeight < 50) maxHeight = 50;

                  scrollDel.setPreferredSize(new Dimension(maxWidth + 30, maxHeight));

                  ok =
                      JOptionPane.showConfirmDialog(
                          null, scrollDel, "Confirm Deletion", JOptionPane.YES_NO_OPTION);
                }
                if (ok == JOptionPane.OK_OPTION) {
                  try // ask the server to delete these results
                  {
                    setCursor(cbusy);
                    selList = convertToOriginal(selList);
                    new ResultList(mysettings, selList, "delete_saved_results");
                    setCursor(cdone);

                    // amend the list
                    for (int i = 0; i < sel.length; i++) datasets.removeElement(sel[i]);

                    statusField.setText("Deleted " + sel.length + "  result(s)");

                    aboutRes.setText("");
                    st.setSelectedIndex(-1);
                  } catch (JembossSoapException eae) {
                    AuthPopup ap = new AuthPopup(mysettings, f);
                    ap.setBottomPanel();
                    ap.setSize(380, 170);
                    ap.pack();
                    ap.setVisible(true);
                  }
                }
              } else {
                statusField.setText("Nothing selected for deletion.");
              }
            }
          });
      resButtonPanel.add(delResButton);
      resButtonPanel.add(addNoteButton);
      resButtonPanel.add(showResButton);
      resButtonStatus.add(resButtonPanel, BorderLayout.CENTER);
      resButtonStatus.add(statusField, BorderLayout.SOUTH);

      Container c = getContentPane();
      c.add(ss, BorderLayout.WEST);
      c.add(aboutScroll, BorderLayout.CENTER);
      c.add(resButtonStatus, BorderLayout.SOUTH);
      pack();

      setVisible(true);
    } catch (JembossSoapException eae) {
      AuthPopup ap = new AuthPopup(mysettings, f);
      ap.setBottomPanel();
      ap.setSize(380, 170);
      ap.pack();
      ap.setVisible(true);
    }
  }
コード例 #30
0
  /**
   * Adds the menus to the main frame Includes adding ActionListeners to respond to menu commands
   */
  private void addMenus() {
    JMenuBar menuBar = new JMenuBar();
    JMenu gameMenu = new JMenu("Game");
    gameMenu.setMnemonic('G');

    JMenuItem newMenu = new JMenuItem("New Game");
    newMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));

    newMenu.addActionListener(
        new ActionListener() {
          /**
           * Responds to the New menu option
           *
           * @param event The event that selected this menu option
           */
          public void actionPerformed(ActionEvent e) {
            newGame();
            time = 0;
          }
        });

    JMenuItem exitMenu = new JMenuItem("Exit");
    exitMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));

    exitMenu.addActionListener(
        new ActionListener() {
          /**
           * Responds to the exit game option being selected
           *
           * @param event The event that selected this menu option
           */
          public void actionPerformed(ActionEvent event) {
            System.exit(0);
          }
        });
    gameMenu.add(newMenu);
    gameMenu.add(exitMenu);
    menuBar.add(gameMenu);

    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic('H');
    JMenuItem instructionsMenuItem = new JMenuItem("Instructions", 'I');
    instructionsMenuItem.addActionListener(
        new ActionListener() {
          /**
           * Responds to the help option being selected
           *
           * @param event The event that selected this menu option
           */
          public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(
                BearSweeper.this,
                "The objective of the game is to flag Fabear's hiding spots so people know where to avoid.\n"
                    + "If you click on an area that Fabear does not reside, a digit is revealed.\n"
                    + "This digit indicates the number of adjacent squares in which Fabear resides.\n"
                    + "Mark Fabear's hiding spots by right clicking."
                    + "If you click on a spot where Fabear resides, you will wake up and unleash his wrath.\n"
                    + "Note: You only have enough flags for exactly the number of hiding spots!",
                "Help",
                JOptionPane.INFORMATION_MESSAGE);
          }
        });
    instructionsMenuItem.setAccelerator(
        KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
    JMenuItem aboutMenuItem = new JMenuItem("About...", 'A');
    aboutMenuItem.addActionListener(
        new ActionListener() {
          /**
           * Responds to the about option being selected
           *
           * @param event The event that selected this menu option
           */
          public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(
                BearSweeper.this,
                "Fabear is now a well-known hero on Earth.\n"
                    + "He has saved Earth in the Tera sagas, but not without sacrifice.\n"
                    + "Although the Earth is now clean from the dangerous substances left behind by the aliens, Fabear has changed...\n"
                    + "He had come in contact with the substance and is now under the control of the aliens.\n"
                    + "It is your turn to save Fabear, from himself..."
                    + "He is currently sleeping.\n"
                    + "Find Fabear's hiding spots without waking him from his sleep."
                    + "When all of his possible hiding spots are marked with flags,\n"
                    + "special task forces will take over to secure Fabear and take him to a lab "
                    + "where scientists will do everything they can to\n"
                    + "return Fabear to his original self.\n"
                    + "\nBy: Christopher Li and Aaron Lee - 2009-2010",
                "The Adventures of Fabear",
                JOptionPane.INFORMATION_MESSAGE);
          }
        });
    aboutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));

    helpMenu.add(instructionsMenuItem);
    helpMenu.add(aboutMenuItem);
    menuBar.add(helpMenu);
    setJMenuBar(menuBar);
  }