我想在文本字段中显示数组的所有6个元素

时间:2013-02-24 10:04:29

标签: java

我在文本字段中显示数组j的值时遇到问题。运行时只显示1个元素。

import java.util.Collections;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class SwingCounter extends JFrame implements ActionListener {

    // use Swing's JTextField instead of AWT's TextField
    private JTextField tfCount;
    private int counterValue = 0, numbers=0, j=0;

    public SwingCounter () {

        // retrieve the content pane of the top-level container JFrame
        Container cp = getContentPane();
        // all operations done on the content pane
        cp.setLayout(new FlowLayout());

        cp.add(new JLabel("Counter"));
        tfCount = new JTextField(10);
        tfCount.setEditable(true);
        tfCount.setText(numbers + "");
        cp.add(tfCount);

        JButton btnCount = new JButton("Count");
        cp.add(btnCount);
        btnCount.addActionListener(this);

        // exit program if close-window button clicks
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // set initial window size
        setSize(280,80);
        // location in screen
        setLocation(400,200);
        // set this JFrame's title
        setTitle("Swing Counter");
        setVisible(true);     // Show it
    }

    public void actionPerformed(ActionEvent evt) {
        counterValue++;

        //define ArrayList to hold Integer objects
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for(int i = 0; i < 45; i++)
        {
            numbers.add(i+1);
        }

        Collections.shuffle(numbers);

        System.out.print("This week's lottery numbers are: ");
        for(int j =0; j < 6; j++)
        {
            System.out.print(numbers.get(j) + " ");
            tfCount.setText(numbers.get(j) + " ");
        }
    }
}

4 个答案:

答案 0 :(得分:1)

你需要这样做:

String text=""
for(int j =0; j < 6; j++)
{
text+=numbers.get(j) 
}
tfCount.setText(text); 

答案 1 :(得分:1)

你在for循环中调用它:

tfCount.setText(numbers.get(j) + " "); 

这样总是最后一个数字将显示在TextField中。你必须在循环中连接数字并在之后调用tfCount.setText()

像这样:

String concatenatedNumbers = "";
for(int j =0; j < 6; j++) {
   concatenatedNumbers = concatenatedNumbers + ", " + numbers.get(j);
 }
 tfCount.setText(concatenatedNumbers); 

答案 2 :(得分:1)

您将JTextField的文字覆盖了6次,因此它只显示最后一个。

首先要创建一个包含所有数字的String,然后使用其值来设置文本:

// String to hold the lottery numbers
String numbersString = "";
for(int j =0; j < 6; j++)
{
  // Print number to log/terminal
  System.out.print(numbers.get(j));
  // Append the string with the current number
  numbersString += numbers.get(j) + " ";
}
// Update the value of the JTextField with all the numbers at once
tfCount.setText(numbersString); 

答案 3 :(得分:1)

每次在文本字段上调用setText()时,都会将其显示的文本替换为其他文本。因此,创建一个包含6个第一个数字的String,然后使用结果设置文本字段的文本:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
    sb.append(numbers.get(i));
    sb.append(' ');
}
tfCount.setText(sb.toString());