且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在新的一行打印g.Drawstring for循环中运行时?

更新时间:2023-12-04 10:56:46

您想要做的是有列表 字符串。希望你已经了解了列表,你可以使用数组但加入他们动态吸。

What you want to do is have List of Strings. Hopefully you have learned about Lists, you can use arrays but adding to them dynamically sucks.

使用列表,你可以做这样的事情在你的最后一个循环

Using a list you could do something like this in your last loop

public class assignment... {
    private List<String> list = new ArrayList<>();
    ....
    public void actionPerfomed(ActionEvent e) {
        ....
        // instead of this
        //for (b = 0; b < pr_count.length; b++){
            //if (pr_count[b] > 0) {
            //pr_name = ("There are " + pr_count[b] + " words of length " + b); 
            //repaint();
        //}

        // do this
        for (b = 0; b < pr_count.length; b++){
            if (pr_count[b] > 0) {
                list.add("There are " + pr_count[b] + " words of length " + b);
            }
        }
        repaint();  // repaint after all is added to the list.
    }
}

在你的油漆方法,你可以再通过列表循环。你需要做虽然什么,每一行,你需要更新位置自其移动到下一行。既然你不能使用你还没有学到的东西,我不会建议的FontMetrics 它可以让你衡量字母的高度。而不是仅仅猜测的高度和递增的每一行。事情是这样的。

In your paint method you could then loop through the list. What you need to do though, for each line, you need to update the y position since its moving to the next line. Since you can't use things you haven't learned, I won't suggest FontMetrics which lets you measure the height of letters. Instead just guess the height and increment the y for each line. Something like this

public void paint(Graphics g) {
    int y = 20;
    for (String s : list) {
        g.drawString(s, 20, y);
        y += 15;  // 15 is just a guess. Play with it til you get it right
    }
}