bằng cách sử dụng FontMetrics và TextLayout bạn có thể nhận được kết quả này (xin đọc một bình luận trong các mã)
SwingUtilities thể làm điều đó một cách chính xác quá
tôi sugget để thêm một vài điểm ảnh hơn nữa trên cả hai hướng
thêm ComponentListener vào vùng chứa và thành phầnĐối với sự kiện được đánh giá lại tính toán lại FontMetrics
import java.awt.*;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
public class ShowFontMetrics extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel lTime;
public ShowFontMetrics() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
lTime = new JLabel("88:88");
lTime.setFont(new Font("Helvetica", Font.PLAIN, 88));
FontMetrics fm = lTime.getFontMetrics(lTime.getFont());
TextLayout layout = new TextLayout(lTime.getText(), lTime.getFont(), fm.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
Dimension d = lTime.getPreferredSize();
d.height = (int) (bounds.getHeight() + 100);// add huge amount of pixels just for for fun
d.width = (int) (bounds.getWidth() + 150);// add huge amount of pixels just for for fun
lTime.setPreferredSize(d);
lTime.setVerticalAlignment(SwingConstants.CENTER);
lTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
pane.add(lTime);
setContentPane(pane);
}
public static void main(String[] arguments) {
ShowFontMetrics frame = new ShowFontMetrics();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Bạn có thử modyifying mã để khắc phục vấn đề khi kích thước khung co lại? – camickr