0
我有一個JTextPane,在它上面是我的Swing應用程序中的JSlider。當我拖動滑塊時,我想要JTextPane的當前有脫字符的段落減少/增加其寬度(並相應地調整高度)。我已經實現了下面的代碼,但似乎沒有任何工作。之前我已經實現了一些與此類似的功能,但我認爲我現在缺少一些東西。任何人都可以指出這個錯誤。ParagraphView preferrence change
public class ExtendedParagraphView extends ParagraphView {
/** Maximum width of a single char (assuming monospaced font) {#{@value}}*/
public static final float CHARACTER_WIDTH = (float) 8.0;
/* DELTA is used to adjust the width of the paragraph view */
private float DELTA = (float) 0.0;
public ExtendedParagraphView(Element arg0) {
super(arg0);
}
/**
* Shift the paragraph to the left/right by an amount given by the
* difference between the end and the start position
* @param start
* @param end
*/
public void shiftParagraphView (int start, int end) {
/* The difference in pixel position is always calculated in terms of the
* difference between the end and start position */
DELTA = (float)(end - start) * ExtendedParagraphView.CHARACTER_WIDTH;
}
@Override
public float getPreferredSpan (int axis) {
if (axis == View.Y_AXIS) {
return super.getPreferredSpan(axis);
}
return super.getPreferredSpan(axis) - this.DELTA;
}
}
以下是ExtendedParagraphView內部的shiftParagraphView方法調用時的代碼。
protected void shiftTextPaneElement (int start, int end) {
if (start == end) {
return;
}
int dot = this.textpane.getCaret().getDot();
int mark = this.textpane.getCaret().getMark();
int pos = mark <= dot ? mark : dot;
View view = textpane.getUI().getRootView(textpane);
int n = view.getViewCount();
for (int i = 0; i < n; i++) {
View v = view.getView(i);
if (v instanceof BoxView) {
int m = v.getViewCount();
for (int k = 0; k < m; k++) {
View vv = v.getView(k);
if (vv instanceof ExtendedParagraphView) {
((ExtendedParagraphView) vv).
shiftParagraphView(start, end);
return; //only a single paragraph is currently shifted
}
}
}
}
}
注:經過一些試驗和錯誤以下似乎是工作,
public void shiftParagraphView (int start, int end) {
DELTA = (float)(end - start) * ExtendedParagraphView.CHARACTER_WIDTH;
this.setInsets(getTopInset(), (short) (getLeftInset() + DELTA),
getBottomInset(), getRightInset());
this.getParent().preferenceChanged(this, true, false);
this.getContainer().repaint();
}
感謝您的回覆。事實上,我已經看到你的公開可用的搖擺代碼,它們很棒。我從Java文檔中學到了更多東西。然而,回到問題 - 沒有辦法做到這一點,而不改變模型代碼?我認爲這可以通過僅改變視圖代碼來完成。我認爲在BoxView中有一系列方法 - preferrenceChanged,佈局,isLayoutValid應該這樣做。在這裏,我只想改變擴展段落視圖沿其流軸的寬度。我希望Swing沿瓷磚軸進行調整 – user396089
絕對有可能。 preferenceChanged(...);然後repaint()應該可以正常工作。可以更好地模仿Element change事件。 – StanislavL