下面列出了javax.swing.text.JTextComponent#requestFocus ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void showPopupMenu(int x, int y) {
// First call the build-popup-menu action to possibly rebuild the popup menu
JTextComponent c = getComponent();
if (c != null) {
BaseKit kit = Utilities.getKit(c);
if (kit != null) {
Action a = kit.getActionByName(ExtKit.buildPopupMenuAction);
if (a != null) {
a.actionPerformed(new ActionEvent(c, 0, "")); // NOI18N
}
}
JPopupMenu pm = getPopupMenu();
if (pm != null) {
if (c.isShowing()) { // fix of #18808
if (!c.isFocusOwner()) {
c.requestFocus();
}
pm.show(c, x, y);
}
}
}
}
private static Runnable createOnFocusGained(final JTextComponent textComponent, final Runnable onFocusGained) {
final FocusListener focusListener = new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
super.focusGained(arg0);
SwingUtilities.invokeLater(onFocusGained);
textComponent.removeFocusListener(this);
}
};
textComponent.addFocusListener(focusListener);
return new Runnable() {
@Override
public void run() {
textComponent.requestFocus();
}
};
}
public void actionPerformed(ActionEvent ae) {
String addressPath = OperationDialog.this.node.addressPath();
if (OperationDialog.this.opName.equals("add")) {
UserObject usrObj = (UserObject)OperationDialog.this.node.getUserObject();
ManagementModelNode parent = (ManagementModelNode)OperationDialog.this.node.getParent();
RequestProp resourceProp = OperationDialog.this.props.first();
String value = resourceProp.getValueAsString();
value = ManagementModelNode.escapeAddressElement(value);
addressPath = parent.addressPath() + usrObj.getName() + "=" + value + "/";
OperationDialog.this.props.remove(resourceProp);
}
StringBuilder command = new StringBuilder();
command.append(addressPath);
command.append(":");
command.append(OperationDialog.this.opName);
addRequestProps(command, OperationDialog.this.props);
JTextComponent cmdText = cliGuiCtx.getCommandLine().getCmdText();
cmdText.setText(command.toString());
OperationDialog.this.dispose();
cmdText.requestFocus();
}
public void actionPerformed(ActionEvent e) {
StringBuilder builder = new StringBuilder("undeploy ");
String name = deploymentChooser.getSelectedDeployment();
builder.append(name);
if (keepContent.isSelected()) builder.append(" --keep-content");
if (!cliGuiCtx.isStandalone()) {
addDomainParams(builder);
}
JTextComponent cmdText = cliGuiCtx.getCommandLine().getCmdText();
cmdText.setText(builder.toString());
dispose();
cmdText.requestFocus();
}
public void actionPerformed(ActionEvent ae) {
JTextComponent cmdText = cliGuiCtx.getCommandLine().getCmdText();
ModelNode requestProperties = opDescription.get("result", "request-properties");
if (isNoArgOperation(requestProperties)) {
cmdText.setText(addressPath + ":" + opName);
cmdText.requestFocus();
return;
}
if (node.isLeaf() && opName.equals("undefine-attribute")) {
UserObject usrObj = (UserObject)node.getUserObject();
cmdText.setText(addressPath + ":" + opName + "(name=" + usrObj.getName() + ")");
cmdText.requestFocus();
return;
}
OperationDialog dialog = new OperationDialog(cliGuiCtx, node, opName, strDescription, requestProperties);
dialog.setLocationRelativeTo(cliGuiCtx.getMainWindow());
dialog.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JTextComponent)) {
return;
}
textComponent = (JTextComponent) e.getSource();
textComponent.requestFocus();
boolean enabled = textComponent.isEnabled();
boolean editable = textComponent.isEditable();
boolean nonempty = !(textComponent.getText() == null || textComponent.getText().equals(""));
boolean marked = textComponent.getSelectedText() != null;
boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);
undoAction.setEnabled(enabled && editable && (lastActionSelected == Actions.CUT || lastActionSelected == Actions.PASTE));
cutAction.setEnabled(enabled && editable && marked);
copyAction.setEnabled(enabled && marked);
pasteAction.setEnabled(enabled && editable && pasteAvailable);
selectAllAction.setEnabled(enabled && nonempty);
int nx = e.getX();
if (nx > 500) {
nx = nx - popup.getSize().width;
}
popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
}
}
@Override
public boolean marathon_select(String value) {
JTextComponent tc = (JTextComponent) component;
tc.requestFocus();
Boolean clientProperty = (Boolean) tc.getClientProperty("marathon.celleditor");
clear();
if (clientProperty != null && clientProperty) {
sendKeys(value, JavaAgentKeys.ENTER);
} else {
sendKeys(value);
}
return true;
}
private void prepareEditor() {
Component c = getEditor().getEditorComponent();
if (c instanceof JTextComponent) {
JTextComponent jtc = (JTextComponent) c;
String s = jtc.getText();
if ((s != null) && (s.length() > 0)) {
jtc.setSelectionStart(0);
jtc.setSelectionEnd(s.length());
}
if (tableUI) {
jtc.setBackground(getBackground());
} else {
jtc.setBackground(PropUtils.getTextFieldBackground());
}
if( tableUI )
jtc.requestFocus();
}
if (getLayout() != null) {
getLayout().layoutContainer(this);
}
repaint();
}
public void setText(JTextComponent component, String text) {
component.requestFocus();
waitForDispatchThread();
Document doc = component.getDocument();
try {
doc.remove(0, doc.getLength());
doc.insertString(0, text, null);
} catch (BadLocationException ex) {
testCase.fail(ex);
}
ddObj.modelUpdatedFromUI();
waitForDispatchThread();
}
public static void requestFocus(JTextComponent c) {
if (c != null) {
if (!ImplementationProvider.getDefault().activateComponent(c)) {
Frame f = EditorUI.getParentFrame(c);
if (f != null) {
f.requestFocus();
}
c.requestFocus();
}
}
}
public static void requestFocus(JTextComponent c) {
if (c != null) {
if (!EditorImplementation.getDefault().activateComponent(c)) {
Frame f = getParentFrame(c);
if (f != null) {
f.requestFocus();
}
c.requestFocus();
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getModifiers() == InputEvent.BUTTON3_MASK) {
if (!(e.getSource() instanceof JTextComponent)) {
return;
}
_textComponent = (JTextComponent) e.getSource();
_textComponent.requestFocus();
boolean enabled = _textComponent.isEnabled();
boolean editable = _textComponent.isEditable();
boolean nonempty = !(_textComponent.getText() == null || _textComponent.getText().isEmpty());
boolean marked = _textComponent.getSelectedText() != null;
boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);
_undoAction.setEnabled(enabled && editable && (_lastActionSelected == _Actions.CUT || _lastActionSelected == _Actions.PASTE));
_cutAction.setEnabled(enabled && editable && marked);
_copyAction.setEnabled(enabled && marked);
_pasteAction.setEnabled(enabled && editable && pasteAvailable);
_selectAllAction.setEnabled(enabled && nonempty);
int nx = e.getX();
if (nx > 500) {
nx -= _popup.getSize().width;
}
_popup.show(e.getComponent(), nx, e.getY() - _popup.getSize().height);
}
}
public void actionPerformed(ActionEvent e) {
StringBuilder builder = new StringBuilder("deploy");
String path = pathField.getText();
if (!path.trim().isEmpty()) {
builder.append(" ").append(path);
} else {
JOptionPane.showMessageDialog(this, "A file must be selected.", "Empty File Path", JOptionPane.ERROR_MESSAGE);
return;
}
String name = nameField.getText();
if (!name.trim().isEmpty()) builder.append(" --name=").append(name);
String runtimeName = runtimeNameField.getText();
if (!runtimeName.trim().isEmpty()) builder.append(" --runtime-name=").append(runtimeName);
if (forceCheckBox.isSelected()) builder.append(" --force");
if (disabledCheckBox.isSelected() && disabledCheckBox.isEnabled()) builder.append(" --disabled");
if (!cliGuiCtx.isStandalone()) {
if (allServerGroups.isSelected() && allServerGroups.isEnabled()) {
builder.append(" --all-server-groups");
} else if (serverGroupChooser.isEnabled()) {
builder.append(serverGroupChooser.getCmdLineArg());
}
}
JTextComponent cmdText = cliGuiCtx.getCommandLine().getCmdText();
cmdText.setText(builder.toString());
dispose();
cmdText.requestFocus();
}
private void createUI() {
final JPanel dialogPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
int line = 0;
GridBagUtils.addToPanel(dialogPane, _paramName.getEditor().getLabelComponent(), gbc,
"fill=BOTH, weightx=1, insets.top=3");
GridBagUtils.addToPanel(dialogPane, _paramName.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramDesc.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramDesc.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramUnit.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramUnit.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramDataType.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramDataType.getEditor().getComponent(), gbc);
_paramDataType.setUIEnabled(false);
GridBagUtils.addToPanel(dialogPane, createInfoPanel(), gbc, "gridy=" + ++line + ", insets.top=10, gridwidth=2");
setContent(dialogPane);
final JComponent editorComponent = _paramName.getEditor().getEditorComponent();
if (editorComponent instanceof JTextComponent) {
final JTextComponent tc = (JTextComponent) editorComponent;
tc.selectAll();
tc.requestFocus();
}
}
public void actionPerformed(ActionEvent e) {
final Component c = getInvoker();
if (c instanceof JTextComponent) {
JTextComponent text = (JTextComponent)c;
text.requestFocus();
if (c instanceof JFormattedTextField)
text.setText(text.getText());
text.selectAll();
}
}
void apply(JTextComponent cmp) {
if(!applied && cmp.getDocument().getLength() >= len) {
if(dot == mark) {
cmp.setCaretPosition(dot);
} else {
cmp.setSelectionStart(mark);
cmp.setSelectionEnd(dot);
cmp.getCaret().setSelectionVisible(true);
}
if(focus) cmp.requestFocus();
applied = true;
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (ignoreComboAction)
return; // not invoked by user, ignore
GuardedBlock gBlock = codeData.getGuardedBlock(category, blockIndex);
GuardBlockInfo gInfo = getGuardInfos(category)[blockIndex];
int[] blockBounds = getGuardBlockBounds(category, blockIndex);
int startOffset = blockBounds[0];
int endOffset = blockBounds[1];
int gHead = gBlock.getHeaderLength();
int gFoot = gBlock.getFooterLength();
JTextComponent editor = getEditor(category);
StyledDocument doc = (StyledDocument) editor.getDocument();
changed = true;
JComboBox combo = (JComboBox) e.getSource();
try {
docListener.setActive(false);
if (combo.getSelectedIndex() == 1) { // changing from default to custom
NbDocument.unmarkGuarded(doc, startOffset, endOffset - startOffset);
// keep last '\n' so we don't destroy next editable block's position
doc.remove(startOffset, endOffset - startOffset - 1);
// insert the custom code into the document
String customCode = gBlock.getCustomCode();
int customLength = customCode.length();
if (gInfo.customizedCode != null) { // already was edited before
customCode = customCode.substring(0, gHead)
+ gInfo.customizedCode
+ customCode.substring(customLength - gFoot);
customLength = customCode.length();
}
if (customCode.endsWith("\n")) // NOI18N
customCode = customCode.substring(0, customLength-1);
doc.insertString(startOffset, customCode, null);
gInfo.customized = true;
// make guarded "header" and "footer", select the text in between
NbDocument.markGuarded(doc, startOffset, gHead);
NbDocument.markGuarded(doc, startOffset + customLength - gFoot, gFoot);
editor.setSelectionStart(startOffset + gHead);
editor.setSelectionEnd(startOffset + customLength - gFoot);
editor.requestFocus();
combo.setToolTipText(gBlock.getCustomEntry().getToolTipText());
}
else { // changing from custom to default
// remember the customized code
gInfo.customizedCode = doc.getText(startOffset + gHead,
endOffset - gFoot - gHead - startOffset);
NbDocument.unmarkGuarded(doc, endOffset - gFoot, gFoot);
NbDocument.unmarkGuarded(doc, startOffset, gHead);
// keep last '\n' so we don't destroy next editable block's position
doc.remove(startOffset, endOffset - startOffset - 1);
String defaultCode = gBlock.getDefaultCode();
if (defaultCode.endsWith("\n")) // NOI18N
defaultCode = defaultCode.substring(0, defaultCode.length()-1);
doc.insertString(startOffset, defaultCode, null);
gInfo.customized = false;
// make the whole text guarded, cancel selection
NbDocument.markGuarded(doc, startOffset, defaultCode.length()+1); // including '\n'
if (editor.getSelectionStart() >= startOffset && editor.getSelectionEnd() <= endOffset)
editor.setCaretPosition(startOffset);
combo.setToolTipText(NbBundle.getMessage(CustomCodeData.class, "CTL_GuardCombo_Default_Hint")); // NOI18N
}
// we must create a new Position - current was moved away by inserting new string on it
gInfo.position = NbDocument.createPosition(doc, startOffset, Position.Bias.Forward);
docListener.setActive(true);
}
catch (BadLocationException ex) { // should not happen
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
}
}
@Override
public void mousePressed(MouseEvent evt) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("mousePressed: " + logMouseEvent(evt) + ", state=" + mouseState + '\n'); // NOI18N
}
JTextComponent c = component;
if (c != null && isLeftMouseButtonExt(evt)) {
// Expand fold if offset is in collapsed fold
int offset = mouse2Offset(evt);
switch (evt.getClickCount()) {
case 1: // Single press
if (c.isEnabled() && !c.hasFocus()) {
c.requestFocus();
}
c.setDragEnabled(true);
if (evt.isShiftDown()) { // Select till offset
moveDot(offset);
adjustRectangularSelectionMouseX(evt.getX(), evt.getY()); // also fires state change
mouseState = MouseState.CHAR_SELECTION;
} else { // Regular press
// check whether selection drag is possible
if (isDragPossible(evt) && mapDragOperationFromModifiers(evt) != TransferHandler.NONE) {
mouseState = MouseState.DRAG_SELECTION_POSSIBLE;
} else { // Drag not possible
mouseState = MouseState.CHAR_SELECTION;
setDot(offset);
}
}
break;
case 2: // double-click => word selection
mouseState = MouseState.WORD_SELECTION;
// Disable drag which would otherwise occur when mouse would be over text
c.setDragEnabled(false);
// Check possible fold expansion
try {
// hack, to get knowledge of possible expansion. Editor depends on Folding, so it's not really possible
// to have Folding depend on BaseCaret (= a cycle). If BaseCaret moves to editor.lib2, this contract
// can be formalized as an interface.
Callable<Boolean> cc = (Callable<Boolean>)c.getClientProperty("org.netbeans.api.fold.expander");
if (cc == null || !cc.equals(this)) {
if (selectWordAction == null) {
selectWordAction = ((BaseKit) c.getUI().getEditorKit(
c)).getActionByName(BaseKit.selectWordAction);
}
if (selectWordAction != null) {
selectWordAction.actionPerformed(null);
}
// Select word action selects forward i.e. dot > mark
minSelectionStartOffset = getMark();
minSelectionEndOffset = getDot();
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
break;
case 3: // triple-click => line selection
mouseState = MouseState.LINE_SELECTION;
// Disable drag which would otherwise occur when mouse would be over text
c.setDragEnabled(false);
if (selectLineAction == null) {
selectLineAction = ((BaseKit) c.getUI().getEditorKit(
c)).getActionByName(BaseKit.selectLineAction);
}
if (selectLineAction != null) {
selectLineAction.actionPerformed(null);
// Select word action selects forward i.e. dot > mark
minSelectionStartOffset = getMark();
minSelectionEndOffset = getDot();
}
break;
default: // multi-click
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
JTextComponent text = (textPane != null) ? textPane : getTextComponent(e);
String currentSearch = search;
if ((currentSearch == null) || (currentSearch.isEmpty())) {
currentSearch = text.getSelectedText();
}
if ((currentSearch == null) || (currentSearch.isEmpty())) {
currentSearch = lastSearch;
}
currentSearch = JOptionPane.showInputDialog(
text.getParent(),
GT._T("String to find"),
currentSearch);
if ((currentSearch == null) || ("".equals(currentSearch.trim()))) {
return;
}
lastSearch = currentSearch;
String textPattern = "";
char firstChar = lastSearch.charAt(0);
if (Character.isLetter(firstChar)) {
textPattern =
"[" + Character.toUpperCase(firstChar) + Character.toLowerCase(firstChar) + "]" +
Pattern.quote(lastSearch.substring(1));
} else {
textPattern = Pattern.quote(lastSearch);
}
Pattern pattern = Pattern.compile(textPattern);
Matcher matcher = pattern.matcher(text.getText());
if (matcher.find(text.getCaretPosition())) {
text.setCaretPosition(matcher.start());
text.moveCaretPosition(matcher.end());
text.requestFocus();
return;
}
if (matcher.find(0)) {
text.setCaretPosition(matcher.start());
text.moveCaretPosition(matcher.end());
text.requestFocus();
return;
}
}
private void createUI() {
createButtonsAndLabels();
int line = 0;
JPanel dialogPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramNewName.getEditor().getLabelComponent(), gbc,
"fill=BOTH, weightx=0, insets.top=3");
GridBagUtils.addToPanel(dialogPane, paramNewName.getEditor().getComponent(), gbc, "weightx=1, gridwidth=3");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramNewDesc.getEditor().getLabelComponent(), gbc,
"weightx=0, gridwidth=1");
GridBagUtils.addToPanel(dialogPane, paramNewDesc.getEditor().getComponent(), gbc, "weightx=1, gridwidth=3");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramSourceProduct.getEditor().getLabelComponent(), gbc,
"fill=NONE, gridwidth=4, insets.top=15");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramSourceProduct.getEditor().getComponent(), gbc,
"fill=HORIZONTAL, insets.top=3");
gbc.gridy = ++line;
final JPanel radioPanel = new JPanel(new BorderLayout());
radioPanel.add(copyAllRButton, BorderLayout.WEST);
radioPanel.add(geocodingRButton);
GridBagUtils.addToPanel(dialogPane, radioPanel, gbc, "fill=NONE, gridwidth=2");
GridBagUtils.addToPanel(dialogPane, subsetRButton, gbc, "gridwidth=1, weightx=300, anchor=EAST");
GridBagUtils.addToPanel(dialogPane, subsetButton, gbc, "fill=NONE, weightx=1, anchor=EAST");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, createInfoPanel(), gbc,
"fill=BOTH, anchor=WEST, insets.top=10, gridwidth=4");
setContent(dialogPane);
final JComponent editorComponent = paramNewName.getEditor().getEditorComponent();
if (editorComponent instanceof JTextComponent) {
JTextComponent tf = (JTextComponent) editorComponent;
tf.selectAll();
tf.requestFocus();
}
}