I am having trouble coming up with formula to print a triangle of numbers in a panel. I can print them to a specified number, of my choosing, but I can't seem to come up with a formula to print them out according to the size of the frame and then have them repainted when the panel is resized, to fit the panel.

Example:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
. . . . . . etc.

I have included in my code the way that I am able to print them, which is not right. I also have some code in there that I was trying to formulate, but I have it in /* */ just so you can see what I was trying, even though it was probably way off.

Code:

import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TrashableTest extends JFrame {

    public TrashableTest() {

        Container orderedNums = getContentPane();
        orderedNums.setLayout(new GridLayout(3, 3));


        for (int i = 0; i < 1; i++) {
            orderedNums.add(new TriangleNumbers());
        }
    }

    public static void main(String[] args) {

        JFrame frame = new TrashableTest();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setTitle("Triangle of Numbers");
        frame.setSize(400, 400);

    }
}

class TriangleNumbers extends JPanel {

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);


        /*int z[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        String w = "1 2 3 4 5 6 7 8 9 10";
       // w.toCharArray();
        for (int i = 1; i < 10; i++) {
            g.drawChars(w.toCharArray(), 1, w.length() - 1, 20, 20);
            //g.drawC
        }*/



        String a = "1";
        String b = "2";
        String c = "3";
        String d = "4";
        String e = "5";
        String f = "6";
        String h = "7";
        String k = "8";
        String l = "9";
        String m = "10";
        g.drawString(a, 10, 10);
        g.drawString(a + b, 10, 20);
        g.drawString(a + b + c, 10, 30);
        g.drawString(a + b + c + d, 10, 40);
        g.drawString(a + b + c + d + e, 10, 50);
        g.drawString(a + b + c + d + e + f, 10, 60);
        g.drawString(a + b + c + d + e + f + h, 10, 70);
        g.drawString(a + b + c + d + e + f + h + k, 10, 80);
        g.drawString(a + b + c + d + e + f + h + k + l, 10, 90);
        g.drawString(a + b + c + d + e + f + h + k + l + m, 10, 100);








    }
}

To fill a component with characters you need the size of the component and you need to get the size of the characters in pixels. See the FontMetrics class. It has many methods for getting sizes. Use the Graphics class getFontMetrics method to get the needed object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.