【发布时间】:2011-05-14 01:11:15
【问题描述】:
类 SampleFiveA 扩展了 JPanel。这包含文本字段,一个在另一个之下,每个在左侧都有一个标签。所有文本字段将具有相同的宽度并位于面板的右边框。 SampleFiveA 只有一个构造函数,接受以下三个参数:
ArrayList 名称, ArrayList 值, 整数列
到目前为止,我在 GUI 中创建了示例用户名密码屏幕,但现在我在 JPanel 中实现一个 ArrayList 时遇到问题,一个用于用户名,另一个用于密码。有点卡在那里几个小时现在找不到合适的例子来做到这一点。下面是我注释了我需要使用 ArrayList 完成的代码。
public class SampleFiveA extends JPanel {
ArrayList<String> names = new ArrayList<String>(); //the text for the labels
ArrayList<String> values = new ArrayList<String>(); // the initial contents of the text fields
int col ; //the number of columns used to set the width of each textfield
public SampleFiveA()
{
JPanel p = new JPanel();
p.setLayout(new GridLayout(2,2));
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.add(lab1 = new JLabel("User Name"));
JTextField txt1 = new JTextField("User Name", JTextField.RIGHT);
p.add(txt1= new JTextField());
JLabel lab2 = new JLabel("Password ", JLabel.LEFT);
p.add(lab2 = new JLabel("Password"));
JPasswordField txt2 = new JPasswordField("*****",JPasswordField.RIGHT );
p.add(txt2 = new JPasswordField());
// names.add(lab1,lab2);// Not right but I want to put the label text to this arrayList
// values.add(txt1,txt2);//
add(p);
};
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new SampleFiveA());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
};
};
【问题讨论】:
-
需要理解的重要一点:您不能创建 ArrayLists
names、values或 intcols。它们被传递到您的构造函数中,然后您将它们分配给对象自己的变量。那么,您的构造函数的签名是public SampleFiveA(ArrayList names, ArrayList values, int cols)。我不知道你在这里要达到什么目标,但我怀疑这将涉及从这些提供的列表中读取/写入。 -
你知道如何迭代你的列表吗?如果没有,请阅读for loops。