public void loadBindingMap(InputMap im, ActionMap am) { results.append("Bound Actions\n"); String unboundActions = ""; String unboundInputKeys = ""; Hashtable mi = buildReverseMap(im); Object[] k = am.allKeys(); if (k != null) { for (int i = 0; i < k.length; i++) { if (mi.containsKey(k[i])) { results.append(" " + getActionName(k[i])); results.append(";" + mi.get(k[i]) + "\n"); } else { unboundActions += (" " + getActionName(k[i]) + "\n"); } } results.append("\nUnbound Actions\n\n"); results.append(unboundActions); } results.append("\nUnbound InputMap Entries\n"); k = im.allKeys(); if (k != null) { for (int i = 0; i < k.length; i++) { KeyStroke key = (KeyStroke) k[i]; Object actionKey = im.get(key); if (am.get(actionKey) == null) { results.append(" " + im.get((KeyStroke) k[i]) + ": " + k[i] + "\n"); } } } }
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); }
/** * Set up key bindings and focus listener for the FieldEditor. * * @param component */ public void setupJTextComponent(final JComponent component, final AutoCompleteListener acl) { // Here we add focus listeners to the component. The funny code is because we need // to guarantee that the AutoCompleteListener - if used - is called before fieldListener // on a focus lost event. The AutoCompleteListener is responsible for removing any // current suggestion when focus is lost, and this must be done before fieldListener // stores the current edit. Swing doesn't guarantee the order of execution of event // listeners, so we handle this by only adding the AutoCompleteListener and telling // it to call fieldListener afterwards. If no AutoCompleteListener is used, we // add the fieldListener normally. if (acl != null) { component.addKeyListener(acl); component.addFocusListener(acl); acl.setNextFocusListener(fieldListener); } else component.addFocusListener(fieldListener); InputMap im = component.getInputMap(JComponent.WHEN_FOCUSED); ActionMap am = component.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); try { HashSet<AWTKeyStroke> keys = new HashSet<AWTKeyStroke>( component.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)); keys.clear(); keys.add(AWTKeyStroke.getAWTKeyStroke("pressed TAB")); component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, keys); keys = new HashSet<AWTKeyStroke>( component.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)); keys.clear(); keys.add(KeyStroke.getKeyStroke("shift pressed TAB")); component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, keys); } catch (Throwable t) { System.err.println(t); } }
protected void installKeyboardActions() { super.installKeyboardActions(); ActionMap map = SwingUtilities.getUIActionMap(getComponent()); if (map != null && map.get(DefaultEditorKit.selectWordAction) != null) { Action a = map.get(DefaultEditorKit.selectLineAction); if (a != null) { map.put(DefaultEditorKit.selectWordAction, a); } } }
private void initActions() { @NonNls InputMap inputMap = getInputMap(WHEN_FOCUSED); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "moveFocusDown"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "moveFocusUp"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "collapse"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "expand"); @NonNls ActionMap actionMap = getActionMap(); actionMap.put("moveFocusDown", new MoveFocusAction(true)); actionMap.put("moveFocusUp", new MoveFocusAction(false)); actionMap.put("collapse", new ExpandAction(false)); actionMap.put("expand", new ExpandAction(true)); }
// --------> // original code: // ftp://ftp.oreilly.de/pub/examples/english_examples/jswing2/code/goodies/Mapper.java // modified by terai // private Hashtable<Object, ArrayList<KeyStroke>> buildReverseMap(InputMap im) { // Hashtable<Object, ArrayList<KeyStroke>> h = new Hashtable<>(); // if (Objects.isNull(im.allKeys())) { // return h; // } // for (KeyStroke ks: im.allKeys()) { // Object name = im.get(ks); // if (h.containsKey(name)) { // h.get(name).add(ks); // } else { // ArrayList<KeyStroke> keylist = new ArrayList<>(); // keylist.add(ks); // h.put(name, keylist); // } // } // return h; // } private void loadBindingMap(Integer focusType, InputMap im, ActionMap am) { if (Objects.isNull(im.allKeys())) { return; } ActionMap tmpAm = new ActionMap(); for (Object actionMapKey : am.allKeys()) { tmpAm.put(actionMapKey, am.get(actionMapKey)); } for (KeyStroke ks : im.allKeys()) { Object actionMapKey = im.get(ks); Action action = am.get(actionMapKey); if (Objects.isNull(action)) { model.addBinding(new Binding(focusType, "____" + actionMapKey.toString(), ks.toString())); } else { model.addBinding(new Binding(focusType, actionMapKey.toString(), ks.toString())); } tmpAm.remove(actionMapKey); } if (Objects.isNull(tmpAm.allKeys())) { return; } for (Object actionMapKey : tmpAm.allKeys()) { model.addBinding(new Binding(focusType, actionMapKey.toString(), "")); } }
protected void setActive(Component component, boolean active) { if (component instanceof Tile) { Tile tile = (Tile) component; if (active) { tile.addTiledView(_points); tile.addMouseListener(_ml); tile.addMouseWheelListener(_mwl); InputMap im = tile.getInputMap(); ActionMap am = tile.getActionMap(); im.put(KS_BACK_SPACE, "backspace"); im.put(KS_UP, "up"); im.put(KS_DOWN, "down"); am.put("backspace", _bsa); am.put("up", _uaa); am.put("down", _daa); } else { tile.removeTiledView(_points); tile.removeMouseListener(_ml); tile.removeMouseWheelListener(_mwl); InputMap im = tile.getInputMap(); ActionMap am = tile.getActionMap(); im.remove(KS_BACK_SPACE); im.remove(KS_UP); im.remove(KS_DOWN); am.remove("backspace"); am.remove("up"); am.remove("down"); } } }
private void initActions() { ActionMap map = getActionMap(); map.put("selectPreviousRow", new MoveFocusAction(map.get("selectPreviousRow"), false)); map.put("selectNextRow", new MoveFocusAction(map.get("selectNextRow"), true)); map.put( "selectPreviousColumn", new MoveFocusAction(new ChangeColumnAction(map.get("selectPreviousColumn"), false), false)); map.put( "selectNextColumn", new MoveFocusAction(new ChangeColumnAction(map.get("selectNextColumn"), true), true)); }
static JComponent createMenuComponent(JComponent menu, ActionMap actionMap, List actions) { MenuAdapter menuAdapter = new MenuAdapter(menu); for (Object menuElement : actions) { if (MenuFactory.SEPARATOR.equals(menuElement)) { menuAdapter.addSeparator(); } else if (menuElement instanceof Object[]) { Object[] items = (Object[]) menuElement; if (items.length > 1) { JMenu subMenu = new JMenu(items[0].toString()); List<Object> keys = Arrays.asList(items).subList(1, items.length); createMenuComponent(subMenu, actionMap, keys); if (subMenu.getMenuComponents().length > 0) { menuAdapter.addSubMenu(subMenu); } } } else if (menuElement instanceof List) { List items = (List) menuElement; if (items.size() > 1) { JMenu subMenu = new JMenu(items.get(0).toString()); List<List> keys = Arrays.asList(items).subList(1, items.size()); createMenuComponent(subMenu, actionMap, keys); if (subMenu.getMenuComponents().length > 0) { menuAdapter.addSubMenu(subMenu); } } } else { Action action = actionMap.get(menuElement); if (action != null) { menuAdapter.add(action); } } } return trim(menuAdapter); }
ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); Action refreshAction = new UIAction(FilePane.ACTION_REFRESH) { public void actionPerformed(ActionEvent evt) { getFileChooser().rescanCurrentDirectory(); } }; map.put(FilePane.ACTION_APPROVE_SELECTION, getApproveSelectionAction()); map.put(FilePane.ACTION_CANCEL, getCancelSelectionAction()); map.put(FilePane.ACTION_REFRESH, refreshAction); map.put(FilePane.ACTION_CHANGE_TO_PARENT_DIRECTORY, getChangeToParentDirectoryAction()); return map; }
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); }
public final void registerAction( @NonNls String aActionName, int aKeyCode, @JdkConstants.InputEventMask int aModifier, Action aAction) { myInputMap.put(KeyStroke.getKeyStroke(aKeyCode, aModifier), aActionName); myActionMap.put(aActionName, aAction); }
void initActions() { // TODO: copied from CloneableEditor - this has no effect ActionMap paneMap = editorPane.getActionMap(); ActionMap am = getActionMap(); am.setParent(paneMap); paneMap.put(DefaultEditorKit.cutAction, getAction(DefaultEditorKit.cutAction)); paneMap.put(DefaultEditorKit.copyAction, getAction(DefaultEditorKit.copyAction)); paneMap.put("delete", getAction(DefaultEditorKit.deleteNextCharAction)); // NOI18N paneMap.put(DefaultEditorKit.pasteAction, getAction(DefaultEditorKit.pasteAction)); }
private boolean proceedKeyEvent(KeyEvent event, KeyStroke stroke) { if (myInputMap.get(stroke) != null) { final Action action = myActionMap.get(myInputMap.get(stroke)); if (action != null && action.isEnabled()) { action.actionPerformed( new ActionEvent( getContent(), event.getID(), "", event.getWhen(), event.getModifiers())); return true; } } return false; }
public void loadActionMap(ActionMap am, String indent) { Object[] k = am.allKeys(); if (k == null) { results.append(indent + "No ActionMap defined\n"); } else { results.append(indent + "\nActionMap (" + k.length + " local keys)\n"); } if (k != null) { for (int i = 0; i < k.length; i++) { results.append(indent + " Action: " + k[i] + "\n"); } } }
// {{{ _preprocessKeyEvent() method private KeyEvent _preprocessKeyEvent(KeyEvent evt) { if (view.isClosed()) return null; Component focusOwner = view.getFocusOwner(); if (focusOwner instanceof JComponent) { JComponent comp = (JComponent) focusOwner; InputMap map = comp.getInputMap(); ActionMap am = comp.getActionMap(); if (map != null && am != null && comp.isEnabled()) { KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(evt); Object binding = map.get(keyStroke); if (binding != null && am.get(binding) != null) { return null; } } } if (focusOwner instanceof JTextComponent) { // fix for the bug where key events in JTextComponents // inside views are also handled by the input handler if (evt.getID() == KeyEvent.KEY_PRESSED) { switch (evt.getKeyCode()) { case KeyEvent.VK_ENTER: case KeyEvent.VK_TAB: case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_SPACE: return null; } } } if (evt.isConsumed()) return null; if (Debug.DUMP_KEY_EVENTS) { Log.log(Log.DEBUG, this, "Key event (preprocessing) : " + AbstractInputHandler.toString(evt)); } return KeyEventWorkaround.processKeyEvent(evt); } // }}}
private void buildGUI() { setLayout(new BorderLayout()); _tree = new PsiViewerTree(_model); _tree.getSelectionModel().addTreeSelectionListener(_treeSelectionListener); ActionMap actionMap = _tree.getActionMap(); actionMap.put( "EditSource", new AbstractAction("EditSource") { public void actionPerformed(ActionEvent e) { debug("key typed " + e); if (getSelectedElement() == null) return; Editor editor = _caretMover.openInEditor(getSelectedElement()); selectElementAtCaret(editor, TREE_SELECTION_CHANGED); editor.getContentComponent().requestFocus(); } }); InputMap inputMap = _tree.getInputMap(); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0, true), "EditSource"); _propertyPanel = new PropertySheetPanel(); _splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JBScrollPane(_tree), _propertyPanel) { public void setDividerLocation(int location) { debug( "Divider location changed to " + location + " component below " + (getRightComponent().isVisible() ? "visible" : "not visible")); if (getRightComponent().isVisible()) _projectComponent.setSplitDividerLocation(location); super.setDividerLocation(location); } }; _splitPane.setDividerLocation(_projectComponent.getSplitDividerLocation()); add(_splitPane); }
/** * Registers the keystroke of the given action as "command" of the given component. * * <p>This code is based on the Sulky-tools, found at <http://github.com/huxi/sulky>. * * @param aComponent the component that should react on the keystroke, cannot be <code>null</code> * ; * @param aAction the action of the keystroke, cannot be <code>null</code>; * @param aCommandName the name of the command to register the keystore under. */ public static void registerKeystroke( final JComponent aComponent, final Action aAction, final String aCommandName) { final KeyStroke keyStroke = (KeyStroke) aAction.getValue(Action.ACCELERATOR_KEY); if (keyStroke == null) { return; } InputMap inputMap = aComponent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = aComponent.getActionMap(); inputMap.put(keyStroke, aCommandName); actionMap.put(aCommandName, aAction); inputMap = aComponent.getInputMap(JComponent.WHEN_FOCUSED); Object value = inputMap.get(keyStroke); if (value != null) { inputMap.put(keyStroke, aCommandName); } inputMap = aComponent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); value = inputMap.get(keyStroke); if (value != null) { inputMap.put(keyStroke, aCommandName); } }
/** * 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"); } }); }
/** * A text editor created for my own use. Credit to * http://forum.codecall.net/topic/49721-simple-text-editor/ * * @author Corey Hickson * @version 0.1 */ public class CoreyTextEditor extends JFrame { // Variables to help initialize the text editor private JTextArea area = new JTextArea(20, 120); private JFileChooser dialog = new JFileChooser(System.getProperty("user.dir")); private String currentFile = "Untitled"; private boolean changed = false; /** Constructor to create the frame and its components */ public CoreyTextEditor() { // Create a scroll pane area.setFont(new Font("Monospaced", Font.PLAIN, 12)); JScrollPane scroll = new JScrollPane( area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); add(scroll, BorderLayout.CENTER); // Adds the system default look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) { e.printStackTrace(); } // Create a menu bar JMenuBar JMB = new JMenuBar(); setJMenuBar(JMB); JMenu file = new JMenu("File"); JMenu edit = new JMenu("Edit"); JMB.add(file); JMB.add(edit); // Finishing our menu bar file.add(New); file.add(Open); file.add(Save); file.add(SaveAs); file.addSeparator(); file.add(Quit); edit.add(Cut); edit.add(Copy); edit.add(Paste); edit.getItem(0).setText("Cut"); edit.getItem(0).setIcon(new ImageIcon("cut.gif")); edit.getItem(1).setText("Copy"); edit.getItem(1).setIcon(new ImageIcon("copy.gif")); edit.getItem(2).setText("Paste"); edit.getItem(2).setIcon(new ImageIcon("paste.gif")); // Time to make a toolbar! JToolBar tool = new JToolBar(); add(tool, BorderLayout.NORTH); tool.add(New); tool.add(Open); tool.add(Save); tool.addSeparator(); JButton cut = tool.add(Cut); JButton cop = tool.add(Copy); JButton pas = tool.add(Paste); cut.setText(null); cut.setIcon(new ImageIcon("cut.gif")); cop.setText(null); cop.setIcon(new ImageIcon("copy.gif")); pas.setText(null); pas.setIcon(new ImageIcon("paste.gif")); Save.setEnabled(false); SaveAs.setEnabled(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); pack(); /* KeyListener to change Save and SaveAs */ KeyListener k1 = new KeyAdapter() { public void keyPressed(KeyEvent e) { changed = true; Save.setEnabled(true); SaveAs.setEnabled(true); } }; area.addKeyListener(k1); setTitle(currentFile + " - CoreyTextEditor"); setVisible(true); } Action New = new AbstractAction("New", new ImageIcon("new.gif")) { public void actionPerformed(ActionEvent e) { saveOld(); area.setText(""); currentFile = "Untitled"; setTitle(currentFile + " - CoreyTextEditor"); changed = false; Save.setEnabled(false); SaveAs.setEnabled(false); } }; Action Open = new AbstractAction("Open", new ImageIcon("open.gif")) { public void actionPerformed(ActionEvent e) { saveOld(); if (dialog.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { readInFile(dialog.getSelectedFile().getAbsolutePath()); } SaveAs.setEnabled(true); } }; Action Save = new AbstractAction("Save", new ImageIcon("save.gif")) { public void actionPerformed(ActionEvent e) { if (!currentFile.equals("Untitled")) { saveFile(currentFile); } else { saveFileAs(); } } }; Action SaveAs = new AbstractAction("Save as...") { public void actionPerformed(ActionEvent e) { saveFileAs(); } }; Action Quit = new AbstractAction("Quit") { public void actionPerformed(ActionEvent e) { saveOld(); System.exit(0); } }; ActionMap m = area.getActionMap(); Action Cut = m.get(DefaultEditorKit.cutAction); Action Copy = m.get(DefaultEditorKit.copyAction); Action Paste = m.get(DefaultEditorKit.pasteAction); private void saveFileAs() { if (dialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { saveFile(dialog.getSelectedFile().getAbsolutePath()); } } private void saveOld() { if (changed) { if (JOptionPane.showConfirmDialog( this, "Would you like to save " + currentFile + " ?", "Save", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { saveFile(currentFile); } } } private void readInFile(String fileName) { try { FileReader r = new FileReader(fileName); area.read(r, null); r.close(); currentFile = fileName; setTitle(currentFile + " - CoreyTextEditor"); changed = false; } catch (IOException e) { Toolkit.getDefaultToolkit().beep(); JOptionPane.showMessageDialog(this, "Editor can't find the file called " + fileName); } } private void saveFile(String fileName) { try { FileWriter w = new FileWriter(fileName); area.write(w); w.close(); currentFile = fileName; setTitle(currentFile + " - CoreyTextEditor"); changed = false; Save.setEnabled(false); } catch (IOException e) { // No handling done here } } public static void main(String[] args) { new CoreyTextEditor(); } }
public void teclasAtalhos() { // BOTAO EXCLUIR LOTE Action actionExcluir = new AbstractAction() { @Override public void actionPerformed(ActionEvent arg0) { // simula o click no botão jBExcluirLote.grabFocus(); jBExcluirLote.doClick(); } }; // Associa o listener com a tecla f2 para que seja disparado toda vez, mesmo quando o foco não // está no botão KeyStroke keyStrokeExcluir = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0); String actionNameExcluir = "TECLA_F1"; InputMap inputMapExcluir = jBExcluirLote.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMapExcluir.put(keyStrokeExcluir, actionNameExcluir); ActionMap actionMapExcluir = jBExcluirLote.getActionMap(); actionMapExcluir.put(actionNameExcluir, actionExcluir); // BOTAO SAIR TELA // Action para o botao fechar Action actionTeclaFechar = new AbstractAction() { @Override public void actionPerformed(ActionEvent arg0) { // simula o click no botão jBFechar.grabFocus(); jBFechar.doClick(); } }; // Associa o listener com a tecla esc para que seja disparado toda vez, mesmo quando o foco não // está no botão KeyStroke keyStrokeFechar = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); String actionNameFechar = "TECLA_ESC"; InputMap inputMapFechar = jBFechar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMapFechar.put(keyStrokeFechar, actionNameFechar); ActionMap actionMapFechar = jBFechar.getActionMap(); actionMapFechar.put(actionNameFechar, actionTeclaFechar); // BOTAO ATUALIZAR // Action para o botao Atualizar Action actionTeclaAtualizar = new AbstractAction() { @Override public void actionPerformed(ActionEvent arg0) { // simula o click no botão jBAtualizar.grabFocus(); jBAtualizar.doClick(); } }; // Associa o listener com a tecla f6 para que seja disparado toda vez, mesmo quando o foco não // está no botão KeyStroke keyStrokeAtualizar = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0); String actionNameAtualizar = "TECLA_F6"; InputMap inputMapAtualizar = jBAtualizar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMapAtualizar.put(keyStrokeAtualizar, actionNameAtualizar); ActionMap actionMapAtualizar = jBAtualizar.getActionMap(); actionMapAtualizar.put(actionNameAtualizar, actionTeclaAtualizar); // BOTAO MOSTRAR TODOS // Action para o botao exibir todos Action actionTeclaExibirTodos = new AbstractAction() { @Override public void actionPerformed(ActionEvent arg0) { // simula o click no botão jBMostrarTodos.grabFocus(); jBMostrarTodos.doClick(); } }; // Associa o listener com a tecla f4 para que seja disparado toda vez, mesmo quando o foco não // está no botão KeyStroke keyStrokeExibirTodos = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0); String actionNameExibirTodos = "TECLA_F5"; InputMap inputMapExibirTodos = jBMostrarTodos.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMapExibirTodos.put(keyStrokeExibirTodos, actionNameExibirTodos); ActionMap actionMapExibirTodos = jBMostrarTodos.getActionMap(); actionMapExibirTodos.put(actionNameExibirTodos, actionTeclaExibirTodos); }
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); } }
/** Add the given input/action maps to the spinner. */ void addSpinnerMaps(InputMap sim, ActionMap sam) { sim.setParent(spinner.getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)); spinner.setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, sim); sam.setParent(spinner.getActionMap()); spinner.setActionMap(sam); }
/** * 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); } }
private ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); map.put("selectNextColumn", new NavigationalAction(1, 0, false, false, false)); map.put("selectPreviousColumn", new NavigationalAction(-1, 0, false, false, false)); map.put("selectNextRow", new NavigationalAction(0, 1, false, false, false)); map.put("selectPreviousRow", new NavigationalAction(0, -1, false, false, false)); map.put("selectNextColumnExtendSelection", new NavigationalAction(1, 0, false, true, false)); map.put( "selectPreviousColumnExtendSelection", new NavigationalAction(-1, 0, false, true, false)); map.put("selectNextRowExtendSelection", new NavigationalAction(0, 1, false, true, false)); map.put("selectPreviousRowExtendSelection", new NavigationalAction(0, -1, false, true, false)); map.put("scrollUpChangeSelection", new PagingAction(false, false, true, false)); map.put("scrollDownChangeSelection", new PagingAction(false, true, true, false)); map.put("selectFirstColumn", new PagingAction(false, false, false, true)); map.put("selectLastColumn", new PagingAction(false, true, false, false)); map.put("scrollUpExtendSelection", new PagingAction(true, false, true, false)); map.put("scrollDownExtendSelection", new PagingAction(true, true, true, false)); map.put("selectFirstColumnExtendSelection", new PagingAction(true, false, false, true)); map.put("selectLastColumnExtendSelection", new PagingAction(true, true, false, false)); map.put("selectFirstRow", new PagingAction(false, false, true, true)); map.put("selectLastRow", new PagingAction(false, true, true, true)); map.put("selectFirstRowExtendSelection", new PagingAction(true, false, true, true)); map.put("selectLastRowExtendSelection", new PagingAction(true, true, true, true)); map.put("selectNextColumnCell", new NavigationalAction(1, 0, true, false, true)); map.put("selectPreviousColumnCell", new NavigationalAction(-1, 0, true, false, true)); map.put("selectNextRowCell", new NavigationalAction(0, 1, true, false, true)); map.put("selectPreviousRowCell", new NavigationalAction(0, -1, true, false, true)); map.put("selectAll", new SelectAllAction()); map.put("cancel", new CancelEditingAction()); map.put("startEditing", new StartEditingAction()); map.put("scrollLeftChangeSelection", new PagingAction(false, false, false, false)); map.put("scrollRightChangeSelection", new PagingAction(false, true, false, false)); map.put("scrollLeftExtendSelection", new PagingAction(true, false, false, false)); map.put("scrollRightExtendSelection", new PagingAction(true, true, false, false)); return map; }
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); } }); }
public class DistributedTextEditor extends JFrame { private static final long serialVersionUID = -1412971829037207445L; private static DistributedTextEditor editor; private JTextArea area1 = new JTextArea(20, 120); private JTextArea area2 = new JTextArea(20, 120); private JTextField ipaddress = new JTextField("localhost"); private JTextField portNumber = new JTextField("4242"); private EventReplayer er; private Thread ert; private JFileChooser dialog = new JFileChooser(System.getProperty("user.dir")); private String currentFile = "Untitled"; private boolean changed = false; private boolean connected = false; private boolean active = false; private boolean locked = false; private boolean listen = false; private DocumentEventCapturer dec; private ServerSocket serverSocket; private Socket clientSocket; private LamportClock lc; private int serverport; public DistributedTextEditor() { area1.setFont(new Font("Monospaced", Font.PLAIN, 12)); area2.setFont(new Font("Monospaced", Font.PLAIN, 12)); ((AbstractDocument) area1.getDocument()).setDocumentFilter(dec); area2.setEditable(false); Container content = getContentPane(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); JScrollPane scroll1 = new JScrollPane( area1, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); content.add(scroll1, BorderLayout.CENTER); JScrollPane scroll2 = new JScrollPane( area2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); content.add(scroll2, BorderLayout.CENTER); content.add(ipaddress, BorderLayout.CENTER); content.add(portNumber, BorderLayout.CENTER); JMenuBar JMB = new JMenuBar(); setJMenuBar(JMB); JMenu file = new JMenu("File"); JMenu edit = new JMenu("Edit"); JMB.add(file); JMB.add(edit); file.add(Listen); file.add(Connect); file.add(Disconnect); file.addSeparator(); file.add(Save); file.add(SaveAs); file.add(Quit); edit.add(Copy); edit.add(Paste); edit.getItem(0).setText("Copy"); edit.getItem(1).setText("Paste"); Save.setEnabled(false); SaveAs.setEnabled(false); Disconnect.setEnabled(false); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); area1.addKeyListener(k1); area1.addMouseListener(m1); setTitle("Disconnected"); setVisible(true); area1.insert("Welcome to Hjortehandlerne's distributed text editor. \n", 0); this.addWindowListener(w1); } private WindowListener w1 = new WindowListener() { /** Kill all active threads */ @Override public void windowClosing(WindowEvent e) { disconnect(); } @Override public void windowActivated(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowOpened(WindowEvent e) {} }; private KeyListener k1 = new KeyAdapter() { public void keyPressed(KeyEvent e) { changed = true; Save.setEnabled(true); SaveAs.setEnabled(true); } /** * The keyReleased event ensures that the caret-position is updated for both peers, when the * user moves the caret with the arrow-keys. */ public void keyReleased(KeyEvent e) { int left = e.VK_LEFT; int right = e.VK_RIGHT; int up = e.VK_UP; int down = e.VK_DOWN; int home = e.VK_HOME; int end = e.VK_END; int A = e.VK_A; int kc = e.getKeyCode(); if (kc == left || kc == right || kc == up || kc == down || kc == home || kc == end || (kc == A && e.isControlDown())) { if (dec == null) return; lc.increment(); TextEvent cu = new CaretUpdate(area1.getCaretPosition(), lc.getTimeStamp()); dec.sendObjectToAllPeers(cu); er.getEventHistoryLock().lock(); er.getEventHistory().add(cu); er.getEventHistoryLock().unlock(); } } }; /** * This mouselistener ensures that both peers have an updated caret-position for this user, when * he moves his caret by a mouseclick. */ private MouseListener m1 = new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e.getButton() == e.BUTTON1 && connected) { if (dec == null) return; lc.increment(); TextEvent cu = new CaretUpdate(area1.getCaretPosition(), lc.getTimeStamp()); dec.sendObjectToAllPeers(cu); er.getEventHistoryLock().lock(); er.getEventHistory().add(cu); er.getEventHistoryLock().unlock(); } } }; /** * This action is called when the Listen-button is fired. It creates a serversocket, and awaits a * connection. When the first connection is made, a ConnectionData object is sent to the other * peer, and this editor creates new data for the incomming peer. After the first connection is * made, waitForConnection is called, which waits for more connections. */ Action Listen = new AbstractAction("Listen") { public void actionPerformed(ActionEvent e) { saveOld(); final InetAddress local; active = true; try { local = InetAddress.getLocalHost(); Runnable server = new Runnable() { public void run() { serverport = Integer.parseInt(portNumber.getText()); int myID = getNewId(); registerOnPort(); editor.setTitleToListen(); clientSocket = waitForConnectionFromClient(); lc = new LamportClock(myID); area1.setText(""); resetArea2(); if (clientSocket != null) { listen = true; connected = true; dec = new DocumentEventCapturer(lc, editor); setDocumentFilter(dec); er = new EventReplayer(editor, dec, lc); er.updateCaretPos(myID, 0); ert = new Thread(er); ert.start(); try { ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); JoinNetworkRequest request = (JoinNetworkRequest) input.readObject(); int id = getNewId(); Peer peer = new Peer( editor, er, id, clientSocket, output, input, lc, clientSocket.getInetAddress().getHostAddress(), request.getPort()); ConnectionData cd = new ConnectionData( er.getEventHistory(), er.getAcknowledgements(), er.getCarets(), id, area1.getText(), lc.getTimeStamp(), lc.getID(), dec.getPeers(), serverSocket.getLocalPort()); dec.addPeer(peer); er.addCaretPos(id, 0); Thread t = new Thread(peer); t.start(); peer.writeObjectToStream(cd); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } waitForConnection(); } }; Thread serverThread = new Thread(server); serverThread.start(); } catch (UnknownHostException e1) { e1.printStackTrace(); } changed = false; Disconnect.setEnabled(true); Listen.setEnabled(false); Connect.setEnabled(false); Save.setEnabled(false); SaveAs.setEnabled(false); } }; /** * waitForConnection waits for incomming connections. There are two cases. If we receive a * JoinNetworkRequest it means that a new peer tries to get into the network. We lock the entire * system, and sends a ConnectionData object to the new peer, from which he can connect to every * other peer. We add this new peer to our data. * * <p>If we receive a NewPeerDataRequest, it means that a new peer has received ConnectionData * from another peer in the network, and he is now trying to connect to everyone, including me. We * then update our data with the new peer. */ private void waitForConnection() { while (active) { Socket client = waitForConnectionFromClient(); if (client != null) { try { ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream()); ObjectInputStream input = new ObjectInputStream(client.getInputStream()); Object o = input.readObject(); if (o instanceof JoinNetworkRequest) { JoinNetworkRequest request = (JoinNetworkRequest) o; dec.sendObjectToAllPeers(new LockRequest(lc.getTimeStamp())); waitForAllToLock(); setLocked(true); Thread.sleep(500); int id = getNewId(); Peer p = new Peer( editor, er, id, client, output, input, lc, client.getInetAddress().getHostAddress(), request.getPort()); ConnectionData cd = new ConnectionData( er.getEventHistory(), er.getAcknowledgements(), er.getCarets(), id, area1.getText(), lc.getTimeStamp(), lc.getID(), dec.getPeers(), serverSocket.getLocalPort()); p.writeObjectToStream(cd); dec.addPeer(p); Thread t = new Thread(p); t.start(); er.addCaretPos(id, 0); } else if (o instanceof NewPeerDataRequest) { NewPeerDataRequest request = (NewPeerDataRequest) o; Peer newPeer = new Peer( editor, er, request.getId(), client, output, input, lc, client.getInetAddress().getHostAddress(), request.getPort()); dec.addPeer(newPeer); er.addCaretPos(request.getId(), request.getCaretPos()); newPeer.writeObjectToStream(new NewPeerDataAcknowledgement(lc.getTimeStamp())); Thread t = new Thread(newPeer); t.start(); } } catch (IOException | ClassNotFoundException | InterruptedException e) { e.printStackTrace(); } } } } private void waitForAllToLock() { for (Peer p : dec.getPeers()) { while (!p.isLocked() && p.isConnected()) { try { Thread.sleep(100); } catch (InterruptedException e) { } } p.setLocked(false); } } /** * Will register this server on the port number portNumber. Will not start waiting for * connections. For this you should call waitForConnectionFromClient(). */ private void registerOnPort() { try { serverSocket = new ServerSocket(Integer.parseInt(portNumber.getText())); } catch (IOException e) { serverSocket = null; System.err.println("Cannot open server socket on port number" + portNumber.getText()); System.err.println(e); System.exit(-1); } } /** Closes the serversocket */ public void deregisterOnPort() { if (serverSocket != null) { try { serverSocket.close(); serverSocket = null; } catch (IOException e) { System.err.println(e); } } } /** * Waits for the next client to connect on port number portNumber or takes the next one in line in * case a client is already trying to connect. Returns the socket of the connection, null if there * were any failures. */ private Socket waitForConnectionFromClient() { Socket res = null; try { res = serverSocket.accept(); } catch (IOException e) { } return res; } /** * This action is called when the Connect-button is fired. It creates a ClientSocket with the * known peer, and opens a serversocket to listen for new peers. We send a JoinNetworkRequest to * the known peer, and receive ConnectionData from him. We then connect to all other peers in the * network, and update our data from the received ConnectionData. At last we call * waitForConnection() to wait for new connections from new peers, and finally we tell everyone to * unlock the system */ Action Connect = new AbstractAction("Connect") { public void actionPerformed(ActionEvent e) { saveOld(); area1.setText(""); resetArea2(); try { clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText())); Random r = new Random(); serverport = 10000 + r.nextInt(8999); // random port :D serverSocket = new ServerSocket(serverport); active = true; editor.setTitleToListen(); connected = true; ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); output.writeObject(new JoinNetworkRequest(serverport)); ConnectionData data = getConnectionData(clientSocket, input); lc = new LamportClock(data.getId()); lc.setMaxTime(data.getTs()); dec = new DocumentEventCapturer(lc, editor); er = new EventReplayer(editor, dec, lc); ert = new Thread(er); ert.start(); Peer peer = new Peer( editor, er, data.getHostId(), clientSocket, output, input, lc, clientSocket.getInetAddress().getHostAddress(), data.getPort()); dec.addPeer(peer); Thread thread = new Thread(peer); thread.start(); er.setAcknowledgements(data.getAcknowledgements()); er.setEventHistory(data.getEventHistory()); er.setCarets(data.getCarets()); er.addCaretPos(lc.getID(), 0); for (PeerWrapper p : data.getPeers()) { Socket socket; try { socket = connectToPeer(p.getIP(), p.getPort()); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); outputStream.writeObject( new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0)); Peer newPeer = new Peer( editor, er, p.getId(), socket, outputStream, inputStream, lc, p.getIP(), p.getPort()); dec.addPeer(newPeer); Thread t = new Thread(newPeer); t.start(); } catch (IOException ex) { continue; } } Thread t1 = new Thread( new Runnable() { @Override public void run() { waitForConnection(); } }); t1.start(); area1.setText(data.getTextField()); area1.setCaretPosition(0); setDocumentFilter(dec); dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp())); changed = false; Connect.setEnabled(false); Disconnect.setEnabled(true); Listen.setEnabled(false); Save.setEnabled(false); SaveAs.setEnabled(false); } catch (NumberFormatException | IOException e1) { setTitle("Unable to connect"); } } private Socket connectToPeer(String ip, int port) { try { Socket peer = new Socket(ip, port); return peer; } catch (IOException e) { e.printStackTrace(); } return null; } private ConnectionData getConnectionData(Socket clientSocket, ObjectInputStream input) { ConnectionData res; try { Object o = input.readObject(); res = (ConnectionData) o; return res; } catch (IOException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }; /** This action is called when the Disconnect-button is fired. */ Action Disconnect = new AbstractAction("Disconnect") { public void actionPerformed(ActionEvent e) { disconnect(); } }; /** * The disconnect method will stop the eventreplayer, and send null to the other peers, to stop * their reading from their streams. The GUI-menu is updated appropriately. */ public void disconnect() { setTitle("Disconnected"); active = false; if (connected == true) { er.stopStreamToQueue(); ert.interrupt(); setDocumentFilter(null); connected = false; setLocked(false); } deregisterOnPort(); Disconnect.setEnabled(false); Connect.setEnabled(true); Listen.setEnabled(true); Save.setEnabled(true); SaveAs.setEnabled(true); } Action Save = new AbstractAction("Save") { public void actionPerformed(ActionEvent e) { if (!currentFile.equals("Untitled")) saveFile(currentFile); else saveFileAs(); } }; Action SaveAs = new AbstractAction("Save as...") { public void actionPerformed(ActionEvent e) { saveFileAs(); } }; Action Quit = new AbstractAction("Quit") { public void actionPerformed(ActionEvent e) { saveOld(); System.exit(0); } }; ActionMap m = area1.getActionMap(); Action Copy = m.get(DefaultEditorKit.copyAction); Action Paste = m.get(DefaultEditorKit.pasteAction); private void saveFileAs() { if (dialog.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) saveFile(dialog.getSelectedFile().getAbsolutePath()); } private void saveOld() { if (changed) { if (JOptionPane.showConfirmDialog( this, "Would you like to save " + currentFile + " ?", "Save", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) saveFile(currentFile); } } private void saveFile(String fileName) { try { FileWriter w = new FileWriter(fileName); area1.write(w); w.close(); currentFile = fileName; changed = false; Save.setEnabled(false); } catch (IOException e) { } } public boolean getActive() { return active; } public DocumentFilter getDocumentFilter() { return dec; } public JTextArea getTextArea() { return area1; } public DocumentEventCapturer getDocumentEventCapturer() { return dec; } public void setDocumentFilter(DocumentFilter filter) { ((AbstractDocument) area1.getDocument()).setDocumentFilter(filter); } public void setErrorMessage(String s) { area2.setText("Error: " + s); } public void setTitleToListen() { try { String serverString = serverSocket.getInetAddress().getLocalHost().toString(); String serverIP = serverString.split("/")[1]; editor.setTitle("Listening on: " + serverIP + ":" + serverport); } catch (UnknownHostException e) { e.printStackTrace(); } } public void resetArea2() { area2.setText(""); } public static void main(String[] arg) { editor = new DistributedTextEditor(); } public void setLocked(boolean b) { locked = b; area1.setEnabled(!b); } public boolean getListen() { return listen; } public void setTextInArea2(String res) { area2.setText(res); } public EventReplayer getEventReplayer() { return er; } public int getNewId() { Random r = new Random(); return r.nextInt(1000000); } }
// {{{ InstallPanel constructor InstallPanel(PluginManager window, boolean updates) { super(new BorderLayout(12, 12)); this.window = window; this.updates = updates; setBorder(new EmptyBorder(12, 12, 12, 12)); final JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT); split.setResizeWeight(0.75); /* Setup the table */ table = new JTable(pluginModel = new PluginTableModel()); table.setShowGrid(false); table.setIntercellSpacing(new Dimension(0, 0)); table.setRowHeight(table.getRowHeight() + 2); table.setPreferredScrollableViewportSize(new Dimension(500, 200)); table.setDefaultRenderer( Object.class, new TextRenderer((DefaultTableCellRenderer) table.getDefaultRenderer(Object.class))); table.addFocusListener(new TableFocusHandler()); InputMap tableInputMap = table.getInputMap(JComponent.WHEN_FOCUSED); ActionMap tableActionMap = table.getActionMap(); tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tabOutForward"); tableActionMap.put("tabOutForward", new KeyboardAction(KeyboardCommand.TAB_OUT_FORWARD)); tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK), "tabOutBack"); tableActionMap.put("tabOutBack", new KeyboardAction(KeyboardCommand.TAB_OUT_BACK)); tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "editPlugin"); tableActionMap.put("editPlugin", new KeyboardAction(KeyboardCommand.EDIT_PLUGIN)); tableInputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "closePluginManager"); tableActionMap.put( "closePluginManager", new KeyboardAction(KeyboardCommand.CLOSE_PLUGIN_MANAGER)); TableColumn col1 = table.getColumnModel().getColumn(0); TableColumn col2 = table.getColumnModel().getColumn(1); TableColumn col3 = table.getColumnModel().getColumn(2); TableColumn col4 = table.getColumnModel().getColumn(3); TableColumn col5 = table.getColumnModel().getColumn(4); col1.setPreferredWidth(30); col1.setMinWidth(30); col1.setMaxWidth(30); col1.setResizable(false); col2.setPreferredWidth(180); col3.setPreferredWidth(130); col4.setPreferredWidth(70); col5.setPreferredWidth(70); JTableHeader header = table.getTableHeader(); header.setReorderingAllowed(false); header.addMouseListener(new HeaderMouseHandler()); header.setDefaultRenderer( new HeaderRenderer((DefaultTableCellRenderer) header.getDefaultRenderer())); scrollpane = new JScrollPane(table); scrollpane.getViewport().setBackground(table.getBackground()); split.setTopComponent(scrollpane); /* Create description */ JScrollPane infoPane = new JScrollPane(infoBox = new PluginInfoBox()); infoPane.setPreferredSize(new Dimension(500, 100)); split.setBottomComponent(infoPane); EventQueue.invokeLater( new Runnable() { @Override public void run() { split.setDividerLocation(0.75); } }); final JTextField searchField = new JTextField(); searchField.addKeyListener( new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_UP) { table.dispatchEvent(e); table.requestFocus(); } } }); searchField .getDocument() .addDocumentListener( new DocumentListener() { void update() { pluginModel.setFilterString(searchField.getText()); } @Override public void changedUpdate(DocumentEvent e) { update(); } @Override public void insertUpdate(DocumentEvent e) { update(); } @Override public void removeUpdate(DocumentEvent e) { update(); } }); table.addKeyListener( new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int i = table.getSelectedRow(), n = table.getModel().getRowCount(); if (e.getKeyCode() == KeyEvent.VK_DOWN && i == (n - 1) || e.getKeyCode() == KeyEvent.VK_UP && i == 0) { searchField.requestFocus(); searchField.selectAll(); } } }); Box filterBox = Box.createHorizontalBox(); filterBox.add(new JLabel("Filter : ")); filterBox.add(searchField); add(BorderLayout.NORTH, filterBox); add(BorderLayout.CENTER, split); /* Create buttons */ Box buttons = new Box(BoxLayout.X_AXIS); buttons.add(new InstallButton()); buttons.add(Box.createHorizontalStrut(12)); buttons.add(new SelectallButton()); buttons.add(chooseButton = new ChoosePluginSet()); buttons.add(new ClearPluginSet()); buttons.add(Box.createGlue()); buttons.add(new SizeLabel()); add(BorderLayout.SOUTH, buttons); String path = jEdit.getProperty(PluginManager.PROPERTY_PLUGINSET, ""); if (!path.isEmpty()) { loadPluginSet(path); } } // }}}
public AuthDialog(final JFrame parent, String title, boolean modal) { super(parent, title, modal); // Set up close behaviour setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { if (!okButtonClicked) System.exit(0); } }); // Set up OK button behaviour JButton okButton = new JButton("OK"); okButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { if (getUserName().length() == 0) { showMessageDialog( AuthDialog.this, "Please enter a username", "Format Error", ERROR_MESSAGE); return; } if (getDatabasePassword().length() == 0) { showMessageDialog( AuthDialog.this, "Please enter a password", "Format Error", ERROR_MESSAGE); return; } okButtonClicked = true; setVisible(false); } }); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Set up dialog contents labelPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 5, 5)); inputPanel.setBorder(BorderFactory.createEmptyBorder(20, 5, 5, 20)); labelPanel.setLayout(new GridLayout(2, 1)); labelPanel.add(new JLabel("User Name: ")); labelPanel.add(new JLabel("Password:"******"ESCAPE"), "exitAction"); actionMap.put( "exitAction", new AbstractAction() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Pack it all pack(); // Center on the screen setLocationRelativeTo(null); }