在JLable中加入文字和图片,如何实现在水平方向,一个左对齐,一个右对齐呢?
3条回答 默认 最新
- g_johnson_lee 2010-03-18 10:10关注
废话少说,见代码:
[code="java"]
package org.zergle.test;import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;public class TestJLabelFrame extends JFrame {
XLabel lbl = new XLabel("内容");public TestJLabelFrame() { super(); JPanel container = (JPanel) this.getContentPane(); lbl.setIcon(new ImageIcon(this.getClass().getResource("icon.gif"))); container.add(lbl, BorderLayout.CENTER); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(640, 480); } public static void main(String[] args) { new TestJLabelFrame().setVisible(true); }
}
class XLabel extends JLabel {
public XLabel() {} public XLabel(String text) { super(text); } public void paint(Graphics g) { String text = this.getText(); Icon icon = this.getIcon(); Rectangle2D bounds = this.getBounds(); FontMetrics fm = this.getFontMetrics(new Font("宋体", Font.PLAIN, 12)); Rectangle2D rect = fm.getStringBounds(text, 0, text.length(), g); int y = (int) (bounds.getHeight() - rect.getHeight()) / 2; g.drawString(text, 0, y); if (icon != null) { int x = (int) bounds.getWidth() - icon.getIconWidth(); y = (int) (bounds.getHeight() - icon.getIconHeight()) / 2; icon.paintIcon(this, g, x, y); } g.dispose(); }
}
[/code]哈哈,准备接分 :wink:
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 网络科学导论,网络控制
- ¥15 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)