2

我现在只是在浏览一些基本教程。现在的人想要一个能把你的名字画成红色的图形程序。我试图创建一个扩展 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);

    }
}

并使用使用 JFrame 的 NameViewer 类来显示名称:

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);
    }
} 

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

非常感谢!

4

2 回答 2

1

You need to override the method paintComponent rather than paintMessage. Adding the @Override annotation over the method will show that paintMessage is not a standard method of JComponent. Also you may want to reduce the y-coordinate in your drawString as the text is currently not visible due to the additional decoration dimensions of the JFrame. Finally remember to call super.paintComponent to repaint the background of the component.

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

See: Painting in AWT and Swing

于 2012-12-11T17:50:58.173 回答
0

您需要在之后添加此行public void paintMessage(Graphics g){

super.paint(g);

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

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

于 2012-12-11T17:44:35.100 回答