【发布时间】:2017-06-03 01:25:18
【问题描述】:
好的,所以我正在制作一个需要我将变量打印到图形界面的程序。因为我不知道会有多少变量,所以我想使用 for 循环。问题是当我这样做时,我之前打印的文本消失了。即使我在 GUI 的不同区域打印文本。例如,我如何使用 JLabel 打印 1 2 3 4 5 与每个数字相距 20 像素并且所有数字都保留在 GUI 上?
这是我到目前为止想出的:
JFrame frame = new JFrame("Email Sender");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
frame.setContentPane(contentPane);
frame.setSize(100, 60);
frame.setLocationByPlatform(true);
frame.setVisible(true);
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
JLabel num = new Jlabel;
for (int i = 0; i < a.length; i++)
{
num.setText((String.valueOf(a[i]));
num.setLocation(20*i, 20);
contentPane.add(num);
}
【问题讨论】:
-
小提示:在编译时创建已知数组时,请查看Array Literals。它只是更好的语法。
-
在添加完所有内容后在框架上调用
setVisible