我想为所有打开的文档应用插入键操作(可在键盘中用作“插入”键)。默认情况下,它不适用于任何文档。我为插入键编写代码。但是,在我的程序中插入键操作仅适用于最近打开的文件。我想将此功能添加到所有打开的文件中。请检查一次。
主类:
public class InsertDemo extends javax.swing.JFrame {
JScrollPane scrollPane;
JTextArea textArea;
public InsertDemo() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
tabbedPane = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
file = new javax.swing.JMenu();
newFile = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
file.setText("File");
newFile.setText("NewFile");
newFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newFileActionPerformed(evt);
}
});
file.add(newFile);
jMenuBar1.add(file);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void newFileActionPerformed(java.awt.event.ActionEvent evt) {
textArea=new CaretTextArea();
scrollPane=new JScrollPane(textArea);
tabbedPane.add(scrollPane);
}
public static void main(String args[]) {
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(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InsertDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InsertDemo().setVisible(true);
}
});
}
private javax.swing.JMenu file;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem newFile;
private javax.swing.JTabbedPane tabbedPane;
}
插入Action类。我通过这个类创建JtextArea引用。这是JTextArea的扩展类。
public class CaretTextArea extends JTextArea {
private boolean isInsertMode=false;
Color oldCaretColor;
Color insertCaretColor=new Color(254, 254, 254);
public CaretTextArea() {
MyCaret c=new MyCaret();
c.setBlinkRate(getCaret().getBlinkRate());
setCaret(c);
oldCaretColor=getCaretColor();
addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e){
if (isInsertMode()) {
processCaretWidth();
}
}
});
Keymap kMap=this.getKeymap();
Action a=new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
setInsertMode(!isInsertMode());
}
};
kMap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT,0),a);
}
public boolean isInsertMode() {
return isInsertMode;
}
public void setInsertMode(boolean insertMode) {
isInsertMode = insertMode;
processMode();
}
private void processMode() {
if (isInsertMode()) {
processCaretWidth();
setCaretColor(insertCaretColor);
}
else {
setCaretColor(oldCaretColor);
putClientProperty("caretWidth", 1);
}
}
private void processCaretWidth() {
try {
int pos=getCaretPosition();
Rectangle rPos=modelToView(pos)!=null ? modelToView(pos).getBounds() :new Rectangle();
int caretX=rPos.x;
int caretEndX=rPos.x;
if (pos<getDocument().getLength()) {
Rectangle rNextPos=modelToView(pos+1)!=null ? modelToView(pos+1).getBounds(): new Rectangle();
if (rPos.y==rNextPos.y) {
caretEndX=rNextPos.x;
}
}
putClientProperty("caretWidth", Math.max(1, caretEndX-caretX+1));
} catch (BadLocationException e) {
// e.printStackTrace();
}
}
@Override
public void replaceSelection(String content) {
if (isEditable() && isInsertMode() && getSelectionStart()==getSelectionEnd()) {
int pos=getCaretPosition();
int lastPos=Math.min(getDocument().getLength(), pos+content.length());
select(pos, lastPos);
}
super.replaceSelection(content);
}
class MyCaret extends DefaultCaret {
public void paint(Graphics g) {
if (isInsertMode()) {
//we should shift to half width because of DefaultCaret rendering algorithm
AffineTransform old=((Graphics2D)g).getTransform();
int w=(Integer)getClientProperty("caretWidth");
g.setXORMode(Color.black);
g.translate(w/2,0);
super.paint(g);
((Graphics2D)g).setTransform(old);
}
else {
super.paint(g);
}
}
protected synchronized void damage(Rectangle r) {
if (isInsertMode()) {
if (r != null) {
int damageWidth = (Integer)getClientProperty("caretWidth");
x = r.x - 4 - (damageWidth/2 );
y = r.y;
width = 9 + 3*damageWidth/2;
height = r.height;
repaint();
}
}
else {
super.damage(r);
}
}
}
}