import javax.swing.*;
import java.awt.*;
public class TestTriangle extends JFrame {
public TestTriangle() {
JTextArea textArea = new JTextArea();
textArea.setColumns(1);
textArea.setRows(10);
textArea.setLineWrap(false);
textArea.setWrapStyleWord(true);
add(textArea);
}
public static void main(String[] args) {
TestTriangle frame = new TestTriangle();
frame.setTitle("Number Triangle");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我试图让输出成为一个循环。现在当我运行这个时,我只得到一个带有空白文本区域的框架。我需要文本区域按照这样的顺序填充数字。
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
etc..
我无法找到关于此的任何信息。
答案 0 :(得分:1)
希望以下示例可以帮助您。
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class TestTriangle extends JFrame {
public TestTriangle() {
JTextArea textArea = new JTextArea();
//textArea.setColumns(1);
//textArea.setRows(10);
textArea.setText(buildText());
textArea.setLineWrap(false);
textArea.setWrapStyleWord(true);
add(textArea);
}
public static void main(String[] args) {
TestTriangle frame = new TestTriangle();
frame.setTitle("Number Triangle");
frame.setSize(200, 195);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static String buildText()
{
StringBuilder sb = new StringBuilder();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
sb.append(j);
}
sb.append('\n');
}
return sb.toString();
}
}
答案 1 :(得分:1)
这个问题听起来非常像家庭作业...... 无论如何,使用JScrollPane以允许查看文本区域。
JScrollPane sc=new JScrollPane(textArea);
add(sc);
for(int i=1; i<=10; i++) {
for(int j=1; j<=i; j++) {
textArea.append(j+" ");
}
if(i<10)
textArea.append("\n");
}