我在文本字段中显示数组 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) + " ");
}
}
}