JLabel1???à???×?1??ˉD§1?
ê±??:2010-12-25 BlogJava ×?×?í£í£ó?èy?ê
ê×?èòa????ò???????£oò???×?·?′??ú?????ú?á???D?ù??μ?????£?±è·??μè?ò???JLabelà???μ?Text?ù??μ??íoí??£?·?·¨è???: £¨?÷òaó?μ?FontMetricsàà£?
import??java.awt.FontMetrics;
import??javax.swing.JLabel;
JLabel??label??=??new??JLabel("test??Label??");
FontMetrics??metrics??=??label.getFontMetrics(label.getFont());
int??textH??=??metrics.getHeight();??//×?·?′?μ???£???oí×?ì?óD1?
int??textW??=??metrics.stringWidth(label.getText());??//×?·?′?μ??í
í¨3£?é????£?ò?????????3???????£
??ì?′ú??è???£o
Test.java
import??java.awt.BorderLayout;
import??java.awt.Color;
import??java.awt.Dimension;
import??java.awt.FontMetrics;
import??java.awt.event.ComponentAdapter;
import??java.awt.event.ComponentEvent;
import??javax.swing.JFrame;
import??javax.swing.JLabel;
import??javax.swing.JPanel;
public??class??Test??{
???????? private??JFrame??frame;
???????? private??String??scrolledText;
???????? private??String??str??=??"1??ˉ??×???Demo";
???????? /**??*//**
?????????? *??Launch??the??application
?????????? *??@param??args
?????????? */
???????? public??static??void??main(String??args[])??{
???????????????? try??{
???????????????????????? Test??window??=??new??Test();
???????????????????????? window.frame.setVisible(true);
???????????????? }??catch??(Exception??e)??{
???????????????????????? e.printStackTrace();
???????????????? }
???????? }
???????? /**??*//**
?????????? *??Create??the??application
?????????? */
???????? public??Test()??{
???????????????? initialize();
???????? }
???????? /**??*//**
?????????? *??Initialize??the??contents??of??the??frame
?????????? */
???????? private??void??initialize()??{
???????????????? frame??=??new??JFrame();
???????????????? frame.setBounds(100,??100,??500,??375);
???????????????? frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
???????????????? final??JPanel??panel??=??new??JPanel();
???????????????? panel.setBackground(Color.WHITE);
???????????????? panel.setLayout(new??BorderLayout());
???????????????? frame.getContentPane().add(panel,??BorderLayout.NORTH);
???????????????? final??JLabel??label??=??new??JLabel();
???????????????? label.setText("New??JLabel");
???????????????? panel.add(label);
???????????????? label_scrolledText(label);
???????????????? //??μ±′°ì?±??ˉê±òa??D???labelμ?1??ˉ??×???DDéè??
???????????????? frame.addComponentListener(new??ComponentAdapter()??{
???????????????????????? public??void??componentResized(ComponentEvent??arg0)??{
???????????????????????????????? label_scrolledText(label);
???????????????????????? }
???????????????? });
???????? }
???????? /**??*//**
?????????? *??1??ˉ??×?
?????????? *??@param??label
?????????? */
???????? public??void??label_scrolledText(JLabel??label)??{
???????????????? this.scrolledText??=??this.str;
???????????????? label.setText(scrolledText);
???????????????? FontMetr
|