如何将字符串插入矩形?

时间:2013-12-30 20:50:19

标签: java string rectangles

这是我的代码:

package com.Bench3.simplyMining;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Keying extends JPanel {

    private static final long serialVersionUID = 1L;

    public Rectangle miningRock;
    public Rectangle Rocks;
    public int mRockW = 150;
    public int mRockH = 100;
    public long rocks = 0;
    public String rockAmount = rocks + " Rocks";

    public Keying(Display f, Images i){
        miningRock = new Rectangle(0, 658, mRockW, mRockH);
        Rocks = new Rectangle(1024, 0, 0, 0);

        f.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e){

            }

            public void keyReleased(KeyEvent e){
                /* if(e.getKeyCode() == KeyEvent.VK_A){
                    left = false;
                } -- Used for setting key combinations and stuff */
            }
        });
    }

    public void paintComponent(Graphics g){
        if(Main.f.i.imagesLoaded){
        super.paintComponent(g);

        g.drawImage(Main.f.i.miningRock, miningRock.x, miningRock.y, miningRock.width, miningRock.height, null);

        g.drawString(rockAmount, Rocks.x, Rocks.y);

        this.setBackground(Color.WHITE); // Sets background color
        // g.setColor(Color.WHITE); -- Used for setting colors

        repaint();
        }
    }
}

我一直在尝试使用g.drawString()将字符串“rockAmount”插入到矩形“Rocks”中,但是当我尝试它时不会在矩形内部输出字符串。我做错了什么?

编辑:解决了,感谢Paul提供答案。

2 个答案:

答案 0 :(得分:1)

文本的y位置表示基线减去字体上升。这意味着文本似乎呈现在y位置之上。

渲染文字时,您需要考虑文本和字体的FontMetrics

例如,以下内容在左侧的矩形x / y位置呈现文本,然后计算x / y位置,使其可以使文本在给定矩形中居中。

enter image description here

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestTextRect {

    public static void main(String[] args) {
        new TestTextRect();
    }

    public TestTextRect() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            int mRockW = 150;
            int mRockH = 100;
            int x = ((getWidth() / 2) - mRockW) / 2;
            int y = (getHeight() - mRockH) / 2;
            badRect(g2d, x, y, mRockW, mRockH);

            x = (getWidth() / 2) + (((getWidth() / 2) - mRockW) / 2);
            goodRect(g2d, x, y, mRockW, mRockH);

            g2d.dispose();
        }

        protected void badRect(Graphics2D g2d, int x, int y, int mRockW, int mRockH) {
            g2d.drawRect(x, y, mRockW, mRockH);
            String text = "rockAmount";

            g2d.drawString(text, x, y);
        }

        protected void goodRect(Graphics2D g2d, int x, int y, int mRockW, int mRockH) {
            g2d.drawRect(x, y, mRockW, mRockH);
            FontMetrics fm = g2d.getFontMetrics();
            String text = "rockAmount";

            x = x + ((mRockW - fm.stringWidth(text)) / 2);
            y = (y + ((mRockH - fm.getHeight()) / 2)) + fm.getAscent();
            g2d.drawString(text, x, y);
        }

    }

}

请查看Working with text APIs了解详情

您应该避免在repaint方法中调用repaint或任何可能调用paintXxx的方法。由于在Swing中计划绘制的方式,这将设置一个无限循环,最终会消耗CPU周期并使您的应用程序无响应...

你也应该总是打电话给super.paintComponent,不管你想做什么......

我还建议Key bindings超过KeyListener因为它可以更好地控制焦点水平

答案 1 :(得分:0)

您需要添加矩形宽度和高度的x和y位置1/2。

g.drawString(rockAmount,Rocks.x+rectangleWidth/2,Rocks.y+rectangleHeight/2);