我有一个JTextPane,在我的Swing应用程序中有一个JSlider。当我拖动滑块时,我想要当前具有插入符号的JTextPane的段落减小/增加其宽度(并相应地调整高度)。我已经实现了以下代码,但似乎没有任何工作。我之前已经实现了类似的功能,但我认为我现在缺少一些东西。任何人都可以指出错误。
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();
}
答案 0 :(得分:2)
使用yourStyledDocument.setParagraphAttributes()
代替指定所需的左右缩进。