【问题标题】:Trying to use drawString method to print a name尝试使用 drawString 方法打印名称
【发布时间】:2012-12-11 17:41:24
【问题描述】:

我现在正在学习一些基本教程。现在的人想要一个能把你的名字画成红色的图形程序。我试图创建一个扩展 JComponent 的 NameComponent 类,并使用 drawString() 方法来做到这一点:

import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;

public class NameComponent extends JComponent {

    public void paintMessage(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(Color.RED);
    g2.drawString("John", 5, 175);

    }
}

并使用一个 NameViewer 类,它利用 JFrame 来显示名称:

import javax.swing.JFrame;

public class NameViewer {

public static void main (String[] args) {

    JFrame myFrame = new JFrame();
    myFrame.setSize(400, 200);
    myFrame.setTitle("Name Viewer");
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    NameComponent myName = new NameComponent();
    myFrame.add(myName);

    myFrame.setVisible(true);
    }
} 

...但是当我运行它时,框架出现空白!谁能让我知道我在这里做错了什么?

非常感谢!

【问题讨论】:

    标签: java graphics drawstring


    【解决方案1】:

    您需要重写方法paintComponent 而不是paintMessage。在方法上添加@Override 注解将表明paintMessage 不是JComponent 的标准方法。此外,您可能希望减少 drawString 中的 y 坐标,因为由于 JFrame 的附加装饰尺寸,文本当前不可见。最后记得调用super.paintComponent重新绘制组件的背景。

    @Override
    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Graphics2D g2 = (Graphics2D) g;
       g2.setColor(Color.RED);
       g2.drawString("John", 5, 100);
    }
    

    见:Painting in AWT and Swing

    【讨论】:

      【解决方案2】:

      你需要在public void paintMessage(Graphics g){后面加上这一行:

      super.paint(g);

      这告诉 Java 使用超类 (JComponent) 来绘制消息。

      你还需要调用你的方法paintComponents()而不是paintMessage()

      【讨论】:

      • 没问题。只要记住为好的答案投票并接受最佳答案(提示,提示)
      猜你喜欢
      • 2020-08-02
      • 2017-12-11
      • 1970-01-01
      • 2015-11-02
      • 2012-06-16
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多