在 JFrame 上用图形对象绘制文本

Draw text with graphics object on JFrame(在 JFrame 上用图形对象绘制文本)

本文介绍了在 JFrame 上用图形对象绘制文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名狂热的程序员,但今天是我的第一堂 Java 课.

I am an avid programmer but today is my first Java lesson.

public void Paint (Graphics g)
{
    if(g instanceof Graphics2D)
    {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
    g.drawString("This is gona be awesome", 200, 200);
}

使用上面的代码,我想在窗口上写一个句子,但它永远不会写.我做错了什么?

With the above code, I want to write a sentence on the window but it never writes. What am I doing wrong?

没关系 - 油漆必须是油漆.我深表歉意.

Never mind - Paint must be paint. I apologize profusely.

推荐答案

在给定的代码中,你想要的是

In the given code, what you want is

 g2d.drawString("This is gona be awesome", 200, 200);
  ^

<小时>

一个工作示例供您参考:


A working example for your reference :

package Experiments;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class MainClass{
  public static void main(String[] args) {
    JFrame jf = new JFrame("Demo");
    Container cp = jf.getContentPane();
    MyCanvas tl = new MyCanvas();
    cp.add(tl);
    jf.setSize(300, 200);
    jf.setVisible(true);
  }
}

class MyCanvas extends JComponent {

  @Override
  public void paintComponent(Graphics g) {
      if(g instanceof Graphics2D)
      {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

        g2.drawString("This is gona be awesome",70,20); 
       }
   }
}

这篇关于在 JFrame 上用图形对象绘制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 JFrame 上用图形对象绘制文本

基础教程推荐