JScrollPane formatting to show Pascals Triangle

2020-05-03 10:07发布

问题:

so I want to make my Jscrollpane to show Pascals triangle. I have this:

labelPanel= new JPanel();
lRows = new JLabel[n];

for (int i=0;i<n;i++){
    lRows[i]=new JLabel(Arrays.toString(tri.tri[i]));
    labelPanel.add(lRows[i]);
}

But it's not what I want and I am not sure how to fix that, picture included. Any help?

回答1:

By default, JPanel uses a flow layout. To get the vertical arrangement you are looking for, you should be able to do this by using a BoxLayout with a vertical orientation on your labelPanel, then add your JLabel rows.

labelPanel= new JPanel();
//set this up to order things vertically
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
lRows = new JLabel[n];

for (int i=0;i<n;i++){
    lRows[i]=new JLabel(Arrays.toString(tri.tri[i]));
    //to center your label, just set the X alignment
    lRows[i].setAlignmentX(Component.CENTER_ALIGNMENT)
    labelPanel.add(lRows[i]);
}

I also threw in a line to center the rows like your picture. Component comes from the java.awt package.

You can read up on the different layout managers available by default in the Java Tutorial



回答2:

  1. Use a JTextArea
  2. Give it a monospaced font, i.e., Font.MONOSPACED
  3. Append your lines of text to the JTextArea, similar to how you'd do this in the console.
  4. Put the JTextArea into a JScrollPane
  5. Voilà. You're done.


  6. If you need to use JLabels, then put them in a JPanel that uses GridLayout with enough columns to show your bottom row.

  7. If you did this, you'd be putting empty JLabels in every other cell, so that the cells branch correctly.


回答3:

The easiest solution is to rotate the triangle to make it look like:

1   1   1   1   1   1   1

1   2   3   4   5   6   

1   3   6   10  15  

1   4   10  20   

1   5   15  

1   6   

1   

However, if you must print sth like this

I did it this way:

for (int i = 0; i<n; i++){
    for (int j = 0; j<Triangle.trojkat[i].length; j++){
        sb.append(Triangle.trojkat[i][j]);
        len = String.valueOf(Triangle.trojkat[i][j]).length();
        while (12-len>0){
            sb.append(" ");
            len++;
        }
        //sb.append(" ");
    }
    TriangleRes[i] = new JLabel(sb.toString(), JLabel.CENTER);
    TriangleRes[i].setFont(new Font("Serif",Font.PLAIN,8));
sb = new StringBuilder();
}

Let me explain: I decided, that I want my triangle print beautifuly for the size smaller that 35. Then I've checked, that the numbers in such a triangle come up to 10 digits. Then, when I added next number to the existing row, I checked it's length and while total length wasn't 12 yet, I add spaces. This lead to the triangle that you have attached on the picture.

If this is for Ph.D Macyna classes, just post a question on a group and I'll respond :)