从文件中读取的JList scoll窗格程序

时间:2011-11-07 21:50:09

标签: java swing file-io jscrollpane

到目前为止我有下面的代码输出汽车的品牌和价格,但我似乎无法弄清楚是要添加汽车的discritpion,以便它也可以diplayed.HELP!

我尝试添加discription[k] = st.nextToken();,但程序没有运行。

import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Lab22V3 extends JFrame implements ListSelectionListener {

    String[] products = new String[100];
    double[] prices = new double[100];
//string[]discription=new String[100]
    JLabel unitPrice;
    JList productList;

    public static void main(String[] args) {
        Lab22V3 x = new Lab22V3();
        x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        x.setTitle("Lab#22 Version#3");
        x.setSize(350, 250);
        x.setVisible(true);
    } // main

    public Lab22V3() // constructor
    {
        String s;
        StringTokenizer st;
        int k = 0;
        try {
            BufferedReader inFile = new BufferedReader(new FileReader("Lab22data.txt"));
            while ((s = inFile.readLine()) != null) {
                st = new StringTokenizer(s);
                products[k] = st.nextToken();
                //  discription[k] = st.nextToken();
                prices[k] = Double.valueOf(st.nextToken());
                ++k;
            } // while not EOF
            inFile.close();
        } catch (Exception e) {
            System.err.println(e);
        }

        unitPrice = new JLabel();
        getContentPane().add(unitPrice, BorderLayout.NORTH)

        JPanel p = new JPanel();
        productList = new JList(products);  // create a JList object
        productList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane sp = new JScrollPane(productList);  // adding scrolling capability
        p.add(sp);
        getContentPane().add(p, BorderLayout.SOUTH);
        // Event registration
        productList.addListSelectionListener(this);
    } // constructor

    // Event handling
    public void valueChanged(ListSelectionEvent event) {
        unitPrice.setText(" " + prices[productList.getSelectedIndex()]);
        //proddiscrition.setText(""+ discription[productList.getselectedIndex()];
    } // valueChanged
} // Lab22V3>

这是文本文件

1000    100.00  
A dozen of jokes
2000    5.91    
Used BMW
3000    19.28   
Cookie Jar
4000    21.90   
Birthday Cake
5000    35.28   
Used keyboard
6000    50.00   
Love
7000    92.27   
Gone with Wind

1 个答案:

答案 0 :(得分:0)

Angel918已经存在了5个月,所以我正在推广他的评论以Meta Suggestion回答。

我明白了。这是扫管笏我一直搞砸了。谢谢。

unitPrice.setText(" " + prices[productList.getSelectedIndex()] +" "+productnames[productList.getSelectedIndex()]);