使用java.awt和javax.swing我一直在制作一个小的GUI,它将在JPanel中显示多个条目。在使用默认文本成功显示单个条目后,我开始尝试实现for循环以从少数几个数组创建多个条目,并且很难加载标记每个组件的文本字符串。添加for循环和数组后,我现在只在一个没有数据的小空间周围得到一个黑色边框。
以下是我正在使用的代码:
package myInterfaceComponents;
import java.awt.*;
public class ListOfEntries extends JComponent {
//instance variables
//worked until arrays added
String[] telephones = {"5551234567", "5557654321", "5555671234"};
String[] names = {"Emily", "Billy Bob", "Wiley Coyote"};
String[] periods = {"2p - 3p", "1a - 5a", "4:30p - 11p"};
private JLabel telephone = new JLabel();
private JTextField name = new JTextField();
private JButton period = new Button();
private StatusCombo serviceCycle = new StatusCombo();
private AreaCombo area = new AreaCombo();
//constructors
public ListOfEntries() {
setLayout(new GridLayout(2, 3));
for (int x = 0; x == 2; x++) { //worked until added
telephone.setText(telephones[x]); //worked until added
name.setText(names[x]); //worked until added
period.setText(periods[x]); //worked until added
add(telephone);
add(name);
add(area);
add(period);
add(serviceCycle); } //worked until add: "}"
Border line = BorderFactory.createLineBorder(Color.BLACK);
Border titled = BorderFactory.createTitledBorder(line, "Day: DD MMM YYYY");
setBorder(visible);
setVisible(true); }
}
显然我正在对阵列做错事,或者设置组件,但经过多次尝试后才会出现问题。谷歌搜索我错过了一些东西。非常感谢任何帮助。
答案 0 :(得分:2)
我还没有尝试过运行你的程序,但我注意到你的循环:
for (int x = 0; x == 2; x++) { //worked until added
telephone.setText(telephones[x]); //worked until added
name.setText(names[x]); //worked until added
period.setText(periods[x]); //worked until added
add(telephone);
add(name);
add(area);
add(period);
add(serviceCycle); }
在这个循环中,你将计数器变量“x”初始化为0,但是在下一个语句中你有:x == 2,只有当x等于2时才会运行循环,并且因为x是初始化为0,此循环将永远不会运行。尝试将语句x == 2更改为x< 2,看看这是否有帮助。