我有一个外部设备一次向我发送 1 个字符的数据。我正在将其写入 JTextPane 上的 StyledDocument。此数据在不是 AWT 线程的线程上发送给我,因此我需要创建 AWTEvents 并将它们推送到 EventQueue 以便 AWT 处理写入,这样我就不会收到异常。
我现在有一个有趣的问题...
我的文本正在向后打印到文档。
这显然是因为我在收到字符时一次将字符推送到事件队列 1。一个队列显然是最后推送的,首先是弹出的。我正在尝试一种可以在添加新事件或类似事件之前触发事件的方法,以便我可以按顺序触发事件。
http://www.kauss.org/Stephan/swing/index.html是我用来创建事件的示例。
private class RUMAddTextEvent extends AWTEvent {
public static final int EVENT_ID = AWTEvent.RESERVED_ID_MAX + 1;
private int index;
private String str;
private AttributeSet as;
public RUMAddTextEvent(Component target, int index, String str, AttributeSet as) {
super(target, EVENT_ID);
this.index = index;
this.str = str;
this.as = as;
}
public int getIndex() {
return index;
}
public String getStr() {
return str;
}
public AttributeSet getAs() {
return as;
}
}
private class RUMRemoveTextEvent extends AWTEvent {
public static final int EVENT_ID = AWTEvent.RESERVED_ID_MAX + 1;
int index;
int size;
RUMRemoveTextEvent(Component target, int index, int size) {
super(target, EVENT_ID);
this.index = index;
this.size = size;
}
public int getIndex() {
return index;
}
public int getSize() {
return size;
}
}
/**
* Prints a character at a time to the RUMComm window.
*
* @param c
*/
public void simpleOut(Character c) {
cursor.x++;
if (lines.isEmpty()) {
this.lines.add(c.toString());
} else {
this.lines.add(cursor.y, this.lines.get(cursor.y).concat(c.toString()));
this.lines.remove(cursor.y + 1);
}
try {
//doc.insertString(doc.getLength(), c.toString(), as);
eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.postEvent(new RUMAddTextEvent(this, doc.getLength(), c.toString(), as));
getCaret().setDot(doc.getLength());
} catch (Exception ex) {
//Exceptions.printStackTrace(ex);
}
}
/**
* Creates a new line
*/
public void newLine() {
cursor.y++;
cursor.x = 0;
this.lines.add("");
//doc.insertString(doc.getLength(), "\n", null);
eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.postEvent(new RUMAddTextEvent(this, doc.getLength(), "\n", null));
getCaret().setDot(doc.getLength());
}
/**
* Backspace implementation.
*
*/
public void deleteLast() {
int endPos = doc.getLength();
//doc.remove(endPos - 1, 1);
eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.postEvent(new RUMRemoveTextEvent(this, endPos - 1, 1));
cursor.x--;
}
@Override
protected void processEvent(AWTEvent awte) {
//super.processEvent(awte);
if (awte instanceof RUMAddTextEvent) {
RUMAddTextEvent ev = (RUMAddTextEvent) awte;
try {
doc.insertString(ev.getIndex(), ev.getStr(), ev.getAs());
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
} else if (awte instanceof RUMRemoveTextEvent) {
RUMRemoveTextEvent ev = (RUMRemoveTextEvent) awte;
try {
doc.remove(ev.getIndex(), ev.getSize());
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
} else {
super.processEvent(awte);
}
}