[英]How do you read a textfile using a scanner into a Swing control component?
In an array class I have the following code and would like to use the name, surname and score variables to be loaded into a jList. 在数组类中,我有以下代码,并希望使用名称,姓氏和分数变量加载到jList中。 How would I do so?
我该怎么办?
private static User uArr [] = new User [10];
private static int size = 0;
public UserArray () throws FileNotFoundException {
try
{
Scanner fcFile = new Scanner (new File ("user.txt"));
String line, name, surname;
int score;
while (fcFile.hasNext())
{
line = fcFile.nextLine();
Scanner cfFile = new Scanner (line);
name = cfFile.next();
surname = cfFile.next();
score = cfFile.nextInt();
cfFile.close();
uArr[size] = new User (name,surname,score);
size++;
}
fcFile.close();
}
catch (FileNotFoundException f)
{
System.out.println("File Not Found - Check File Name And Path Again.");
}
would like to use the name, surname and score variables to be loaded into a jList
想要使用名称,姓氏和分数变量加载到jList中
A JList is used to store a single piece of data. JList用于存储单个数据。 Since you want to display an object containing 3 pieces of data then you should use a JTable.
由于要显示包含3个数据的对象,因此应使用JTable。 Read the section from the Swing tutorial on How to Use Tables for more information and examples to get you started.
阅读Swing教程中有关如何使用表的部分,以获取更多信息和示例以开始使用。
When using a JTable
you could use the DefaultTableModel
and store each piece of data separately into the TablemModel
without using your User
class. 使用
JTable
,可以使用DefaultTableModel
并将每个数据分别存储到TablemModel
而无需使用User
类。
Or, if you want to add the User
class to the JTable
then you will need to create a custom TableModel. 或者,如果要将
User
类添加到JTable
则需要创建一个自定义TableModel。 Check out Row Table Model for a step-by-step example of creating a custom model for an object. 请查看行表模型 ,以获取为对象创建自定义模型的分步示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.