我无法通过方法将列表中的项目打印到JTextArea中。
void grab(){
if(appleField.getText().equals("")){
appleField.setText("");
}
else{
int a = Integer.parseInt(appleField.getText());
list.add(new MyShoppingCart(a, "Apples bought:"));
}
if(bananaField.getText().equals("")){
bananaField.setText("");
}
else{
int b = Integer.parseInt(bananaField.getText());
list.add(new MyShoppingCart(b, "Bananas bought:"));
}
if(cherryField.getText().equals("")){
cherryField.setText("");
}
else{
int c = Integer.parseInt(cherryField.getText());
list.add(new MyShoppingCart(c, "Cherries bought:"));
}
if(dukuField.getText().equals("")){
dukuField.setText("");
}
else{
int d = Integer.parseInt(dukuField.getText());
list.add(new MyShoppingCart(d, "Dukus bought:"));
}
if(elderField.getText().equals("")){
elderField.setText("");
}
else{
int e = Integer.parseInt(elderField.getText());
list.add(new MyShoppingCart(e, "Elderberries bought"));
}
if(falField.getText().equals("")){
falField.setText("");
}
else{
int f = Integer.parseInt(falField.getText());
list.add(new MyShoppingCart(f, "Falberries bought"));
}
if(gacField.getText().equals("")){
gacField.setText("");
}
else{
int g = Integer.parseInt(gacField.getText());
list.add(new MyShoppingCart(g, "Gacs bought"));
}
if(honeyField.getText().equals("")){
honeyField.setText("");
}
else{
int h = Integer.parseInt(honeyField.getText());
list.add(new MyShoppingCart(h, "Honeydews bought"));;
}
if(mangoField.getText().equals("")){
mangoField.setText("");
}
else{
int m = Integer.parseInt(mangoField.getText());
list.add(new MyShoppingCart(m, "Mangos bought"));
}
if(passionField.getText().equals("")){
passionField.setText("");
}
else{
int p = Integer.parseInt(passionField.getText());
list.add(new MyShoppingCart(p, "Passion fruits bought"));
}
}
它只解析每个值,然后添加到列表中,如果它包含某些内容。
以下是“追加”的方法。
void printList() {
cartArea.setText("");
for (MyShoppingCart s : list) {
StringBuffer spaces = new StringBuffer(" ");
spaces.setLength(spaces.length() - s.getName().length());
cartArea.append(s.getName() + spaces);
cartArea.append(s.getQuantity() + "\n");
}
}
我知道print语句是错误的,但它是我现在唯一拥有的。
答案 0 :(得分:2)
您似乎在文本区域中格式化购物项时遇到问题。尝试使用String.format
正确格式化每一行,例如:
for (MyShoppingCart s : list) {
cartArea.append(String.format("%-20s %-20s\n", s.getName(), s.getQuantity()));
}
请务必使用固定宽度的字体,即Monospaced
:
Font font = new Font("Monospaced", Font.PLAIN, 14);
textArea.setFont(font);
作为替代方案,请考虑完全使用不同的控件 - JTable
。它可能更合适,因为它支持多列。如果需要,您可以隐藏网格线。有关示例,请参阅How to Use Tables。