键入时如何正确删除自动添加的右括号
How to correctly remove the automatically added closing bracket when it is typed
在 textPaneKeyTyped(java.awt.event.keyEvent evt)
方法中,我编写了一些代码以在键入左括号时自动关闭括号。我添加了一些代码,用于在用户在 textPane 中键入右括号时删除右括号,但它没有执行任何操作
这是一个工作示例:
package test;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
textPanel = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textPanel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
textPanelKeyTyped(evt);
}
});
jScrollPane1.setViewportView(textPanel);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void textPanelKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
Action action1 = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textModel = (JTextPane) e.getSource();
try {
int position2 = textModel.getCaretPosition();
textModel.getDocument().remove(position2, 1);
textModel.getDocument().insertString(position2, ")", null);
} catch (Exception e1) {}
}
};
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int position = textModel.getCaretPosition();
textModel.replaceSelection("()");
textModel.setCaretPosition(position+1);
}
};
String key = "typed (";
String key1 = "typed )";
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key), key);
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key1), key1);
textPanel.getActionMap().put(key, action);
textPanel.getActionMap().put(key1, action1);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane textPanel;
// End of variables declaration
}
自动关闭括号的代码有效..
问题是右括号的替换:它在有“(”之前打印“)”。如果我能够随时打印“)”,我应该如何编辑我的代码?
谢谢。
阻止 KeyStroke 的使用从来都不是一个好主意。您永远不知道什么时候可能需要手动输入“)”。谁在乎用户是否输入“)”。如果它在语法上不正确,那么他们最终会得到一个编译错误。聪明的用户会意识到,所有需要做的就是键入“(”,然后“)”将为他们输入。
但是,如果在某些情况下您确实想阻止输入给定字符,则可以使用 Key Bindings
而不是 KeyListener。
例如:
KeyStroke ignore = KeyStroke.getKeyStroke(')');
textPane.getInputMap().put(ignore, "none");
有关 Key Bindings
的更多信息,请阅读 Swig 教程。我在你之前的一个问题中给了你一个 link。将教程 link 放在手边以获取基础知识。当您查看本教程的 table 目录 ("trail") 时,您会找到关于 How to Use Key Bindings
的部分。
对于您的“(”操作,您可以只使用:
textPane.replaceSelection("()");
在 textPaneKeyTyped(java.awt.event.keyEvent evt)
方法中,我编写了一些代码以在键入左括号时自动关闭括号。我添加了一些代码,用于在用户在 textPane 中键入右括号时删除右括号,但它没有执行任何操作
这是一个工作示例:
package test;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
textPanel = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
textPanel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
textPanelKeyTyped(evt);
}
});
jScrollPane1.setViewportView(textPanel);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(27, Short.MAX_VALUE))
);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>
private void textPanelKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
Action action1 = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textModel = (JTextPane) e.getSource();
try {
int position2 = textModel.getCaretPosition();
textModel.getDocument().remove(position2, 1);
textModel.getDocument().insertString(position2, ")", null);
} catch (Exception e1) {}
}
};
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
int position = textModel.getCaretPosition();
textModel.replaceSelection("()");
textModel.setCaretPosition(position+1);
}
};
String key = "typed (";
String key1 = "typed )";
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key), key);
textPanel.getInputMap().put(KeyStroke.getKeyStroke(key1), key1);
textPanel.getActionMap().put(key, action);
textPanel.getActionMap().put(key1, action1);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane textPanel;
// End of variables declaration
}
自动关闭括号的代码有效.. 问题是右括号的替换:它在有“(”之前打印“)”。如果我能够随时打印“)”,我应该如何编辑我的代码? 谢谢。
阻止 KeyStroke 的使用从来都不是一个好主意。您永远不知道什么时候可能需要手动输入“)”。谁在乎用户是否输入“)”。如果它在语法上不正确,那么他们最终会得到一个编译错误。聪明的用户会意识到,所有需要做的就是键入“(”,然后“)”将为他们输入。
但是,如果在某些情况下您确实想阻止输入给定字符,则可以使用 Key Bindings
而不是 KeyListener。
例如:
KeyStroke ignore = KeyStroke.getKeyStroke(')');
textPane.getInputMap().put(ignore, "none");
有关 Key Bindings
的更多信息,请阅读 Swig 教程。我在你之前的一个问题中给了你一个 link。将教程 link 放在手边以获取基础知识。当您查看本教程的 table 目录 ("trail") 时,您会找到关于 How to Use Key Bindings
的部分。
对于您的“(”操作,您可以只使用:
textPane.replaceSelection("()");