FontMetrics का उपयोग करने और TextLayout आप इस उत्पादन प्राप्त कर सकते हैं (कृपया कोड में कोई टिप्पणी पढ़ें) द्वारा
SwingUtilities ऐसा कर सकते हैं सही ढंग से भी
मैं दोनों दिशाओं पर इसके अलावा कुछ पिक्सल जोड़ने के लिए सुझाने
कंटेनर के लिए ComponentListener जोड़ सकते हैं और componentResized घटना पर पुनर्गणना 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);
}
}
क्या आप जब फ्रेम आकार सिकुड़ता है इस समस्या को ठीक करने के लिए कोड modyifying कोशिश? – camickr