将文本放在竞争框中

时间:2014-02-14 15:46:06

标签: java swing graphics paint

我在使用paintComponent方法将String文本放入框架时遇到了问题。

看起来像是:

enter image description here

我不知道为什么它不想把String放在适当的位置,因为我甚至算过像素。

import java.awt.EventQueue;
import javax.swing.JFrame;

public class FrameMain {

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new DrawFrame();
            frame.setVisible(true);
        }
    });

}


public class DrawFrame extends JFrame {

public DrawFrame()
{
    setTitle("Frame with a component containing String");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds (100, 100, 300, 300 );
    DrawComponent draw = new DrawComponent();
    add(draw);

}


public class DrawComponent extends JComponent {

public void paintComponent(Graphics g) {
    g.drawString("First string in component located in frame", WIDTH, HEIGHT);

    final int WIDTH = 175;
    final int HEIGHT = 200;
}

2 个答案:

答案 0 :(得分:3)

g.drawString("First string in component located in frame", WIDTH, HEIGHT);
//final int WIDTH = 175;
//final int HEIGHT = 200;

使用后永远不要定义变量。 WIDTH和HEIGHT是来自其他Swing类的变量,默认为0。

final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);

编辑:

  

我希望String在给定框架大小的位置设置位置,而不是它的位置。

不要做自定义绘画。使用JLabel。

JLabel label = new JLabel("centered");
label.setHorizontalAlignment( JLabel.CENTER );
frame.add(label);

答案 1 :(得分:2)

问题是你有

 final int WIDTH = 175;
 final int HEIGHT = 200;

drawString(..., WIDTH, HEIGHT)

之后声明

正在发生的事情是JComponent还有一个HEIGHTWIDTH,因此drawString正在使用WIDTHHEIGHT JComponet而不是你声明的那些。

如果您想使用自己的,只需将放在 drawString

之前
final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);

<强>更新

要使文字居中,您需要使用FontMetrics。见这里

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        String message = "First string in component located in frame";
        Font font = new Font("impact", Font.PLAIN, 14);
        g.setFont(font);
        FontMetrics fm = g.getFontMetrics(font);
        int stringWidth = fm.stringWidth(message);
        int height = fm.getAscent();
        int x = getWidth()/2 - stringWidth/2;
        int y = getHeight()/2 + height/2;
        g.drawString(message, x, y);    
    }