简体   繁体   English

如何在Java中使用Canvas根据屏幕宽度和高度绘制字符串或矩形

[英]How do you draw a String or Rectangle according to the screens width and Height with a Canvas in Java

I want to know How could I draw a String or Rectangle (the JFrame is in a full screen completely)我想知道如何绘制字符串或矩形(JFrame 完全处于全屏状态)

Heres what in my Main.java class:这是我的 Main.java 类中的内容:

public static int WIDTH, HEIGHT;
private Window window;
...
public Main() {
    window = new Window("2D Shooter", this);
...
    private void render(){
    BufferStrategy bs = this.getBufferStrategy();

    if(bs == null){
        this.createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.setColor(Color.BLACK);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    handler.render(g);//this calls the render method to render objects

    g.dispose();
    bs.show();
}

Later in a different class I have:后来在另一个班级我有:

public void render(Graphics g){
    ...
    g.setColor(Color.WHITE);
    g.drawString("2D Shooter", ((Main.WIDTH)/2), (Main.HEIGHT/5));
    ...

} }

This Code Works and runs BUT the text is not completely centered I want it to be Centered on top not in the middle.此代码有效并运行,但文本并未完全居中,我希望它居中居中而不是居中。 Thank You!谢谢你!

Use the graphics context's FontMetrics .使用图形上下文的FontMetrics

String s = "2D Shooter";
int w2 = g.getFontMetrics().stringWidth(s) / 2;
int h2 = g.getFontMetrics().getHeight();
g.drawString(s, getWidth() / 2 - w2, h2);

图片

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see http://stackoverflow.com/a/37150783/230513
 */
public class Test {

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setFont(getFont().deriveFont(Font.BOLD, 24f));
                String s = "2D Shooter";
                int w2 = g.getFontMetrics().stringWidth(s) / 2;
                int h2 = g.getFontMetrics().getHeight();
                g.drawString(s, getWidth() / 2 - w2, h2);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(320, 240);
            }
        });
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM