在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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
- ¥15 Oracle触发器记录修改前后的字段值
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图
- ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
- ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
- ¥15 CSAPPattacklab
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图
- ¥15 stm32开发clion时遇到的编译问题