包含HTML的标签的行为在首次绘制到BufferedImage时似乎会发生变化。在下面的代码中,仅显示文本的前两行。随着添加更多<br>
个中断,行数会增加。它似乎是计算预包装而不是后包装的行数。
如果标签直接涂在组件的图形上(即注释行),那么它可以正常工作。
如果行为被绘制为BufferedImage
图形而不是JComponent
,行为会发生什么变化。
public class HTMLFormatting {
public static void main(String[] args) {
JFrame frame = new JFrame("HTML Formatting");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(200, 330));
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel() {
public void paint(Graphics g) {
BufferedImage image = new BufferedImage(200, 300, BufferedImage.TYPE_INT_ARGB);
JLabel label = new JLabel("<html>A piece of text that requires wrapping because "
+ "it is too long for a single line of a label and is a test of formatting."
+ "<br>A second line.</html>");
label.setVerticalAlignment(JLabel.TOP);
JPanel layoutPanel = new JPanel(new BorderLayout());
layoutPanel.setSize(new Dimension(200, 300));
layoutPanel.add(label, BorderLayout.NORTH);
layoutPanel.doLayout();
label.paint(image.getGraphics());
g.drawImage(image, 0, 0, null);
// label.paint(g);
}
};
frame.add(panel, BorderLayout.CENTER);
JButton exitButton = new JButton("Exit");
frame.add(exitButton, BorderLayout.SOUTH);
exitButton.addActionListener(ev -> System.exit(0));
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:3)
可以使用HTML样式(CSS)为body
设置宽度。这反过来将决定要渲染的行数,以及从中确定标签的首选高度。
在CSS中设置宽度可以避免计算标签中出现换行符的位置(或最佳尺寸)。
import javax.swing.*;
public class FixedWidthLabel {
public static void main(String[] srgs) {
final String s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu nulla urna. Donec sit amet risus nisl, a porta enim. Quisque luctus, ligula eu scelerisque gravida, tellus quam vestibulum urna, ut aliquet sapien purus sed erat. Pellentesque consequat vehicula magna, eu aliquam magna interdum porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sollicitudin sapien non leo tempus lobortis. Morbi semper auctor ipsum, a semper quam elementum a. Aliquam eget sem metus.";
final String html1 = "<html><body style='width: ";
final String html2 = "px'>";
Runnable r = new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(
null, new JLabel(html1 + "200" + html2 + s));
JOptionPane.showMessageDialog(
null, new JLabel(html1 + "300" + html2 + s));
}
};
SwingUtilities.invokeLater(r);
}
}