java截断字符串_Java用省略号截断字符串的理想方法

本文探讨如何在Java Swing应用中通过`MyLabelUI`类精确测量文本长度,借助`FontMetrics`获取字体信息,并通过`layoutCompoundLabel()`实现模型与视图的转换。实例演示了如何在组件大小改变时实时更新尺寸信息。
摘要由CSDN通过智能技术生成

小编典典

似乎您可以从Java图形上下文的中获得更准确的几何图形FontMetrics。

附录:解决此问题时,可能有助于区分模型和视图。模型是StringUTF-16代码点的有限序列,而视图是一系列字形,以某种字体在某些设备上呈现。

在Java的特定情况下,可以使用JavaSwingUtilities.layoutCompoundLabel()进行翻译。下面的示例拦截了布局调用BasicLabelUI以演示效果。在其他情况下也可以使用实用程序方法,但是FontMetrics必须根据经验确定适当的方法。

替代文字

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.FontMetrics;

import java.awt.GridLayout;

import java.awt.Rectangle;

import java.awt.event.ComponentAdapter;

import java.awt.event.ComponentEvent;

import javax.swing.BorderFactory;

import javax.swing.Icon;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;

import javax.swing.border.LineBorder;

import javax.swing.plaf.basic.BasicLabelUI;

/** @see http://stackoverflow.com/questions/3597550 */

public class LayoutTest extends JPanel {

private static final String text =

"A damsel with a dulcimer in a vision once I saw.";

private final JLabel sizeLabel = new JLabel();

private final JLabel textLabel = new JLabel(text);

private final MyLabelUI myUI = new MyLabelUI();

public LayoutTest() {

super(new GridLayout(0, 1));

this.setBorder(BorderFactory.createCompoundBorder(

new LineBorder(Color.blue), new EmptyBorder(5, 5, 5, 5)));

textLabel.setUI(myUI);

textLabel.setFont(new Font("Serif", Font.ITALIC, 24));

this.add(sizeLabel);

this.add(textLabel);

this.addComponentListener(new ComponentAdapter() {

@Override

public void componentResized(ComponentEvent e) {

sizeLabel.setText(

"Before: " + myUI.before + " after: " + myUI.after);

}

});

}

private static class MyLabelUI extends BasicLabelUI {

int before, after;

@Override

protected String layoutCL(

JLabel label, FontMetrics fontMetrics, String text, Icon icon,

Rectangle viewR, Rectangle iconR, Rectangle textR) {

before = text.length();

String s = super.layoutCL(

label, fontMetrics, text, icon, viewR, iconR, textR);

after = s.length();

System.out.println(s);

return s;

}

}

private void display() {

JFrame f = new JFrame("LayoutTest");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.add(this);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

new LayoutTest().display();

}

});

}

}

2020-09-22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值