在组合框中使用文本文件

时间:2013-04-25 06:07:18

标签: java swing file-io input jcombobox

您好,我一直无法让我的组合框列出文本文件中的项目。虽然我在这里,但是当我改变我的组合框时,我想询问我的radioButton是否会动态变化,还是会有太多麻烦?

import java.awt.GridLayout;
import java.util.Arrays;
import java.util.Scanner;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.io.*;

public class MovieSelection extends JFrame {

private JRadioButton selection1;
private JRadioButton selection2;
private JRadioButton selection3;
private JPanel moviePanel;
private JLabel priceLabel;

private JComboBox movieBox;
private ButtonGroup bg;

private String[] movieName = { "RED", "Taken", "Star Trek", "Star Wars",
        "Avatar" };


public MovieSelection() {
    super("Please select your movie");
    setSize(800, 400);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(new GridLayout(15, 4));

    setLocationRelativeTo(null);
    // PrintWriter outputFile = new PrintWriter(TheMovies.txt);
    buildMoviePanel();

    add(moviePanel);

    setVisible(true);

}



private class MovieLists implements ActionListener {
    public void actionPerformed(ActionEvent e) {

        Scanner inputFile = new Scanner(TheMovies.txt);

        while (inputFile.hasNext()) {
            String nextMovieName = inputFile.nextLine();

        }

        JComboBox cb = (JComboBox) e.getSource();
        String Themovie = (String) cb.getSelectedItem();

    }

}

}

1 个答案:

答案 0 :(得分:1)

您正在编写TheMovies.txt作为表达式,因此java编译器将查找名为TheMovies的类,其中包含名为txt的公共静态成员。

你真正的意思是字符串文字,所以你必须用引号括起来:

"TheMovies.txt"

但是当您将String传递给Scanner constructor时,该字符串本身将被扫描,而不会被解释为文件名。因此,您必须首先从该字符串构造FilePath对象。

Scanner inputFile = new Scanner(new File("TheMovies.txt"));

该行

JComboBox movieLists = new JComboBox(TheMovies.txt);
由于被解释为表达式的相同原因,

是错误的。在任何情况下都不确定你的意图是什么,但我希望你能从中找到自己的后续步骤。它应该是迭代文件内容并一次填充组合框一行的东西。