Example #1
0
  public ActionFrame() {
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    buttonPanel = new JPanel();

    // define actions
    Action yellowAction = new ColorAction("Yellow", new ImagIcon("yellow-ball.gif"), Color.YELLOW);
    Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
    Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);

    // add buttons for these actions
    buttonPanel.add(new JButton(yellowAction));
    buttonPanel.add(new JButton(blueAction));
    buttonPanel.add(new JButton(recAction));

    // add panel to frame
    add(buttonPanel);

    // associate the Y, B, and R keys with names
    InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
    imap.put(KeyStroke.getKeyStroke("Ctrl B"), "panel.blue");
    imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");

    // associate the names with actions
    ActionMap amap = buttonPanel.getActionMap();
    amap.put("panel.yellow", yellowAction);
    amap.put("panel.blue", blueAction);
    amap.put("panel.red", redAction);
  }
Example #2
0
  protected void init(boolean modal, JComponent content, String[] options) {
    super.setModal(modal);
    m_modal = modal;
    this.setFocusTraversalPolicy(
        new LayoutFocusTraversalPolicy() {
          private static final long serialVersionUID = 1L;

          protected boolean accept(Component component) {
            return !(component instanceof HTMLView);
          }
        });

    this.content = content;

    this.enableEvents(AWTEvent.WINDOW_EVENT_MASK);

    JPanel contentPane = (JPanel) this.getContentPane();
    contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout());
    contentPane.add(content, BorderLayout.CENTER);
    contentPane.add(jPanelButtonFrame, BorderLayout.SOUTH);
    jPanelButtonFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
    setButtons(options);
    contentPane.setVisible(true);

    /*
      We enable the escape-key for executing the abortCmd. Many thanks to John Zukowski.
         <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip72.html">Java-Tip 72</a>
    */
    KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    contentPane.getActionMap().put("abort", buttonListener);
    contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "abort");
  }
  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);
  }
Example #4
0
  /**
   * Bind a key to an action. The binding will be active while the Workspace window is selected.
   *
   * @param keyDescription A string describing the key as per KeyStroke.getKeyStroke(String). Ex:
   *     "alt A" or "ctrl UP" (for up-arrow). Key names are the <keyName> part in VK_<keyName>
   * @param action Action object to invoke when key is pressed.
   */
  public void bindKey(String keyDescription, Action action) {

    InputMap keyMap = _panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actionMap = _panel.getActionMap();

    keyMap.put(KeyStroke.getKeyStroke(keyDescription), keyDescription);
    actionMap.put(keyDescription, action);
  }
  /**
   * @param wizardModel The overall wizard data model containing the aggregate information of all
   *     components in the wizard
   * @param isExiting True if the exit button should trigger an application shutdown
   * @param wizardParameter An optional parameter that can be referenced during construction
   * @param escapeIsCancel If true, ESC cancels the wizard, if false, it does nothing
   */
  protected AbstractWizard(
      M wizardModel, boolean isExiting, Optional wizardParameter, boolean escapeIsCancel) {

    Preconditions.checkNotNull(wizardModel, "'model' must be present");

    log.debug("Building wizard...");

    this.wizardModel = wizardModel;
    this.exiting = isExiting;
    this.wizardParameter = wizardParameter;

    // Subscribe to events
    ViewEvents.subscribe(this);
    CoreEvents.subscribe(this);

    // Optionally bind the ESC key to a Cancel event (escape to safety)
    if (escapeIsCancel) {
      wizardScreenHolder
          .getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
          .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "quit");
      wizardScreenHolder.getActionMap().put("quit", getCancelAction());
    }

    // TODO Bind the ENTER key to a Next/Finish/Apply event to speed up data entry through keyboard
    // wizardPanel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "next");
    // wizardPanel.getActionMap().put("next", getNextAction(null));

    log.debug("Populating view map and firing initial state view events...");

    // Populate based on the current locale
    populateWizardViewMap(wizardViewMap);

    // Once all the views are created allow events to occur
    for (Map.Entry<String, AbstractWizardPanelView> entry : wizardViewMap.entrySet()) {

      // Ensure the panel is in the correct starting state
      entry.getValue().fireInitialStateViewEvents();
    }

    wizardScreenHolder.setMinimumSize(
        new Dimension(MultiBitUI.WIZARD_MIN_WIDTH, MultiBitUI.WIZARD_MIN_HEIGHT));
    wizardScreenHolder.setPreferredSize(
        new Dimension(MultiBitUI.WIZARD_MIN_WIDTH, MultiBitUI.WIZARD_MIN_HEIGHT));
    wizardScreenHolder.setSize(
        new Dimension(MultiBitUI.WIZARD_MIN_WIDTH, MultiBitUI.WIZARD_MIN_HEIGHT));

    // Show the panel specified by the initial state
    show(wizardModel.getPanelName());
  }
  /** Support cancelling an order's target acquisition process by hitting the escape key. */
  private void doAddKeyListener(JPanel gameDisplay) {
    Action action =
        new AbstractAction("Escape Handler") {
          public void actionPerformed(ActionEvent e) {
            if ((_actionInProgress != null) && (_actionInProgress instanceof TargetAction)) {
              ((TargetAction) _actionInProgress).cancelTargetAcquisition();
            }
          }
        };

    KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
    gameDisplay.getActionMap().put(action.getValue(Action.NAME), action);
    gameDisplay
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(keyStroke, action.getValue(Action.NAME));
  }
Example #7
0
  private Container createReturnPane() {
    // Create return button
    returnButton = new JButton(returnAction);

    // Create text fields
    retISBN = new JTextField(15);
    retCustID = new JTextField(15);

    // Create panel and layout
    JPanel pane = new JPanel();
    pane.setOpaque(false);
    GridBagLayout gb = new GridBagLayout();
    pane.setLayout(gb);
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(1, 5, 1, 5);

    // Fill panel
    c.anchor = GridBagConstraints.EAST;
    addToGridBag(gb, c, pane, new JLabel("ISBN:"), 0, 0, 1, 1);
    addToGridBag(gb, c, pane, new JLabel("Customer ID:"), 0, 1, 1, 1);

    c.anchor = GridBagConstraints.WEST;
    c.fill = GridBagConstraints.HORIZONTAL;
    addToGridBag(gb, c, pane, retISBN, 1, 0, 3, 1);
    addToGridBag(gb, c, pane, retCustID, 1, 1, 3, 1);

    c.fill = GridBagConstraints.NONE;
    addToGridBag(gb, c, pane, returnButton, 4, 0, 1, 3);

    // Set up VK_ENTER triggering the return button in this panel
    InputMap input = pane.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    input.put(getKeyStroke("ENTER"), "returnAction");
    pane.getActionMap().put("returnAction", returnAction);

    return pane;
  }
Example #8
0
  /**
   * @param groupsRoot The original set of groups, which is required as undo information when all
   *     groups are cleared.
   */
  public AutoGroupDialog(
      JabRefFrame jabrefFrame,
      BasePanel basePanel,
      GroupSelector groupSelector,
      GroupTreeNode groupsRoot,
      String defaultField,
      String defaultRemove,
      String defaultDeliminator) {
    super(jabrefFrame, Localization.lang("Automatically create groups"), true);
    frame = jabrefFrame;
    gs = groupSelector;
    panel = basePanel;
    m_groupsRoot = groupsRoot;
    field.setText(defaultField);
    remove.setText(defaultRemove);
    deliminator.setText(defaultDeliminator);
    nd.setSelected(true);
    ActionListener okListener =
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();

            GroupTreeNode autoGroupsRoot =
                new GroupTreeNode(
                    new ExplicitGroup(
                        Localization.lang("Automatically created groups"),
                        GroupHierarchyType.INCLUDING));
            Set<String> hs = null;
            String fieldText = field.getText();
            if (keywords.isSelected()) {
              if (nd.isSelected()) {
                hs =
                    Util.findDeliminatedWordsInField(
                        panel.getDatabase(),
                        field.getText().toLowerCase().trim(),
                        deliminator.getText());
              } else {
                hs =
                    Util.findAllWordsInField(
                        panel.getDatabase(),
                        field.getText().toLowerCase().trim(),
                        remove.getText());
              }
            } else if (authors.isSelected()) {
              List<String> fields = new ArrayList<>(2);
              fields.add("author");
              hs = Util.findAuthorLastNames(panel.getDatabase(), fields);
              fieldText = "author";
            } else if (editors.isSelected()) {
              List<String> fields = new ArrayList<>(2);
              fields.add("editor");
              hs = Util.findAuthorLastNames(panel.getDatabase(), fields);
              fieldText = "editor";
            }

            for (String keyword : hs) {
              KeywordGroup group =
                  new KeywordGroup(
                      keyword, fieldText, keyword, false, false, GroupHierarchyType.INDEPENDENT);
              autoGroupsRoot.add(new GroupTreeNode(group));
            }

            m_groupsRoot.add(autoGroupsRoot);
            NamedCompound ce = new NamedCompound(Localization.lang("Autogenerate groups"));
            UndoableAddOrRemoveGroup undo =
                new UndoableAddOrRemoveGroup(
                    gs, m_groupsRoot, autoGroupsRoot, UndoableAddOrRemoveGroup.ADD_NODE);
            undo.setRevalidate(true);
            ce.addEdit(undo);

            panel.markBaseChanged(); // a change always occurs
            gs.revalidateGroups();
            frame.output(Localization.lang("Created groups."));
            ce.end();
            panel.undoManager.addEdit(ce);
          }
        };
    remove.addActionListener(okListener);
    field.addActionListener(okListener);
    field.addCaretListener(this);
    AbstractAction cancelAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    JButton cancel = new JButton(Localization.lang("Cancel"));
    cancel.addActionListener(cancelAction);
    ok.addActionListener(okListener);
    // Key bindings:
    JPanel main = new JPanel();
    ActionMap am = main.getActionMap();
    InputMap im = main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(frame.prefs().getKey(KeyBinds.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);

    ButtonGroup bg = new ButtonGroup();
    bg.add(keywords);
    bg.add(authors);
    bg.add(editors);
    keywords.setSelected(true);

    FormBuilder b = FormBuilder.create();
    b.layout(
        new FormLayout(
            "left:20dlu, 4dlu, left:pref, 4dlu, fill:60dlu",
            "p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p"));
    b.add(keywords).xyw(1, 1, 5);
    b.add(Localization.lang("Field to group by") + ":").xy(3, 3);
    b.add(field).xy(5, 3);
    b.add(Localization.lang("Characters to ignore") + ":").xy(3, 5);
    b.add(remove).xy(5, 5);
    b.add(nd).xy(3, 7);
    b.add(deliminator).xy(5, 7);
    b.add(authors).xyw(1, 9, 5);
    b.add(editors).xyw(1, 11, 5);
    b.build();
    b.border(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    JPanel opt = new JPanel();
    ButtonBarBuilder bb = new ButtonBarBuilder(opt);
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();

    main.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    opt.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    getContentPane().add(main, BorderLayout.CENTER);
    getContentPane().add(b.getPanel(), BorderLayout.CENTER);
    getContentPane().add(opt, BorderLayout.SOUTH);

    updateComponents();
    pack();
    PositionWindow.placeDialog(this, frame);
  }
  private void initGui() {
    Container pane = getContentPane();
    pane.setLayout(new BorderLayout());

    biblatexMode = Globals.prefs.getBoolean("biblatexMode");

    JPanel main = new JPanel(), buttons = new JPanel(), right = new JPanel();
    main.setLayout(new BorderLayout());
    right.setLayout(new GridLayout(biblatexMode ? 2 : 1, 2));

    java.util.List<String> entryTypes = new ArrayList<String>();
    for (String s : BibtexEntryType.ALL_TYPES.keySet()) {
      entryTypes.add(s);
    }

    typeComp = new EntryTypeList(entryTypes);
    typeComp.addListSelectionListener(this);
    typeComp.addAdditionActionListener(this);
    typeComp.addDefaultActionListener(new DefaultListener());
    typeComp.setListSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // typeComp.setEnabled(false);
    reqComp =
        new FieldSetComponent(
            Globals.lang("Required fields"), new ArrayList<String>(), preset, true, true);
    reqComp.setEnabled(false);
    reqComp.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ListDataListener dataListener = new DataListener();
    reqComp.addListDataListener(dataListener);
    optComp =
        new FieldSetComponent(
            Globals.lang("Optional fields"), new ArrayList<String>(), preset, true, true);
    optComp.setEnabled(false);
    optComp.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    optComp.addListDataListener(dataListener);
    right.add(reqComp);
    right.add(optComp);

    if (biblatexMode) {
      optComp2 =
          new FieldSetComponent(
              Globals.lang("Optional fields") + " 2", new ArrayList<String>(), preset, true, true);
      optComp2.setEnabled(false);
      optComp2.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
      optComp2.addListDataListener(dataListener);
      right.add(new JPanel());
      right.add(optComp2);
    }

    // right.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),
    // Globals.lang("Fields")));
    right.setBorder(BorderFactory.createEtchedBorder());
    ok = new JButton("Ok");
    cancel = new JButton(Globals.lang("Cancel"));
    apply = new JButton(Globals.lang("Apply"));
    ok.addActionListener(this);
    apply.addActionListener(this);
    cancel.addActionListener(this);
    ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
    buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(apply);
    bb.addButton(cancel);
    bb.addGlue();

    AbstractAction closeAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    ActionMap am = main.getActionMap();
    InputMap im = main.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.prefs.getKey("Close dialog"), "close");
    am.put("close", closeAction);

    // con.fill = GridBagConstraints.BOTH;
    // con.weightx = 0.3;
    // con.weighty = 1;
    // gbl.setConstraints(typeComp, con);
    main.add(typeComp, BorderLayout.WEST);
    main.add(right, BorderLayout.CENTER);
    main.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    pane.add(main, BorderLayout.CENTER);
    pane.add(buttons, BorderLayout.SOUTH);
    pack();
  }
  void setupPanel(JabRefFrame frame, BasePanel bPanel, boolean addKeyField, String title) {

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

    im.put(Globals.prefs.getKey("Entry editor, previous entry"), "prev");
    am.put("prev", parent.prevEntryAction);
    im.put(Globals.prefs.getKey("Entry editor, next entry"), "next");
    am.put("next", parent.nextEntryAction);

    im.put(Globals.prefs.getKey("Entry editor, store field"), "store");
    am.put("store", parent.storeFieldAction);
    im.put(Globals.prefs.getKey("Entry editor, next panel"), "right");
    im.put(Globals.prefs.getKey("Entry editor, next panel 2"), "right");
    am.put("left", parent.switchLeftAction);
    im.put(Globals.prefs.getKey("Entry editor, previous panel"), "left");
    im.put(Globals.prefs.getKey("Entry editor, previous panel 2"), "left");
    am.put("right", parent.switchRightAction);
    im.put(Globals.prefs.getKey("Help"), "help");
    am.put("help", parent.helpAction);
    im.put(Globals.prefs.getKey("Save database"), "save");
    am.put("save", parent.saveDatabaseAction);
    im.put(Globals.prefs.getKey("Next tab"), "nexttab");
    am.put("nexttab", parent.frame.nextTab);
    im.put(Globals.prefs.getKey("Previous tab"), "prevtab");
    am.put("prevtab", parent.frame.prevTab);

    panel.setName(title);
    // String rowSpec = "left:pref, 4dlu, fill:pref:grow, 4dlu, fill:pref";
    String colSpec =
        "fill:pref, 1dlu, fill:10dlu:grow, 1dlu, fill:pref, "
            + "8dlu, fill:pref, 1dlu, fill:10dlu:grow, 1dlu, fill:pref";
    StringBuffer sb = new StringBuffer();
    int rows = (int) Math.ceil((double) fields.length / 2.0);
    for (int i = 0; i < rows; i++) {
      sb.append("fill:pref:grow, ");
    }
    if (addKeyField) sb.append("4dlu, fill:pref");
    else if (sb.length() >= 2) sb.delete(sb.length() - 2, sb.length());
    String rowSpec = sb.toString();

    DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout(colSpec, rowSpec), panel);

    for (int i = 0; i < fields.length; i++) {
      // Create the text area:
      int editorType = BibtexFields.getEditorType(fields[i]);

      final FieldEditor ta;
      if (editorType == GUIGlobals.FILE_LIST_EDITOR)
        ta = new FileListEditor(frame, bPanel.metaData(), fields[i], null, parent);
      else ta = new FieldTextArea(fields[i], null);
      // ta.addUndoableEditListener(bPanel.undoListener);

      JComponent ex = parent.getExtra(fields[i], ta);

      // Add autocompleter listener, if required for this field:
      AbstractAutoCompleter autoComp = bPanel.getAutoCompleter(fields[i]);
      AutoCompleteListener acl = null;
      if (autoComp != null) {
        acl = new AutoCompleteListener(autoComp);
      }
      setupJTextComponent(ta.getTextComponent(), acl);
      ta.setAutoCompleteListener(acl);

      // Store the editor for later reference:
      editors.put(fields[i], ta);
      if (i == 0) activeField = ta;
      // System.out.println(fields[i]+": "+BibtexFields.getFieldWeight(fields[i]));
      // ta.getPane().setPreferredSize(new Dimension(100,
      //        (int)(50.0*BibtexFields.getFieldWeight(fields[i]))));
      builder.append(ta.getLabel());
      if (ex == null) builder.append(ta.getPane(), 3);
      else {
        builder.append(ta.getPane());
        JPanel pan = new JPanel();
        pan.setLayout(new BorderLayout());
        pan.add(ex, BorderLayout.NORTH);
        builder.append(pan);
      }
      if (i % 2 == 1) builder.nextLine();
    }

    // Add the edit field for Bibtex-key.
    if (addKeyField) {
      final FieldTextField tf =
          new FieldTextField(
              BibtexFields.KEY_FIELD, parent.getEntry().getField(BibtexFields.KEY_FIELD), true);
      // tf.addUndoableEditListener(bPanel.undoListener);
      setupJTextComponent(tf, null);

      editors.put("bibtexkey", tf);
      /*
       * If the key field is the only field, we should have only one
       * editor, and this one should be set as active initially:
       */
      if (editors.size() == 1) activeField = tf;
      builder.nextLine();
      builder.append(tf.getLabel());
      builder.append(tf, 3);
    }
  }
Example #11
0
  private Container createBorrowPane() {
    // Initialise date combo boxes
    borDay = new JComboBox();
    borMonth = new JComboBox();
    borYear = new JComboBox();
    String[] days = new String[31];
    for (int i = 0; i < 31; i++) days[i] = String.valueOf(i + 1);
    String[] months = {
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
    };
    String[] years = {
      "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014"
    };
    borDay.setModel(new DefaultComboBoxModel(days));
    borMonth.setModel(new DefaultComboBoxModel(months));
    borYear.setModel(new DefaultComboBoxModel(years));
    Calendar today = Calendar.getInstance();
    borDay.setSelectedIndex(today.get(DAY_OF_MONTH) - 1);
    borMonth.setSelectedIndex(today.get(MONTH));
    borYear.setSelectedIndex(today.get(YEAR) - 2005);

    // Create borrow button
    borrowButton = new JButton(borrowAction);

    // Create text fields
    borISBN = new JTextField(15);
    borCustID = new JTextField(15);

    // Create panel and layout
    JPanel pane = new JPanel();
    pane.setOpaque(false);
    GridBagLayout gb = new GridBagLayout();
    pane.setLayout(gb);
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(1, 5, 1, 5);

    // Fill panel
    c.anchor = GridBagConstraints.EAST;
    addToGridBag(gb, c, pane, new JLabel("ISBN:"), 0, 0, 1, 1);
    addToGridBag(gb, c, pane, new JLabel("Customer ID:"), 0, 1, 1, 1);
    addToGridBag(gb, c, pane, new JLabel("Due Date:"), 0, 2, 1, 1);

    c.anchor = GridBagConstraints.WEST;
    c.fill = GridBagConstraints.HORIZONTAL;
    addToGridBag(gb, c, pane, borISBN, 1, 0, 3, 1);
    addToGridBag(gb, c, pane, borCustID, 1, 1, 3, 1);

    c.fill = GridBagConstraints.NONE;
    addToGridBag(gb, c, pane, borDay, 1, 2, 1, 1);
    addToGridBag(gb, c, pane, borMonth, 2, 2, 1, 1);
    addToGridBag(gb, c, pane, borYear, 3, 2, 1, 1);

    addToGridBag(gb, c, pane, borrowButton, 4, 0, 1, 3);

    // Set up VK_ENTER triggering the borrow button in this panel
    InputMap input = pane.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    input.put(getKeyStroke("ENTER"), "borrowAction");
    pane.getActionMap().put("borrowAction", borrowAction);

    return pane;
  }
  private void init() {

    ok.addActionListener(
        e -> {
          storeSettings();
          dispose();
        });
    Action cancelAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };
    cancel.addActionListener(cancelAction);
    // The toDefaults resets the entire list to its default values.
    toDefaults.addActionListener(
        e -> {
          /*int reply = JOptionPane.showConfirmDialog(ExternalFileTypeEditor.this,
          Globals.lang("All custom file types will be lost. Proceed?"),
          Globals.lang("Reset file type definitions"), JOptionPane.YES_NO_OPTION,
          JOptionPane.QUESTION_MESSAGE);*/
          // if (reply == JOptionPane.YES_OPTION) {
          List<ExternalFileType> list = ExternalFileTypes.getDefaultExternalFileTypes();
          fileTypes.clear();
          fileTypes.addAll(list);
          Collections.sort(fileTypes);
          // Globals.prefs.resetExternalFileTypesToDefault();
          // setValues();
          tableModel.fireTableDataChanged();
          // }
        });

    add.addActionListener(
        e -> {
          // Generate a new file type:
          ExternalFileType type =
              new ExternalFileType("", "", "", "", "new", IconTheme.JabRefIcon.FILE.getSmallIcon());
          // Show the file type editor:
          getEditor(type).setVisible(true);
          if (entryEditor.okPressed()) {
            // Ok was pressed. Add the new file type and update the table:
            fileTypes.add(type);
            tableModel.fireTableDataChanged();
          }
        });

    remove.addActionListener(
        e -> {
          int[] rows = table.getSelectedRows();
          if (rows.length == 0) {
            return;
          }
          for (int i = rows.length - 1; i >= 0; i--) {
            fileTypes.remove(rows[i]);
          }
          tableModel.fireTableDataChanged();
          if (!fileTypes.isEmpty()) {
            int row = Math.min(rows[0], fileTypes.size() - 1);
            table.setRowSelectionInterval(row, row);
          }
        });

    edit.addActionListener(editListener);
    fileTypes = new ArrayList<>();
    setValues();

    tableModel = new FileTypeTableModel();
    table = new JTable(tableModel);
    table.setDefaultRenderer(ImageIcon.class, new IconRenderer());
    table.addMouseListener(new TableClickListener());

    table.getColumnModel().getColumn(0).setMaxWidth(24);
    table.getColumnModel().getColumn(0).setMinWidth(24);
    table.getColumnModel().getColumn(1).setMinWidth(170);
    table.getColumnModel().getColumn(2).setMinWidth(60);
    table.getColumnModel().getColumn(3).setMinWidth(100);
    table.getColumnModel().getColumn(0).setResizable(false);

    GUIUtil.correctRowHeight(table);

    JScrollPane sp = new JScrollPane(table);

    JPanel upper = new JPanel();
    upper.setLayout(new BorderLayout());
    upper.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    upper.add(sp, BorderLayout.CENTER);
    getContentPane().add(upper, BorderLayout.CENTER);

    ButtonStackBuilder bs = new ButtonStackBuilder();
    bs.addButton(add);
    bs.addButton(remove);
    bs.addButton(edit);
    bs.addRelatedGap();
    bs.addButton(toDefaults);
    upper.add(bs.getPanel(), BorderLayout.EAST);

    ButtonBarBuilder bb = new ButtonBarBuilder();
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();
    bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
    pack();

    // Key bindings:
    ActionMap am = upper.getActionMap();
    InputMap im = upper.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);
    am = bb.getPanel().getActionMap();
    im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelAction);

    if (frame == null) {
      setLocationRelativeTo(dialog);
    } else {
      setLocationRelativeTo(frame);
    }
  }
Example #13
0
  int showOpenDialog(final boolean sa) {

    dialog = new JDialog(frame, JDialog.ModalityType.APPLICATION_MODAL);
    // dialog.setUndecorated(false);

    saveAs = sa;

    dialog.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            dialog.dispose();
          }
        });

    panel = new JPanel();
    panel.setLayout(new BorderLayout());

    driver.curDiag.filterOptions[0] = fCParms.title;
    cBox = new MyComboBox(driver.curDiag.filterOptions);
    cBox.setMaximumRowCount(2);
    cBox.addMouseListener(this);
    cBox.setSelectedIndex(driver.allFiles ? 1 : 0);

    order = new Vector<Component>(9);
    order.add(text);
    order.add(butParent);
    order.add(butNF);
    order.add(panel); // just a place-holder - will be filled in by
    // buildList
    order.add(text2);
    order.add(butCopy);
    order.add(butOK);
    order.add(cBox);
    order.add(butDel);
    order.add(butCancel);

    text.setEditable(true);
    text.setEnabled(true);

    // text.getDocument().addDocumentListener(this);

    text2.setEditable(true);
    text2.setEnabled(true);
    text2.setRequestFocusEnabled(true);
    // text2.addKeyListener(this);
    // text2.getDocument().addDocumentListener(this);
    text2.setPreferredSize(new Dimension(100, driver.fontHeight + 2));

    text3.setEditable(false);
    text3.setEnabled(true);
    // text3.setRequestFocusEnabled(true);
    text3.setFont(driver.fontg.deriveFont(Font.ITALIC));
    // text3.setPreferredSize(new Dimension(100, driver.fontHeight + 2));

    String s = (saveAs) ? "Save or Save As" : "Open File";
    comp = new MyFileCompare();
    renderer = new ListRenderer(driver);

    if (fCParms == driver.curDiag.fCPArr[DrawFBP.DIAGRAM]) dialog.setTitle(s);
    else {
      if (fCParms == driver.curDiag.fCPArr[DrawFBP.GENCODE])
        fCParms.prompt =
            "Specify file name for generated code - for diagram: " + driver.curDiag.title + ".drw";

      dialog.setTitle(fCParms.prompt);
      if (fCParms == driver.curDiag.fCPArr[DrawFBP.CLASS]) listShowingJarFile = listHead;
    }

    enterAction = new EnterAction();
    copyAction = new CopyAction();
    cancelAction = new CancelAction();
    deleteAction = new DeleteAction();

    parentAction = new ParentAction();
    newFolderAction = new NewFolderAction();

    butParent.setAction(parentAction);
    butParent.setText("Parent Folder");
    butParent.setMnemonic(KeyEvent.VK_P);

    butNF.setAction(newFolderAction);
    butNF.setMnemonic(KeyEvent.VK_N);
    butNF.setText("New Folder");

    // butOK.setAction(okAction);
    butOK.setAction(enterAction);
    butCopy.setAction(copyAction);
    butCancel.setAction(cancelAction);
    butDel.setAction(deleteAction);

    butParent.setRequestFocusEnabled(true);
    butNF.setRequestFocusEnabled(true);
    butCopy.setRequestFocusEnabled(true);

    text.addMouseListener(this);
    text2.addMouseListener(this);

    panel.setPreferredSize(new Dimension(600, 600));

    text.setFocusTraversalKeysEnabled(false);
    butParent.setFocusTraversalKeysEnabled(false);
    butNF.setFocusTraversalKeysEnabled(false);
    text2.setFocusTraversalKeysEnabled(false);
    butOK.setFocusTraversalKeysEnabled(false);
    butDel.setFocusTraversalKeysEnabled(false);
    butCancel.setFocusTraversalKeysEnabled(false);
    butCopy.setFocusTraversalKeysEnabled(false);

    butParent.setEnabled(true);
    butNF.setEnabled(true);
    butOK.setEnabled(true);
    // butCopy.setEnabled(saveAs);
    butCopy.setEnabled(true);
    butCancel.setEnabled(true);
    butDel.setEnabled(true);

    KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
    panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escape, "CLOSE");

    panel.getActionMap().put("CLOSE", cancelAction);

    JLabel label = new JLabel("Current folder: ");
    label.setFont(driver.fontg);

    Box box0 = new Box(BoxLayout.Y_AXIS);
    Box box1 = new Box(BoxLayout.X_AXIS);

    box1.add(label);

    box1.add(Box.createRigidArea(new Dimension(12, 0)));
    box1.add(text);
    box1.add(Box.createRigidArea(new Dimension(6, 0)));

    box1.add(butParent);
    // butParent.addActionListener(this);
    box1.add(Box.createRigidArea(new Dimension(6, 0)));

    // butNF.addActionListener(this);
    box1.add(butNF);

    box0.add(Box.createRigidArea(new Dimension(0, 20)));
    box0.add(box1);

    box0.add(Box.createRigidArea(new Dimension(0, 20)));
    panel.add(box0, BorderLayout.NORTH);

    text.setFont(label.getFont());
    text.addActionListener(this);
    text2.addActionListener(this);

    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;

    JPanel pan2 = new JPanel();

    pan2.setLayout(gridbag);
    // c.fill = GridBagConstraints.BOTH;

    c.gridx = 0;
    c.gridy = 0;
    c.weightx = 0.0;

    JLabel lab1 = new JLabel("File name: ");
    gridbag.setConstraints(lab1, c);
    pan2.add(lab1);

    c.gridx = 1;
    c.weightx = 0.0;
    JLabel lab5 = new JLabel("  ");
    gridbag.setConstraints(lab5, c);
    pan2.add(lab5);

    c.gridx = 2;

    c.weightx = saveAs ? 0.1 : 1.0;
    c.gridwidth = saveAs ? 1 : 3;
    // c.ipadx  = saveAs ? -20: 0;
    gridbag.setConstraints(text2, c);
    pan2.add(text2);

    if (saveAs) {
      c.gridx = 3;
      c.weightx = 0.0;
      c.gridwidth = 1;
      JLabel lab6 = new JLabel("   Suggestion: ");
      gridbag.setConstraints(lab6, c);
      pan2.add(lab6);

      c.gridx = 4;
      c.weightx = 0.9;
      // c.ipadx = 20;
      gridbag.setConstraints(text3, c);
      pan2.add(text3);
      text3.setBackground(Color.WHITE);
      Dimension dim = text3.getPreferredSize();
      text3.setPreferredSize(new Dimension(driver.fontWidth * 25, dim.height));
    }

    c.gridx = 5;
    c.weightx = 0.0;
    JLabel lab7 = new JLabel("  ");
    gridbag.setConstraints(lab7, c);
    pan2.add(lab7);

    c.gridx = 6;
    c.weightx = 0.0;

    if (saveAs) {
      c.gridwidth = 1;
      gridbag.setConstraints(butCopy, c);
      pan2.add(butCopy);

      c.gridx = 7;
      c.weightx = 0.0;

      c.gridwidth = 1;
    } else c.gridwidth = 2;
    gridbag.setConstraints(butOK, c);
    pan2.add(butOK);

    c.weightx = 0.0;
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;

    JLabel lab2 = new JLabel("Files of type:");
    gridbag.setConstraints(lab2, c);
    pan2.add(lab2);

    c.gridx = 1;
    c.weightx = 0.0;
    JLabel lab8 = new JLabel("  ");
    gridbag.setConstraints(lab8, c);
    pan2.add(lab8);

    c.gridx = 2;
    c.weightx = 1.0;
    c.gridwidth = 3;
    gridbag.setConstraints(cBox, c);
    pan2.add(cBox);
    cBox.addActionListener(this);

    c.gridx = 5;
    c.weightx = 0.0;
    c.gridwidth = 1;
    JLabel lab9 = new JLabel("  ");
    gridbag.setConstraints(lab9, c);
    pan2.add(lab9);

    c.gridx = 6;
    c.weightx = 0.0;
    gridbag.setConstraints(butDel, c);
    pan2.add(butDel);

    c.gridx = 7;
    c.weightx = 0.0;
    gridbag.setConstraints(butCancel, c);
    pan2.add(butCancel);

    butOK.setText("OK");
    butOK.setFont(driver.fontg.deriveFont(Font.BOLD));
    butCancel.setText("Cancel");
    butDel.setText("Delete");
    butCopy.setText(saveAs ? "Use suggested name" : "");

    JLabel lab3 = new JLabel();
    lab3.setPreferredSize(new Dimension(500, 30));
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 4;
    c.weightx = 1.0;
    gridbag.setConstraints(lab3, c);
    pan2.add(lab3);

    cBox.addActionListener(this);

    // cBox.setUI(new BasicComboBoxUI());
    cBox.setRenderer(new ComboBoxRenderer());

    Dimension dim = new Dimension(1000, 800);
    dialog.setPreferredSize(dim);

    dialog.setFocusTraversalKeysEnabled(false);
    text.addKeyListener(this);
    text2.addKeyListener(this);
    butParent.addKeyListener(this); // needed to service tab keys
    butNF.addKeyListener(this); // needed to service tab keys
    butOK.addKeyListener(this); // needed to service tab keys
    cBox.addKeyListener(this); // needed to service tab keys
    butDel.addKeyListener(this); // needed to service tab keys
    butCancel.addKeyListener(this); // needed to service tab keys
    butCopy.addKeyListener(this); // needed to service tab keys
    cBox.setFocusTraversalKeysEnabled(false);
    mtp = new MyTraversalPolicy();
    setFocusTraversalPolicy(mtp);
    setFocusCycleRoot(false);

    showList();
    if (saveAs) {

      if (suggestedName != null && !(suggestedName.equals(""))) {
        File h = new File(suggestedName);
        listHead = h.getParent();
        text.setText(listHead);
        text2.setText(h.getName());
        text3.setText(h.getName());

        /*
        SwingUtilities.invokeLater(new Runnable() {
        	public void run() {
        		text2.requestFocusInWindow();
        		selComp = text2;
        		text2.setBackground(vLightBlue);
        	}
        });

        */

        text2.addAncestorListener(new RequestFocusListener(false));
        selComp = text2;
        // text2.setBackground(vLightBlue);
        // text2.setEditable(true);
      }

      if (driver.curDiag.title != null && driver.curDiag.diagFile != null) {
        s += " (current file: " + driver.curDiag.diagFile.getAbsolutePath() + ")";
      }
    } else {
      text.setText(listHead);
      /*
      SwingUtilities.invokeLater(new Runnable() {
      	public void run() {
      		list.requestFocusInWindow();
      		selComp = list;
      		// list.setBackground(vLightBlue);
      	}
      });
      */
      // list.addAncestorListener( new RequestFocusListener() );
      selComp = list;
    }

    panel.add(pan2, BorderLayout.SOUTH);
    dialog.add(panel);

    dialog.pack();
    dialog.setLocation(200, 100);
    frame.pack();

    dialog.setVisible(true);

    // if (!saveAs)
    // textBackground = Color.WHITE;

    frame.repaint();

    return result;
  }
  public ImportCustomizationDialog(final JabRefFrame frame) {
    super(frame, Localization.lang("Manage custom imports"), false);

    ImportTableModel tableModel = new ImportTableModel();
    customImporterTable = new JTable(tableModel);
    TableColumnModel cm = customImporterTable.getColumnModel();
    cm.getColumn(0).setPreferredWidth(COL_0_WIDTH);
    cm.getColumn(1).setPreferredWidth(COL_1_WIDTH);
    cm.getColumn(2).setPreferredWidth(COL_2_WIDTH);
    cm.getColumn(3).setPreferredWidth(COL_3_WIDTH);
    JScrollPane sp =
        new JScrollPane(
            customImporterTable,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    customImporterTable.setPreferredScrollableViewportSize(getSize());
    if (customImporterTable.getRowCount() > 0) {
      customImporterTable.setRowSelectionInterval(0, 0);
    }

    JButton addFromFolderButton = new JButton(Localization.lang("Add from folder"));
    addFromFolderButton.addActionListener(
        e -> {
          FileDialog dialog = new FileDialog(frame).withExtension(FileExtensions.CLASS);
          dialog.setDefaultExtension(FileExtensions.CLASS);
          Optional<Path> selectedFile = dialog.showDialogAndGetSelectedFile();

          if (selectedFile.isPresent() && (selectedFile.get().getParent() != null)) {
            String chosenFileStr = selectedFile.get().toString();

            try {
              String basePath = selectedFile.get().getParent().toString();
              String className = pathToClass(basePath, new File(chosenFileStr));
              CustomImporter importer = new CustomImporter(basePath, className);

              addOrReplaceImporter(importer);
              customImporterTable.revalidate();
              customImporterTable.repaint();
            } catch (Exception exc) {
              JOptionPane.showMessageDialog(
                  frame, Localization.lang("Could not instantiate %0", chosenFileStr));
            } catch (NoClassDefFoundError exc) {
              JOptionPane.showMessageDialog(
                  frame,
                  Localization.lang(
                      "Could not instantiate %0. Have you chosen the correct package path?",
                      chosenFileStr));
            }
          }
        });
    addFromFolderButton.setToolTipText(
        Localization.lang("Add a (compiled) custom Importer class from a class path.")
            + "\n"
            + Localization.lang("The path need not be on the classpath of JabRef."));

    JButton addFromJarButton = new JButton(Localization.lang("Add from JAR"));
    addFromJarButton.addActionListener(
        e -> {
          FileDialog dialog =
              new FileDialog(frame)
                  .withExtensions(EnumSet.of(FileExtensions.ZIP, FileExtensions.JAR));
          dialog.setDefaultExtension(FileExtensions.JAR);
          Optional<Path> jarZipFile = dialog.showDialogAndGetSelectedFile();

          if (jarZipFile.isPresent()) {
            try (ZipFile zipFile = new ZipFile(jarZipFile.get().toFile(), ZipFile.OPEN_READ)) {
              ZipFileChooser zipFileChooser = new ZipFileChooser(this, zipFile);
              zipFileChooser.setVisible(true);
              customImporterTable.revalidate();
              customImporterTable.repaint(10);
            } catch (IOException exc) {
              LOGGER.info("Could not open ZIP-archive.", exc);
              JOptionPane.showMessageDialog(
                  frame,
                  Localization.lang("Could not open %0", jarZipFile.get().toString())
                      + "\n"
                      + Localization.lang("Have you chosen the correct package path?"));
            } catch (NoClassDefFoundError exc) {
              LOGGER.info("Could not instantiate ZIP-archive reader.", exc);
              JOptionPane.showMessageDialog(
                  frame,
                  Localization.lang("Could not instantiate %0", jarZipFile.get().toString())
                      + "\n"
                      + Localization.lang("Have you chosen the correct package path?"));
            }
          }
        });
    addFromJarButton.setToolTipText(
        Localization.lang("Add a (compiled) custom Importer class from a ZIP-archive.")
            + "\n"
            + Localization.lang("The ZIP-archive need not be on the classpath of JabRef."));

    JButton showDescButton = new JButton(Localization.lang("Show description"));
    showDescButton.addActionListener(
        e -> {
          int row = customImporterTable.getSelectedRow();
          if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
          } else {
            CustomImporter importer =
                ((ImportTableModel) customImporterTable.getModel()).getImporter(row);
            JOptionPane.showMessageDialog(frame, importer.getDescription());
          }
        });

    JButton removeButton = new JButton(Localization.lang("Remove"));
    removeButton.addActionListener(
        e -> {
          int row = customImporterTable.getSelectedRow();
          if (row == -1) {
            JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer."));
          } else {
            customImporterTable.removeRowSelectionInterval(row, row);
            Globals.prefs.customImports.remove(
                ((ImportTableModel) customImporterTable.getModel()).getImporter(row));
            Globals.IMPORT_FORMAT_READER.resetImportFormats(
                Globals.prefs.getImportFormatPreferences(), Globals.prefs.getXMPPreferences());
            customImporterTable.revalidate();
            customImporterTable.repaint();
          }
        });

    Action closeAction =
        new AbstractAction() {

          @Override
          public void actionPerformed(ActionEvent e) {
            dispose();
          }
        };

    JButton closeButton = new JButton(Localization.lang("Close"));
    closeButton.addActionListener(closeAction);

    JButton helpButton = new HelpAction(HelpFile.CUSTOM_IMPORTS).getHelpButton();

    // Key bindings:
    JPanel mainPanel = new JPanel();
    ActionMap am = mainPanel.getActionMap();
    InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", closeAction);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(sp, BorderLayout.CENTER);
    JPanel buttons = new JPanel();
    ButtonBarBuilder bb = new ButtonBarBuilder(buttons);
    buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    bb.addGlue();
    bb.addButton(addFromFolderButton);
    bb.addButton(addFromJarButton);
    bb.addButton(showDescButton);
    bb.addButton(removeButton);
    bb.addButton(closeButton);
    bb.addUnrelatedGap();
    bb.addButton(helpButton);
    bb.addGlue();

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(buttons, BorderLayout.SOUTH);
    this.setSize(getSize());
    pack();
    this.setLocationRelativeTo(frame);
    customImporterTable.requestFocus();
  }