java - 有没有办法让多行 JLabel 文本围绕图标流动?
问题描述
目前在我的项目中,我有多个 JLabel,每个都有自己的文本和图标
我遇到的问题是图标占据了整个左侧
我想要达到的效果是让文字围绕图标流动
JLabel 可以实现这种效果吗?如果没有,是否可以使用任何其他组件?
解决方案
如果这是一个 JLabel 而不是文本可编辑的 JTextArea,我将使用 HTMLed JLabel 而不是 JEditorPane。
public static void main(String[] args) throws Exception {
String imageUrl = "https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/512x512/person.png";
Image sourceImage = ImageIO.read(new URI(imageUrl).toURL()).getScaledInstance(25, 25,
Image.SCALE_SMOOTH);
//Write the image to disk locally
File fileWithImage = File.createTempFile("myicon", ".png");
fileWithImage.deleteOnExit();
ImageIO.write(toBufferedImage(sourceImage), "png", fileWithImage);
String lorem = "Lorem Ipsum is simply dummy text of the printing<br>"
+ " and typesetting industry. Lorem Ipsum has been the industry's<br>"
+ " standard dummy text ever since the 1500s, when an unknown printer<br>"
+ " took a galley of type and scrambled it to make a type specimen book.<br>"
+ " It has survived not only five centuries, but also the leap into electronic<br>"
+ " typesetting, remaining essentially unchanged. It was popularised in the 1960s<br>"
+ " with the release of Letraset sheets containing Lorem Ipsum passages ";
String imgTag = "<img src=\"" + fileWithImage.toURI() + "\">";
final String htmlText = "<html>" + imgTag + " " + lorem;
JOptionPane.showMessageDialog(null, new JLabel(htmlText));
}
public static BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
return bimage;
}
运行上面的例子。您将得到以下图像:
图像转换取决于您如何拥有图标,但想法是这样的。将图像写入临时文件,使其成为 URI 并将其作为 HTML 文本添加到标签中。
推荐阅读
- json - 插入一个大的字符串 JSON 作为突变 GRAPHQL 的输入
- spring - 创建名为“inMemoryDatabaseShutdownExecutor”的 bean 时出错:
- sql - SQL。如何使用循环?PostgreSQL
- c# - 如何在 c# 上将子集合添加到 firestore?
- node.js - 如何修复“类型错误无法读取未定义的属性 0”?
- android - 公用文件夹中保存的文件可见,但 PC 无法访问
- java - 如何在不点击的情况下在 arCore 平面中设置 3d 模型
- php - Laravel Slack 按需通知;在哪里设置 webhook?
- c# - 使用 C#,Strting.Trim() 没有删除我的网络刮板中的前导和尾随空格
- firebase - 服务比页面慢 | 离子 4 | 火力基地