我的类GraphicButton.java创建了一个带有特定文本和字体以及矩形边框的自定义JButton.我的问题是在字符串的最后一个字符和我想要删除的边框的末尾之间有一些额外的空间.
以下是使用字符串“PLAY”和字体FFF Forward(直接下载链接)添加到JFrame的GraphicButton实例.红线是我想要移除的空间.
这是我正在使用的代码(省略了JFrame创建和设置):
GraphicButton.java:
public class GraphicButton extends JButton {
private static final long serialVersionUID = 1L;
//Fields
private String text;
private Font font;
//Constructor
public GraphicButton(String text,Font font) {
super(text);
this.text = text;
this.font = font;
//Setting preferred size here.
this.setPreferredSize(new Dimension(this.getFontMetrics(font).stringWidth(text),this.getFontMetrics(font).getAscent()));
}
@Override
public void paintComponent(Graphics g) {
g.setFont(this.font);
//Draw text
g.drawString(this.text,this.getHeight());
//Draw border
g.drawRect(0,this.getWidth(),this.getHeight());
}
}
我在使用Java 1.8的Mac上运行Eclipse.
最佳答案
您可以使用TextLayout来获得更好的宽度计算.
在下面的示例中,您可以看到使用TextLayout和FontMetrics之间的不同:
import javax.swing.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
public class DrawTest extends JPanel
{
String text;
public DrawTest(String text)
{
this.text = text;
// setFont( new Font("Arial",Font.PLAIN,24) );
setFont( new Font("Monospaced",24) );
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setFont( getFont() );
g2d.setPaint(Color.RED);
// Draw text using FontMetrics
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D rect = fm.getStringBounds(text,g2d);
rect.setRect(rect.getX() + 100,rect.getY() + 50,rect.getWidth(),rect.getHeight());
g2d.draw(rect);
// Draw text using TextLayout
g2d.setPaint(Color.BLACK);
Point2D loc = new Point2D.Float(100,50);
FontRenderContext frc = g2d.getFontRenderContext();
TextLayout layout = new TextLayout(text,getFont(),frc);
layout.draw(g2d,(float)loc.getX(),(float)loc.getY());
Rectangle2D bounds = layout.getBounds();
bounds.setRect(bounds.getX()+loc.getX(),bounds.getY()+loc.getY(),bounds.getWidth(),bounds.getHeight());
g2d.draw(bounds);
}
private static void createAndShowUI()
{
DrawTest text = new DrawTest("This is some ugly test i");
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.add( text );
frame.setSize(400,200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
你也不应该:
>设置首选大小.相反,您应该重写getPreferredSize()方法以返回大小
>在绘画方法中设置字体.所有组件都支持setFont()方法.所以只需在构造函数中设置Font.