在Java 8中,如果我將JTextPane的寬度設定為與FontMetrics.stringWidth回傳的值相匹配,文本就會完全適合并被繪制在一條線上。但是,在 Java 17 中,使用同樣的代碼,文本中的最后一個字被包裹起來。以下是我的代碼:
import java.awt.*;
import javax.swing.*;
public class SimpleTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleTest::test)。
}
private static void test() {
Test test = new Test()。
JPanel panel =new JPanel(new BorderLayout() )。
panel.add(test)。
JFrame frame = new JFrame() 。
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)。
frame.setSize(250, 100)。
frame.setLocationRelativeTo(null)。
frame.setVisible(true)。
}
private static class Test extends JComponent {
private static final long serialVersionUID = 1L;
private JTextPane textPane;
private Test() {
textPane = new JTextPane() 。
textPane.setFont(new Font("Arial", Font.BOLD, 24) )。)
textPane.setBorder(null)。
textPane.setContentType("text/plain")。
}
@Override; }
protected void paintComponent(Graphics g) {
String labelText = "this is a TEST"。
textPane.setText(labelText)。
textPane.setLocation(new Point(0, 0) )。
FontMetrics fm = textPane.getFontMetrics(textPane.getFont() ) 。
int width = fm.stringWidth(labelText)。
int height = fm.getHeight()。
textPane.setSize(width, height);
Graphics2D g2D = (Graphics2D)g. create(0, 0, width, height * 2) 。
textPane.paint(g2D)。
g2D.dispose()。
}
}
}
是否有可能使行為一致?
uj5u.com熱心網友回復:
要想獲得寬度,請這樣呼叫:
int width = textPane.getPreferredSize().width;
而不是這樣:
int width = fm.stringWidth(labelText)。
uj5u.com熱心網友回復:
我不知道它的具體情況,但我100%確定在Java 8中,方法fm.stringWidth(labelText)比在Java 11中大1,因為如果我做fm.stringWidth(labelText) 1,那么換行就可以了。只要改變這一行,你的代碼就能作業。
請讓我知道這是否有幫助。
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/310289.html
標籤:
