JAVA,在框架中以递增字体显示短语

JAVA, display phrase in increasing font sizes in a frame

我在正确获取此代码 运行 时遇到问题。它编译并且最初框架正确显示。问题是,当我通过最大化或拖动框架的一侧手动调整框架大小时,文本消失了。我正在使用 jGRASP,不确定这是否是问题所在。该代码对我来说似乎很有意义,而且就像我说的那样,它可以编译(我知道这不一定是正确的)。我在这方面还是个新手,所以如果有人能指出我正确的方向,我将不胜感激。

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

public class JFontSizes extends JFrame {
   int x = 5;
   int y = 50;
   String homework = "This is the first homework assignment";
   public JFontSizes() {
      super("Increasing Font Sizes");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
   }   
   public void paint(Graphics brush) {
      super.paint(brush);
      // This works sometimes. I am not sure if it is a jGRASP issue or something else.
      // If I resize the frame, the text disappears, and I cannot get the text to start at the top of the frame
      for(int n = 6; n<= 20; ++n) {
         brush.setFont(new Font("Serif", Font.PLAIN, n));
         brush.drawString(homework, x, y);
         y += 15;
      }   
   }              
   public static void main(String[] args) {
      JFontSizes frame = new JFontSizes();
      frame.setSize(400, 500);
      frame.setVisible(true);      
   }   
}

第一次调用paint()时,y的值为5,循环递增。所以在离开 paint() 之前它的值将是 275。

但是当你调整你的框架时 paint() 被再次调用,这次 y 的值为 275 并且当 brush.drawString(homework, x, y); 被调用时 homework 被打印在左上角底部 275px 处.

所以你需要做的就是每次都重新初始化 y :

public void paint(Graphics brush) {
    y = 50;
    ....

编辑:
正如 camickr 所评论的那样,您应该覆盖 paintComponent(...) 而不是 paint(...) 直到您有一些特定的理由来覆盖 paint()。
你的意思是你不能在顶部打印文本(即使在开始时),那是因为你已经用 50 初始化了 y。这意味着文本将在距离顶部 50px 处绘制。