[英]How to get the height of the entered text in a JTextPane?
有沒有辦法在JTextPane
獲取輸入文本的高度? 像素將是偉大的,但任何可以代表它的價值都可以。 例如,我輸入了JTextPane
:
Lorem Ipsum只是印刷和排版行業的虛擬文本。 自16世紀以來,Lorem Ipsum一直是業界標准的虛擬文本,當時一台未知的打印機采用了類型的廚房,並將其拼湊成一本類型的樣本。 它不僅存在了五個世紀,而且還延續了電子排版,基本保持不變。 它在20世紀60年代隨着包含Lorem Ipsum段落的Letraset表格的推出而普及,最近還推出了包括Lorem Ipsum版本在內的Aldus PageMaker等桌面出版軟件。
有沒有辦法獲得它的長度值(不是它有多少行)? 我需要這個,因為如果我在其中一行中輸入圖片,總高度會發生變化,我希望能夠知道它的確切變化程度。 我使用的JTextPane
有一個StyledDocument
並且沒有html。 我制作了一個SSCCE
但是我使用了兩種不同的字體來代替圖像,以顯示2個JTextPanes
的高度之間的差異。
public class Fonts extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Fonts frame = new Fonts();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Fonts() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setFont(new Font("Tahoma", Font.PLAIN, 11));
StyledDocument doc = textPane.getStyledDocument();
JTextPane textPane_1 = new JTextPane();
textPane_1.setFont(new Font("Tahoma", Font.PLAIN, 12));
textPane_1.setEditable(false);
StyledDocument doc1 = textPane_1.getStyledDocument();
String s = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." +
" Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown" +
" printer took a galley of type and scrambled it to make a type specimen book. It has survived not" +
" only five centuries, but also the ";
try {
doc.insertString(0, s, null);
doc1.insertString(0, s, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 214, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textPane_1, GroupLayout.PREFERRED_SIZE, 208, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textPane_1, Alignment.LEADING)
.addComponent(textPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))
.addContainerGap())
);
contentPane.setLayout(gl_contentPane);
}
}
那么有沒有辦法獲得2個JTextPanes的高度?
使用此處描述的方法測量JEditorPane / JTextPane的固定寬度內容高度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.