现在,我一直在尝试使用以下代码插入一个字符,例如Eclipse中的自动完成类型到JTextPane:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.StyledDocument;
public class Main implements Runnable
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final String NAME = "";
private JFrame frame;
private JTextPane textPane = new JTextPane();
public void run()
{
frame = new JFrame(NAME);
frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
frame.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.setMaximumSize(new Dimension(WIDTH, HEIGHT));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(textPane, BorderLayout.CENTER);
textPane.setPreferredSize(new Dimension(WIDTH, HEIGHT));
textPane.setEditable(true);
textPane.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent arg0) {
ArrayList<Integer> keyCode = new ArrayList<Integer>();
StyledDocument doc = textPane.getStyledDocument();
keyCode.add(arg0.getKeyCode());
if(keyCode.contains(KeyEvent.VK_OPEN_BRACKET)) /* If an open brace has been hit! */
{
if(keyCode.contains(KeyEvent.VK_SHIFT)) /* Because brackets and braces use the same keyCode, we needed to
* make sure it was a brace */
{
try
{
doc.insertString(textPane.getCaretPosition(), "\n}", null); /* Putting in our new string */
} catch(Exception e1) {
e1.printStackTrace();
}
return;
}
/* Auto-complete it */
try
{
doc.insertString(textPane.getCaretPosition(), "]", null); /* Putting in our new string */
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
frame.pack();
frame.setVisible(true);
}
public void start()
{
new Thread(this).start();
}
public final static void main(String args[])
{
new Main().start();
}
}
我遇到的唯一问题是,似乎insertString中的偏移是行而不是列;例如,当我尝试将insertString的offest设置为0时,它将字符放在后面的类型字符,所以它最终看起来像这样:
)(
而不是我想要的输出:
()
但是,如果我将偏移量设置为1,那么它会向下移动整行,使其看起来像:
(
)
我无法弄清楚这里发生了什么,或使用setText在之外插入文本的任何其他方式。
有什么想法吗?我注定只使用setText吗?谢谢您的所有时间!
〜美分
编辑:
将代码更改为SSCCE。