0
因此,在我的應用程序中,我使用了一個自定義組件,它是JTextPane的擴展。我需要擴大這個造型。我已設法關閉文字包裝,因爲此組件旨在用作JTextField,即不多行。JTextPane - 無需JScrollPane滾動可見文本
然而,我正面臨的問題是,如果文本跨越可見區域,JTextPane在JScrollpane內部未使用時不會很好地處理非文字包裝文本。使用JTextField時,可見區域外的文本無法移動到可以使用的位置。
我不想使用JScrollpane,因爲我有很多假設JTextComponent的遺留代碼。
所以我的問題是,有沒有一種方法保持可見區域與插入位置內聯,以便當打字達到可見邊緣或嘗試選擇跨越可見區域的文本時,該文本移動到視圖中JTextField呢。
我的問題的一個工作示例如下。它顯示JTextPane上方的JTextField。如果您在文本字段中輸入內容,則會看到可見區域隨文本一起移動。如果您在文本窗格中輸入,則不會發生。
此外,即時通訊在java中提前做這個7
感謝。
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class NoAutoScroll {
public NoAutoScroll() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.setText("This text field can show the text outside the visible area.");
textField.setPreferredSize(new Dimension(150, 30));
JTextPane textPane = new JTextPane();
textPane.setEditorKit(new MyEditorKit());
textPane.setText("This text pane cannot show the text outside the visible area.");
textPane.setPreferredSize(new Dimension(150, 30));
textPane.setBorder(textField.getBorder());
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
mainPanel.add(new JLabel("JTextField"), constraints);
constraints.gridx = 1;
constraints.gridy = 0;
mainPanel.add(textField, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
mainPanel.add(new JLabel("JTextPane"), constraints);
constraints.gridx = 1;
constraints.gridy = 1;
mainPanel.add(textPane, constraints);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public class MyViewFactory implements ViewFactory {
private final class NonBreakingLabelView extends LabelView {
private NonBreakingLabelView(Element elem) {
super(elem);
}
@Override
public int getBreakWeight(int axis, float pos, float len){
return BadBreakWeight;
}
}
@Override
public View create(final Element elem) {
String kind = elem.getName();
if (kind != null) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new NonBreakingLabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
// default to text display
return new LabelView(elem);
}
}
@SuppressWarnings("serial")
public class MyEditorKit extends StyledEditorKit {
@Override
public ViewFactory getViewFactory() {
return new MyViewFactory();
}
}
public static void main(String[] args) {
new NoAutoScroll();
}
}
+1同意。帶有兩個不可見的JScrollBars的JScrollPane。 – StanislavL