コード例 #1
0
  private static String getModifiersText(@JdkConstants.InputEventMask int modifiers) {
    if (SystemInfo.isMac) {
      // try {
      //  Class appleLaf = Class.forName(APPLE_LAF_AQUA_LOOK_AND_FEEL_CLASS_NAME);
      //  Method getModifiers = appleLaf.getMethod(GET_KEY_MODIFIERS_TEXT_METHOD, int.class,
      // boolean.class);
      //  return (String)getModifiers.invoke(appleLaf, modifiers, Boolean.FALSE);
      // }
      // catch (Exception e) {
      //  if (SystemInfo.isMacOSLeopard) {
      //    return getKeyModifiersTextForMacOSLeopard(modifiers);
      //  }
      //
      //  // OK do nothing here.
      // }
      return MacKeymapUtil.getModifiersText(modifiers);
    }

    final String keyModifiersText = KeyEvent.getKeyModifiersText(modifiers);
    if (keyModifiersText.isEmpty()) {
      return keyModifiersText;
    } else {
      return keyModifiersText + "+";
    }
  }
コード例 #2
0
ファイル: Shortcut.java プロジェクト: uazure/josm
 /**
  * Returns a human readable text for the shortcut.
  *
  * @return a human readable text for the shortcut
  */
 public String getKeyText() {
   KeyStroke keyStroke = getKeyStroke();
   if (keyStroke == null) return "";
   String modifText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers());
   if ("".equals(modifText)) return KeyEvent.getKeyText(keyStroke.getKeyCode());
   return modifText + '+' + KeyEvent.getKeyText(keyStroke.getKeyCode());
 }
コード例 #3
0
  private String getModifiers(KeyEvent evt) {
    int modifiers = evt.getModifiers();
    if (modifiers != 0) {
      String sb = KeyEvent.getKeyModifiersText(modifiers);
      return sb.replaceAll("\\+", "|");
    }

    return "";
  }
コード例 #4
0
 /** Translate KeyStrokes into String representation. */
 private String[] getKeyStrings(KeyStroke[] keys) {
   String[] keyStrings = new String[keys.length];
   for (int i = 0; i < keys.length; i++) {
     int modifiers = keys[i].getModifiers();
     keyStrings[i] = KeyEvent.getKeyModifiersText(modifiers);
     if (keyStrings[i].length() > 0) keyStrings[i] += "+";
     keyStrings[i] += KeyEvent.getKeyText(keys[i].getKeyCode());
   }
   return keyStrings;
 }
コード例 #5
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
 public void keyTyped(KeyEvent e) {
   char keyChar = e.getKeyChar();
   int flags = e.getModifiers();
   if (IJ.debugMode)
     IJ.log(
         "keyTyped: char=\""
             + keyChar
             + "\" ("
             + (int) keyChar
             + "), flags= "
             + Integer.toHexString(flags)
             + " ("
             + KeyEvent.getKeyModifiersText(flags)
             + ")");
   if (keyChar == '\\' || keyChar == 171 || keyChar == 223) {
     if (((flags & Event.ALT_MASK) != 0)) doCommand("Animation Options...");
     else doCommand("Start Animation [\\]");
   }
 }
コード例 #6
0
ファイル: PrefJPanel.java プロジェクト: harrymahar/josm
/**
 * This is the keyboard preferences content. If someone wants to merge it with
 * ShortcutPreference.java, feel free.
 */
public class PrefJPanel extends JPanel {

  // table of shortcuts
  private AbstractTableModel model;
  // comboboxes of modifier groups, mapping selectedIndex to real data
  private static int[] modifInts =
      new int[] {
        -1,
        0,
        KeyEvent.SHIFT_DOWN_MASK,
        KeyEvent.CTRL_DOWN_MASK,
        KeyEvent.ALT_DOWN_MASK,
        KeyEvent.META_DOWN_MASK,
        KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK,
        KeyEvent.ALT_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK,
        KeyEvent.META_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK,
        KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK,
        KeyEvent.CTRL_DOWN_MASK | KeyEvent.META_DOWN_MASK,
        KeyEvent.ALT_DOWN_MASK | KeyEvent.META_DOWN_MASK,
        KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK | KeyEvent.ALT_DOWN_MASK,
        KeyEvent.META_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK | KeyEvent.ALT_DOWN_MASK
      };
  // and here are the texts fro the comboboxes
  private static String[] modifList =
      new String[] {
        tr("disabled"),
        tr("no modifier"),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[2]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[3]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[4]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[5]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[6]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[7]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[8]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[9]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[10]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[11]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[12]).getModifiers()),
        KeyEvent.getKeyModifiersText(
            KeyStroke.getKeyStroke(KeyEvent.VK_A, modifInts[13]).getModifiers())
      };
  // this are the display(!) texts for the checkboxes. Let the JVM do the i18n for us <g>.
  // Ok, there's a real reason for this: The JVM should know best how the keys are labelled
  // on the physical keyboard. What language pack is installed in JOSM is completely
  // independent from the keyboard's labelling. But the operation system's locale
  // usually matches the keyboard. This even works with my English Windows and my German
  // keyboard.
  private static String SHIFT =
      KeyEvent.getKeyModifiersText(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.SHIFT_DOWN_MASK).getModifiers());
  private static String CTRL =
      KeyEvent.getKeyModifiersText(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK).getModifiers());
  private static String ALT =
      KeyEvent.getKeyModifiersText(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.ALT_DOWN_MASK).getModifiers());
  private static String META =
      KeyEvent.getKeyModifiersText(
          KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.META_DOWN_MASK).getModifiers());

  // A list of keys to present the user. Sadly this really is a list of keys Java knows about,
  // not a list of real physical keys. If someone knows how to get that list?
  private static Map<Integer, String> keyList = setKeyList();

  private static Map<Integer, String> setKeyList() {
    Map<Integer, String> list = new LinkedHashMap<Integer, String>();
    String unknown = Toolkit.getProperty("AWT.unknown", "Unknown");
    // Assume all known keys are declared in KeyEvent as "public static int VK_*"
    for (Field field : KeyEvent.class.getFields()) {
      if (field.getName().startsWith("VK_")) {
        try {
          int i = field.getInt(null);
          String s = KeyEvent.getKeyText(i);
          if (s != null && s.length() > 0 && !s.contains(unknown)) {
            list.put(Integer.valueOf(i), s);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    list.put(Integer.valueOf(-1), "");
    return list;
  }

  private JCheckBox cbAlt = new JCheckBox();
  private JCheckBox cbCtrl = new JCheckBox();
  private JCheckBox cbMeta = new JCheckBox();
  private JCheckBox cbShift = new JCheckBox();
  private JCheckBox cbDefault = new JCheckBox();
  private JCheckBox cbDisable = new JCheckBox();
  private JosmComboBox tfKey = new JosmComboBox();

  JTable shortcutTable = new JTable();

  private JosmTextField filterField = new JosmTextField();

  /** Creates new form prefJPanel */
  // Ain't those auto-generated comments helpful or what? <g>
  public PrefJPanel(AbstractTableModel model) {
    this.model = model;
    initComponents();
  }

  /** Show only shortcuts with descriptions coontaing given substring */
  public void filter(String substring) {
    filterField.setText(substring);
  }

  private class ShortcutTableCellRenderer extends DefaultTableCellRenderer {

    private boolean name;

    public ShortcutTableCellRenderer(boolean name) {
      this.name = name;
    }

    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      int row1 = shortcutTable.convertRowIndexToModel(row);
      Shortcut sc = (Shortcut) model.getValueAt(row1, -1);
      if (sc == null) return null;
      JLabel label =
          (JLabel)
              super.getTableCellRendererComponent(
                  table,
                  name ? sc.getLongText() : sc.getKeyText(),
                  isSelected,
                  hasFocus,
                  row,
                  column);
      label.setBackground(Main.pref.getUIColor("Table.background"));
      if (isSelected) {
        label.setForeground(Main.pref.getUIColor("Table.foreground"));
      }
      if (sc.getAssignedUser()) {
        label.setBackground(
            Main.pref.getColor(marktr("Shortcut Background: User"), new Color(200, 255, 200)));
      } else if (!sc.getAssignedDefault()) {
        label.setBackground(
            Main.pref.getColor(marktr("Shortcut Background: Modified"), new Color(255, 255, 200)));
      }
      return label;
    }
  }

  private void initComponents() {
    JPanel listPane = new JPanel();
    JScrollPane listScrollPane = new JScrollPane();
    JPanel shortcutEditPane = new JPanel();

    CbAction action = new CbAction(this);
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    add(buildFilterPanel());
    listPane.setLayout(new java.awt.GridLayout());

    // This is the list of shortcuts:
    shortcutTable.setModel(model);
    shortcutTable.getSelectionModel().addListSelectionListener(new CbAction(this));
    shortcutTable.setFillsViewportHeight(true);
    shortcutTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    shortcutTable.setAutoCreateRowSorter(true);
    TableColumnModel mod = shortcutTable.getColumnModel();
    mod.getColumn(0).setCellRenderer(new ShortcutTableCellRenderer(true));
    mod.getColumn(1).setCellRenderer(new ShortcutTableCellRenderer(false));
    listScrollPane.setViewportView(shortcutTable);

    listPane.add(listScrollPane);

    add(listPane);

    // and here follows the edit area. I won't object to someone re-designing it, it looks, um,
    // "minimalistic" ;)
    shortcutEditPane.setLayout(new java.awt.GridLayout(5, 2));

    cbDefault.setAction(action);
    cbDefault.setText(tr("Use default"));
    cbShift.setAction(action);
    cbShift.setText(SHIFT); // see above for why no tr()
    cbDisable.setAction(action);
    cbDisable.setText(tr("Disable"));
    cbCtrl.setAction(action);
    cbCtrl.setText(CTRL); // see above for why no tr()
    cbAlt.setAction(action);
    cbAlt.setText(ALT); // see above for why no tr()
    tfKey.setAction(action);
    tfKey.setModel(new DefaultComboBoxModel(keyList.values().toArray()));
    cbMeta.setAction(action);
    cbMeta.setText(META); // see above for why no tr()

    shortcutEditPane.add(cbDefault);
    shortcutEditPane.add(new JLabel());
    shortcutEditPane.add(cbShift);
    shortcutEditPane.add(cbDisable);
    shortcutEditPane.add(cbCtrl);
    shortcutEditPane.add(new JLabel(tr("Key:"), SwingConstants.LEFT));
    shortcutEditPane.add(cbAlt);
    shortcutEditPane.add(tfKey);
    shortcutEditPane.add(cbMeta);

    shortcutEditPane.add(new JLabel(tr("Attention: Use real keyboard keys only!")));

    action.actionPerformed(null); // init checkboxes

    add(shortcutEditPane);
  }

  private JPanel buildFilterPanel() {
    // copied from PluginPreference
    JPanel pnl = new JPanel(new GridBagLayout());
    pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    GridBagConstraints gc = new GridBagConstraints();

    gc.anchor = GridBagConstraints.NORTHWEST;
    gc.fill = GridBagConstraints.HORIZONTAL;
    gc.weightx = 0.0;
    gc.insets = new Insets(0, 0, 0, 5);
    pnl.add(new JLabel(tr("Search:")), gc);

    gc.gridx = 1;
    gc.weightx = 1.0;
    pnl.add(filterField, gc);
    filterField.setToolTipText(tr("Enter a search expression"));
    SelectAllOnFocusGainedDecorator.decorate(filterField);
    filterField.getDocument().addDocumentListener(new FilterFieldAdapter());
    pnl.setMaximumSize(new Dimension(300, 10));
    return pnl;
  }

  private void disableAllModifierCheckboxes() {
    cbDefault.setEnabled(false);
    cbDisable.setEnabled(false);
    cbShift.setEnabled(false);
    cbCtrl.setEnabled(false);
    cbAlt.setEnabled(false);
    cbMeta.setEnabled(false);
  }

  // this allows to edit shortcuts. it:
  //  * sets the edit controls to the selected shortcut
  //  * enabled/disables the controls as needed
  //  * writes the user's changes to the shortcut
  // And after I finally had it working, I realized that those two methods
  // are playing ping-pong (politically correct: table tennis, I know) and
  // even have some duplicated code. Feel free to refactor, If you have
  // more expirience with GUI coding than I have.
  private class CbAction extends AbstractAction implements ListSelectionListener {
    private PrefJPanel panel;

    public CbAction(PrefJPanel panel) {
      this.panel = panel;
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
      ListSelectionModel lsm = panel.shortcutTable.getSelectionModel(); // can't use e here
      if (!lsm.isSelectionEmpty()) {
        int row = panel.shortcutTable.convertRowIndexToModel(lsm.getMinSelectionIndex());
        Shortcut sc = (Shortcut) panel.model.getValueAt(row, -1);
        panel.cbDefault.setSelected(!sc.getAssignedUser());
        panel.cbDisable.setSelected(sc.getKeyStroke() == null);
        panel.cbShift.setSelected(
            sc.getAssignedModifier() != -1
                && (sc.getAssignedModifier() & KeyEvent.SHIFT_DOWN_MASK) != 0);
        panel.cbCtrl.setSelected(
            sc.getAssignedModifier() != -1
                && (sc.getAssignedModifier() & KeyEvent.CTRL_DOWN_MASK) != 0);
        panel.cbAlt.setSelected(
            sc.getAssignedModifier() != -1
                && (sc.getAssignedModifier() & KeyEvent.ALT_DOWN_MASK) != 0);
        panel.cbMeta.setSelected(
            sc.getAssignedModifier() != -1
                && (sc.getAssignedModifier() & KeyEvent.META_DOWN_MASK) != 0);
        if (sc.getKeyStroke() != null) {
          tfKey.setSelectedItem(keyList.get(sc.getKeyStroke().getKeyCode()));
        } else {
          tfKey.setSelectedItem(keyList.get(-1));
        }
        if (!sc.isChangeable()) {
          disableAllModifierCheckboxes();
          panel.tfKey.setEnabled(false);
        } else {
          panel.cbDefault.setEnabled(true);
          actionPerformed(null);
        }
        model.fireTableRowsUpdated(row, row);
      } else {
        panel.disableAllModifierCheckboxes();
        panel.tfKey.setEnabled(false);
      }
    }

    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
      ListSelectionModel lsm = panel.shortcutTable.getSelectionModel();
      if (lsm != null && !lsm.isSelectionEmpty()) {
        if (e != null) { // only if we've been called by a user action
          int row = panel.shortcutTable.convertRowIndexToModel(lsm.getMinSelectionIndex());
          Shortcut sc = (Shortcut) panel.model.getValueAt(row, -1);
          if (panel.cbDisable.isSelected()) {
            sc.setAssignedModifier(-1);
          } else if (panel.tfKey.getSelectedItem() == null
              || panel.tfKey.getSelectedItem().equals("")) {
            sc.setAssignedModifier(KeyEvent.VK_CANCEL);
          } else {
            sc.setAssignedModifier(
                (panel.cbShift.isSelected() ? KeyEvent.SHIFT_DOWN_MASK : 0)
                    | (panel.cbCtrl.isSelected() ? KeyEvent.CTRL_DOWN_MASK : 0)
                    | (panel.cbAlt.isSelected() ? KeyEvent.ALT_DOWN_MASK : 0)
                    | (panel.cbMeta.isSelected() ? KeyEvent.META_DOWN_MASK : 0));
            for (Map.Entry<Integer, String> entry : keyList.entrySet()) {
              if (entry.getValue().equals(panel.tfKey.getSelectedItem())) {
                sc.setAssignedKey(entry.getKey());
              }
            }
          }
          sc.setAssignedUser(!panel.cbDefault.isSelected());
          valueChanged(null);
        }
        boolean state = !panel.cbDefault.isSelected();
        panel.cbDisable.setEnabled(state);
        state = state && !panel.cbDisable.isSelected();
        panel.cbShift.setEnabled(state);
        panel.cbCtrl.setEnabled(state);
        panel.cbAlt.setEnabled(state);
        panel.cbMeta.setEnabled(state);
        panel.tfKey.setEnabled(state);
      } else {
        panel.disableAllModifierCheckboxes();
        panel.tfKey.setEnabled(false);
      }
    }
  }

  class FilterFieldAdapter implements DocumentListener {
    public void filter() {
      String expr = filterField.getText().trim();
      if (expr.length() == 0) {
        expr = null;
      }
      try {
        final TableRowSorter<? extends TableModel> sorter =
            ((TableRowSorter<? extends TableModel>) shortcutTable.getRowSorter());
        if (expr == null) {
          sorter.setRowFilter(null);
        } else {
          expr = expr.replace("+", "\\+");
          // split search string on whitespace, do case-insensitive AND search
          ArrayList<RowFilter<Object, Object>> andFilters =
              new ArrayList<RowFilter<Object, Object>>();
          for (String word : expr.split("\\s+")) {
            andFilters.add(RowFilter.regexFilter("(?i)" + word));
          }
          sorter.setRowFilter(RowFilter.andFilter(andFilters));
        }
        model.fireTableDataChanged();
      } catch (PatternSyntaxException ex) {
      } catch (ClassCastException ex2) {
        /* eliminate warning */
      }
    }

    @Override
    public void changedUpdate(DocumentEvent arg0) {
      filter();
    }

    @Override
    public void insertUpdate(DocumentEvent arg0) {
      filter();
    }

    @Override
    public void removeUpdate(DocumentEvent arg0) {
      filter();
    }
  }
}
コード例 #7
0
ファイル: KeyBinding.java プロジェクト: mahogny/Endrov
 public String getKeyDesc() {
   if (keyCode == 0 && modifierEx == 0) return "<unassigned>";
   String r = KeyEvent.getKeyModifiersText(modifierEx);
   if (!r.equals("")) r = r + "+";
   return (r + KeyEvent.getKeyText(keyCode)).toLowerCase();
 }
コード例 #8
0
ファイル: EditorPane.java プロジェクト: hencjo/jOOQ
  private void addResultTable(
      final String sql, long duration, final StatementExecutionResultSetResult resultSetResult) {
    int rowCount = resultSetResult.getRowCount();
    JPanel resultPane = addResultPane();
    final JLabel label = new JLabel(" " + rowCount + " rows");
    FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT, 0, 0);
    flowLayout.setAlignOnBaseline(true);
    JPanel statusPane = new JPanel(flowLayout);
    statusPane.setOpaque(false);
    if (rowCount <= resultSetResult.getRetainParsedRSDataRowCountThreshold()) {
      final JTableX table = new ResultTable(resultSetResult);
      JTableHeader tableHeader =
          new JTableHeader(table.getColumnModel()) {
            @Override
            public String getToolTipText(MouseEvent e) {
              int col = getTable().convertColumnIndexToModel(columnAtPoint(e.getPoint()));
              return col == 0 ? null : resultSetResult.getTypeInfos()[col - 1].toString();
            }
          };
      ToolTipManager.sharedInstance().registerComponent(tableHeader);
      table.setTableHeader(tableHeader);
      table.setDefaultRenderer(
          String.class,
          new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              if (value != null) {
                value = "\"" + value + "\"";
              }
              return super.getTableCellRendererComponent(
                  table, value, isSelected, hasFocus, row, column);
            }
          });
      final TableCellRenderer booleanRenderer = table.getDefaultRenderer(Boolean.class);
      table.setDefaultRenderer(
          Boolean.class,
          new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              Component c = null;
              if (value == null) {
                c =
                    super.getTableCellRendererComponent(
                        table, " ", isSelected, hasFocus, row, column);
              } else {
                c =
                    booleanRenderer.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
              }
              if (!isSelected) {
                c.setBackground(
                    row % 2 == 0
                        ? UIManager.getColor("Table.background")
                        : JTableX.getTableAlternateRowBackgroundColor());
              }
              return c;
            }
          });
      table.setDefaultRenderer(
          Timestamp.class,
          new DefaultTableCellRenderer() {
            @SuppressWarnings("deprecation")
            @Override
            public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              Component c =
                  super.getTableCellRendererComponent(
                      table, value, isSelected, hasFocus, row, column);
              if (value != null && c instanceof JLabel) {
                Timestamp timestamp = (Timestamp) value;
                String s;
                if (timestamp.getHours() != 0
                    || timestamp.getMinutes() != 0
                    || timestamp.getSeconds() != 0) {
                  s = Utils.formatDateTimeGMT((Timestamp) value);
                } else {
                  s = Utils.formatDateGMT((Timestamp) value);
                }
                ((JLabel) c).setText(s);
              }
              return c;
            }
          });
      table.setDefaultRenderer(
          byte[].class,
          new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(
                JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
              Component c =
                  super.getTableCellRendererComponent(
                      table, value, isSelected, hasFocus, row, column);
              if (value != null && c instanceof JLabel) {
                byte[] bytes = (byte[]) value;
                ((JLabel) c).setText("Blob (" + bytes.length + " bytes)");
              }
              return c;
            }
          });
      table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
      table.setAutoCreateRowSorter(true);
      table
          .getRowSorter()
          .setSortKeys(Arrays.asList(new RowSorter.SortKey(0, SortOrder.ASCENDING)));
      table.setColumnSelectionAllowed(true);
      table.applyMinimumAndPreferredColumnSizes(200);
      resultPane.add(new JScrollPane(table), BorderLayout.CENTER);
      table
          .getSelectionModel()
          .addListSelectionListener(
              new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                  int selectedRowCount = table.getSelectedRowCount();
                  label.setText(
                      " "
                          + resultSetResult.getRowData().length
                          + " rows"
                          + (selectedRowCount == 0
                              ? ""
                              : " - " + selectedRowCount + " selected rows"));
                }
              });
      table.addMouseListener(
          new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
              int row = table.rowAtPoint(e.getPoint());
              int column = table.columnAtPoint(e.getPoint());
              if (!table.isCellSelected(row, column)) {
                table.changeSelection(row, column, false, false);
              }
              maybeShowPopup(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
              maybeShowPopup(e);
            }

            private void maybeShowPopup(MouseEvent e) {
              if (!e.isPopupTrigger()) {
                return;
              }
              boolean isEditable = resultSetResult.isEditable();
              JPopupMenu menu = new JPopupMenu();
              int selectedRowCount = table.getSelectedRowCount();
              int selectedColumnCount = table.getSelectedColumnCount();
              boolean isAddingSeparator = false;
              // Here to add custom menus.
              if (isEditable) {
                if (isAddingSeparator) {
                  isAddingSeparator = false;
                  menu.addSeparator();
                }
                JMenuItem insertNullMenuItem = new JMenuItem("Insert NULL");
                insertNullMenuItem.addActionListener(
                    new ActionListener() {
                      @Override
                      public void actionPerformed(ActionEvent e) {
                        int row = table.getSelectedRow();
                        int column = table.getSelectedColumn();
                        table.setValueAt(null, row, column);
                      }
                    });
                insertNullMenuItem.setEnabled(
                    selectedRowCount == 1
                        && selectedColumnCount == 1
                        && table.convertColumnIndexToModel(table.getSelectedColumn()) != 0);
                menu.add(insertNullMenuItem);
                menu.addSeparator();
                JMenuItem deleteRowMenuItem =
                    new JMenuItem(
                        "Delete " + (selectedRowCount > 1 ? selectedRowCount + " rows" : "row"));
                deleteRowMenuItem.addActionListener(
                    new ActionListener() {
                      @Override
                      public void actionPerformed(ActionEvent e) {
                        int[] selectedRows = table.getSelectedRows();
                        for (int i = selectedRows.length - 1; i >= 0; i--) {
                          selectedRows[i] = table.convertRowIndexToModel(selectedRows[i]);
                        }
                        Arrays.sort(selectedRows);
                        for (int i = selectedRows.length - 1; i >= 0; i--) {
                          int row = selectedRows[i];
                          boolean isSuccess = resultSetResult.deleteRow(row);
                          if (isSuccess) {
                            ((AbstractTableModel) table.getModel()).fireTableRowsDeleted(row, row);
                          }
                        }
                      }
                    });
                deleteRowMenuItem.setEnabled(selectedRowCount > 0);
                menu.add(deleteRowMenuItem);
              }
              if (menu.getComponentCount() > 0) {
                menu.show(e.getComponent(), e.getX(), e.getY());
              }
            }
          });
      final JPanel filterPane = new JPanel(flowLayout);
      filterPane.setOpaque(false);
      final JToggleButton filterToggleButton =
          new JToggleButton(
              new ImageIcon(
                  getClass().getResource("/org/jooq/debug/console/resources/Search16.png")));
      filterToggleButton.setOpaque(false);
      filterToggleButton.setToolTipText(
          "Filter ("
              + KeyEvent.getKeyModifiersText(InputEvent.CTRL_MASK)
              + "+"
              + KeyEvent.getKeyText(KeyEvent.VK_F)
              + ")");
      filterToggleButton.setMargin(new Insets(0, 0, 0, 0));
      filterPane.add(filterToggleButton);
      final JTextField searchField = new JTextField(7);
      searchField
          .getDocument()
          .addDocumentListener(
              new DocumentListener() {
                @Override
                public void removeUpdate(DocumentEvent e) {
                  adjustFilter();
                }

                @Override
                public void insertUpdate(DocumentEvent e) {
                  adjustFilter();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                  adjustFilter();
                }

                private void adjustFilter() {
                  setFilter(table, searchField.getText());
                }
              });
      searchField.setVisible(false);
      filterPane.add(searchField);
      filterToggleButton.addItemListener(
          new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
              boolean isActive = e.getStateChange() == ItemEvent.SELECTED;
              searchField.setVisible(isActive);
              if (isActive) {
                searchField.requestFocus();
              } else {
                searchField.setText("");
                table.requestFocus();
              }
              filterPane.revalidate();
              filterPane.repaint();
            }
          });
      searchField.addKeyListener(
          new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                e.consume();
                filterToggleButton.setSelected(false);
              } else if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()) {
                filterToggleButton.setSelected(false);
              }
            }
          });
      table.addKeyListener(
          new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()) {
                e.consume();
                filterToggleButton.setSelected(true);
                searchField.requestFocus();
                searchField.selectAll();
              }
            }
          });
      statusPane.add(filterPane);
    }
    JPanel southResultPanel = new JPanel(new BorderLayout());
    southResultPanel.setOpaque(false);
    if (isUsingMaxRowCount && rowCount == MAX_ROW_COUNT) {
      label.setForeground(Color.RED);
    }
    statusPane.add(label);
    southResultPanel.add(statusPane, BorderLayout.WEST);
    southResultPanel.add(
        new JLabel(
            Utils.formatDuration(duration)
                + " - "
                + Utils.formatDuration(resultSetResult.getResultSetParsingDuration())),
        BorderLayout.EAST);
    resultPane.add(southResultPanel, BorderLayout.SOUTH);
    southResultPanel.setToolTipText(sql);
    resultPane.revalidate();
    resultPane.repaint();
  }
コード例 #9
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
  public void keyPressed(KeyEvent e) {
    // if (e.isConsumed()) return;
    int keyCode = e.getKeyCode();
    IJ.setKeyDown(keyCode);
    hotkey = false;
    if (keyCode == KeyEvent.VK_CONTROL || keyCode == KeyEvent.VK_SHIFT) return;
    char keyChar = e.getKeyChar();
    int flags = e.getModifiers();
    if (IJ.debugMode)
      IJ.log(
          "keyPressed: code="
              + keyCode
              + " ("
              + KeyEvent.getKeyText(keyCode)
              + "), char=\""
              + keyChar
              + "\" ("
              + (int) keyChar
              + "), flags="
              + KeyEvent.getKeyModifiersText(flags));
    boolean shift = (flags & KeyEvent.SHIFT_MASK) != 0;
    boolean control = (flags & KeyEvent.CTRL_MASK) != 0;
    boolean alt = (flags & KeyEvent.ALT_MASK) != 0;
    boolean meta = (flags & KeyEvent.META_MASK) != 0;
    String cmd = null;
    ImagePlus imp = WindowManager.getCurrentImage();
    boolean isStack = (imp != null) && (imp.getStackSize() > 1);

    if (imp != null
        && !control
        && ((keyChar >= 32 && keyChar <= 255) || keyChar == '\b' || keyChar == '\n')) {
      Roi roi = imp.getRoi();
      if (roi instanceof TextRoi) {
        if ((flags & KeyEvent.META_MASK) != 0 && IJ.isMacOSX()) return;
        if (alt) {
          switch (keyChar) {
            case 'u':
            case 'm':
              keyChar = IJ.micronSymbol;
              break;
            case 'A':
              keyChar = IJ.angstromSymbol;
              break;
            default:
          }
        }
        ((TextRoi) roi).addChar(keyChar);
        return;
      }
    }

    // Handle one character macro shortcuts
    if (!control && !meta) {
      Hashtable macroShortcuts = Menus.getMacroShortcuts();
      if (macroShortcuts.size() > 0) {
        if (shift) cmd = (String) macroShortcuts.get(new Integer(keyCode + 200));
        else cmd = (String) macroShortcuts.get(new Integer(keyCode));
        if (cmd != null) {
          // MacroInstaller.runMacroCommand(cmd);
          commandName = cmd;
          MacroInstaller.runMacroShortcut(cmd);
          return;
        }
      }
    }

    if ((!Prefs.requireControlKey || control || meta) && keyChar != '+') {
      Hashtable shortcuts = Menus.getShortcuts();
      if (shift) cmd = (String) shortcuts.get(new Integer(keyCode + 200));
      else cmd = (String) shortcuts.get(new Integer(keyCode));
    }

    if (cmd == null) {
      switch (keyChar) {
        case '<':
        case ',':
          if (isStack) cmd = "Previous Slice [<]";
          break;
        case '>':
        case '.':
        case ';':
          if (isStack) cmd = "Next Slice [>]";
          break;
        case '+':
        case '=':
          cmd = "In [+]";
          break;
        case '-':
          cmd = "Out [-]";
          break;
        case '/':
          cmd = "Reslice [/]...";
          break;
        default:
      }
    }

    if (cmd == null) {
      switch (keyCode) {
        case KeyEvent.VK_TAB:
          WindowManager.putBehind();
          return;
        case KeyEvent.VK_BACK_SPACE: // delete
          if (deleteOverlayRoi(imp)) return;
          cmd = "Clear";
          hotkey = true;
          break;
          // case KeyEvent.VK_BACK_SLASH: cmd=IJ.altKeyDown()?"Animation Options...":"Start
          // Animation"; break;
        case KeyEvent.VK_EQUALS:
          cmd = "In [+]";
          break;
        case KeyEvent.VK_MINUS:
          cmd = "Out [-]";
          break;
        case KeyEvent.VK_SLASH:
        case 0xbf:
          cmd = "Reslice [/]...";
          break;
        case KeyEvent.VK_COMMA:
        case 0xbc:
          if (isStack) cmd = "Previous Slice [<]";
          break;
        case KeyEvent.VK_PERIOD:
        case 0xbe:
          if (isStack) cmd = "Next Slice [>]";
          break;
        case KeyEvent.VK_LEFT:
        case KeyEvent.VK_RIGHT:
        case KeyEvent.VK_UP:
        case KeyEvent.VK_DOWN: // arrow keys
          if (imp == null) return;
          Roi roi = imp.getRoi();
          if (IJ.shiftKeyDown() && imp == Orthogonal_Views.getImage()) return;
          boolean stackKey = imp.getStackSize() > 1 && (roi == null || IJ.shiftKeyDown());
          boolean zoomKey = roi == null || IJ.shiftKeyDown() || IJ.controlKeyDown();
          if (stackKey && keyCode == KeyEvent.VK_RIGHT) cmd = "Next Slice [>]";
          else if (stackKey && keyCode == KeyEvent.VK_LEFT) cmd = "Previous Slice [<]";
          else if (zoomKey
              && keyCode == KeyEvent.VK_DOWN
              && !ignoreArrowKeys(imp)
              && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "Out [-]";
          else if (zoomKey
              && keyCode == KeyEvent.VK_UP
              && !ignoreArrowKeys(imp)
              && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "In [+]";
          else if (roi != null) {
            if ((flags & KeyEvent.ALT_MASK) != 0) roi.nudgeCorner(keyCode);
            else roi.nudge(keyCode);
            return;
          }
          break;
        case KeyEvent.VK_ESCAPE:
          abortPluginOrMacro(imp);
          return;
        case KeyEvent.VK_ENTER:
          WindowManager.toFront(this);
          return;
        default:
          break;
      }
    }

    if (cmd != null && !cmd.equals("")) {
      commandName = cmd;
      if (cmd.equals("Fill") || cmd.equals("Draw")) hotkey = true;
      if (cmd.charAt(0) == MacroInstaller.commandPrefix) MacroInstaller.runMacroShortcut(cmd);
      else {
        doCommand(cmd);
        keyPressedTime = System.currentTimeMillis();
        lastKeyCommand = cmd;
      }
    }
  }
コード例 #10
0
ファイル: HelpOverlay.java プロジェクト: vohoaiviet/metanet
 public void registerKeyStroke(KeyStroke keyStroke, String description) {
   String modifiersText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers());
   String keyText = KeyEvent.getKeyText(keyStroke.getKeyCode());
   keyboardEntries.add(
       (modifiersText.length() != 0 ? modifiersText + " " : "") + keyText + ": " + description);
 }
コード例 #11
0
  /**
   * This method is not being used to paint menu item since 6.0 This code left for compatibility
   * only. Do not use or override it, this will not cause any visible effect.
   */
  public static void paintMenuItem(
      Graphics g,
      JComponent c,
      Icon checkIcon,
      Icon arrowIcon,
      Color background,
      Color foreground,
      int defaultTextIconGap) {

    JMenuItem b = (JMenuItem) c;
    ButtonModel model = b.getModel();

    Dimension size = b.getSize();
    Insets i = c.getInsets();

    Rectangle viewRect = new Rectangle(size);

    viewRect.x += i.left;
    viewRect.y += i.top;
    viewRect.width -= (i.right + viewRect.x);
    viewRect.height -= (i.bottom + viewRect.y);

    Rectangle iconRect = new Rectangle();
    Rectangle textRect = new Rectangle();
    Rectangle acceleratorRect = new Rectangle();
    Rectangle checkRect = new Rectangle();
    Rectangle arrowRect = new Rectangle();

    Font holdf = g.getFont();
    Font f = c.getFont();
    g.setFont(f);
    FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, f);
    FontMetrics fmAccel =
        SwingUtilities2.getFontMetrics(c, g, UIManager.getFont("MenuItem.acceleratorFont"));

    if (c.isOpaque()) {
      if (model.isArmed() || (c instanceof JMenu && model.isSelected())) {
        g.setColor(background);
      } else {
        g.setColor(c.getBackground());
      }
      g.fillRect(0, 0, size.width, size.height);
    }

    // get Accelerator text
    KeyStroke accelerator = b.getAccelerator();
    String acceleratorText = "";
    if (accelerator != null) {
      int modifiers = accelerator.getModifiers();
      if (modifiers > 0) {
        acceleratorText = KeyEvent.getKeyModifiersText(modifiers);
        acceleratorText += "+";
      }
      acceleratorText += KeyEvent.getKeyText(accelerator.getKeyCode());
    }

    // layout the text and icon
    String text =
        layoutMenuItem(
            c,
            fm,
            b.getText(),
            fmAccel,
            acceleratorText,
            b.getIcon(),
            checkIcon,
            arrowIcon,
            b.getVerticalAlignment(),
            b.getHorizontalAlignment(),
            b.getVerticalTextPosition(),
            b.getHorizontalTextPosition(),
            viewRect,
            iconRect,
            textRect,
            acceleratorRect,
            checkRect,
            arrowRect,
            b.getText() == null ? 0 : defaultTextIconGap,
            defaultTextIconGap);

    // Paint the Check
    Color holdc = g.getColor();
    if (checkIcon != null) {
      if (model.isArmed() || (c instanceof JMenu && model.isSelected())) g.setColor(foreground);
      checkIcon.paintIcon(c, g, checkRect.x, checkRect.y);
      g.setColor(holdc);
    }

    // Paint the Icon
    if (b.getIcon() != null) {
      Icon icon;
      if (!model.isEnabled()) {
        icon = (Icon) b.getDisabledIcon();
      } else if (model.isPressed() && model.isArmed()) {
        icon = (Icon) b.getPressedIcon();
        if (icon == null) {
          // Use default icon
          icon = (Icon) b.getIcon();
        }
      } else {
        icon = (Icon) b.getIcon();
      }

      if (icon != null) {
        icon.paintIcon(c, g, iconRect.x, iconRect.y);
      }
    }

    // Draw the Text
    if (text != null && !text.equals("")) {
      // Once BasicHTML becomes public, use BasicHTML.propertyKey
      // instead of the hardcoded string below!
      View v = (View) c.getClientProperty("html");
      if (v != null) {
        v.paint(g, textRect);
      } else {
        int mnemIndex = b.getDisplayedMnemonicIndex();

        if (!model.isEnabled()) {
          // *** paint the text disabled
          g.setColor(b.getBackground().brighter());
          SwingUtilities2.drawStringUnderlineCharAt(
              b, g, text, mnemIndex, textRect.x, textRect.y + fmAccel.getAscent());
          g.setColor(b.getBackground().darker());
          SwingUtilities2.drawStringUnderlineCharAt(
              b, g, text, mnemIndex, textRect.x - 1, textRect.y + fmAccel.getAscent() - 1);

        } else {
          // *** paint the text normally
          if (model.isArmed() || (c instanceof JMenu && model.isSelected())) {
            g.setColor(foreground);
          } else {
            g.setColor(b.getForeground());
          }
          SwingUtilities2.drawStringUnderlineCharAt(
              b, g, text, mnemIndex, textRect.x, textRect.y + fm.getAscent());
        }
      }
    }

    // Draw the Accelerator Text
    if (acceleratorText != null && !acceleratorText.equals("")) {

      // Get the maxAccWidth from the parent to calculate the offset.
      int accOffset = 0;
      Container parent = b.getParent();
      if (parent != null && parent instanceof JComponent) {
        JComponent p = (JComponent) parent;
        Integer maxValueInt = (Integer) p.getClientProperty(MotifGraphicsUtils.MAX_ACC_WIDTH);
        int maxValue = maxValueInt != null ? maxValueInt.intValue() : acceleratorRect.width;

        // Calculate the offset, with which the accelerator texts will be drawn with.
        accOffset = maxValue - acceleratorRect.width;
      }

      g.setFont(UIManager.getFont("MenuItem.acceleratorFont"));
      if (!model.isEnabled()) {
        // *** paint the acceleratorText disabled
        g.setColor(b.getBackground().brighter());
        SwingUtilities2.drawString(
            c,
            g,
            acceleratorText,
            acceleratorRect.x - accOffset,
            acceleratorRect.y + fm.getAscent());
        g.setColor(b.getBackground().darker());
        SwingUtilities2.drawString(
            c,
            g,
            acceleratorText,
            acceleratorRect.x - accOffset - 1,
            acceleratorRect.y + fm.getAscent() - 1);
      } else {
        // *** paint the acceleratorText normally
        if (model.isArmed() || (c instanceof JMenu && model.isSelected())) {
          g.setColor(foreground);
        } else {
          g.setColor(b.getForeground());
        }
        SwingUtilities2.drawString(
            c,
            g,
            acceleratorText,
            acceleratorRect.x - accOffset,
            acceleratorRect.y + fmAccel.getAscent());
      }
    }

    // Paint the Arrow
    if (arrowIcon != null) {
      if (model.isArmed() || (c instanceof JMenu && model.isSelected())) g.setColor(foreground);
      if (!(b.getParent() instanceof JMenuBar)) arrowIcon.paintIcon(c, g, arrowRect.x, arrowRect.y);
    }

    g.setColor(holdc);
    g.setFont(holdf);
  }
コード例 #12
0
ファイル: MenuUtils.java プロジェクト: juliusse/freeplane
 public static String formatKeyStroke(final KeyStroke keyStroke) {
   final String keyModifiersText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers());
   final String keyText = KeyEvent.getKeyText(keyStroke.getKeyCode());
   return keyModifiersText.length() == 0 ? keyText : keyModifiersText + "+" + keyText;
 }
コード例 #13
0
ファイル: WebHotkeyLabel.java プロジェクト: ExPixel/weblaf
 public WebHotkeyLabel(final int keyCode, final int modifiers) {
   super(KeyEvent.getKeyModifiersText(modifiers) + "+" + KeyEvent.getKeyText(keyCode));
   initializeView();
 }