62,615
社区成员
发帖
与我相关
我的任务
分享
import javax.swing.*;
import java.awt.*;
public class ResizeLabel extends JLabel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 60);
JLabel label = new ResizeLabel();
label.setText("label");
label.setOpaque(true);
label.setIcon(new ImageIcon("web.gif"));
frame.add(label);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paintComponent(Graphics g) {
// super.paintComponent(g);
int height = getHeight();
Font oldFont = getFont();
setFont(new Font(oldFont.getName(), oldFont.getStyle(), height));
Icon icon = getIcon();
String text = getText();
if (icon != null && icon instanceof ImageIcon) {
double scale = (double)icon.getIconWidth() / icon.getIconHeight();
int width = (int)(height * scale);
ImageIcon image = (ImageIcon)icon;
g.drawImage(image.getImage(), 0, 0, width, height, null);
g.drawString(text, width, (int)(height * 0.85));
} else {
g.drawString(text, 0, (int)(height * 0.85));
}
}
}