2014-11-03 73 views
-1

我正在开发一个程序,它需要一个txt文件,它是一个电影列表,并从中选择一个随机电影。一切正常,但有一个GUI问题。当我按下按钮时,我无法将JLabel更改文本转换为所选电影。Java:actionPerformed抛出异常并拒绝工作

事实上,无论我放在actionPerformed方法拒绝工作,并抛出一堆例外。

我不知道如何解决这个问题,因为一切都应该工作正常(至少对我来说)。

您可以看到,在主要方法中,我调用System.out.println从列表中打印出该电影,并以此方式工作。我试图在actionPerformed中放入相同的System.out.println命令,但它不起作用。

下面的代码: MoviePick.java

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

public class MoviePick implements ActionListener{ 
    private JButton button; 
    private JLabel display; 

    public static void main(String[] args) { 
     ReadList list = new ReadList(); 
     MoviePick gui = new MoviePick(); 

     list.openFile(); 
     list.readFile(); 
     list.closeFile(); 

     gui.setup(); 

     //This works 
     System.out.println(list.getRandom()); 
    } 

    public void setup(){ 
     JFrame frame = new JFrame("Random Movie Picker"); 
     frame.setSize(250,100); 
     frame.setResizable(false); 
     frame.setLocationRelativeTo(null); 

     button = new JButton("Get Random Movie"); 
     display = new JLabel("Movie"); 

     button.addActionListener(this); 
     button.setPreferredSize(new Dimension(240,25)); 

     frame.setLayout(new FlowLayout(FlowLayout.CENTER)); 

     frame.add(display); 
     frame.add(button); 

     frame.setVisible(true); 
    } 

    @Override 
    public void actionPerformed(ActionEvent event){ 
     ReadList random = new ReadList(); 

     //This doesn't work 
     display.setText(random.getRandom()); 
    } 
} 

ReadList.java

import java.io.File; 
import java.util.ArrayList; 
import java.util.Scanner; 

public class ReadList { 
    private Scanner f; 
    private ArrayList<String> theList = new ArrayList<String>(); 

    public void openFile(){  
     try{ 
      f = new Scanner(new File("list.txt")); 
     }catch(Exception e){ 
      System.out.println("File not found!"); 
     } 
    } 

    public void readFile(){ 
     while(f.hasNextLine()){ 
      theList.add(f.nextLine()); 
     } 
    } 

    public void closeFile(){ 
     f.close(); 
    } 

    public void getList(){ 
     for(String mov : theList){ 
      System.out.println(mov); 
     } 
    } 

    public String getRandom() { 
     int rand = (int) (Math.random()*theList.size()); 
     String chosenOne = theList.get(rand); 
     return chosenOne; 
    } 

} 

回答

1

它不工作的原因是因为你有你的main方法这些方法,但不是在你的actionPerformed一个

list.openFile(); 
list.readFile(); 
list.closeFile(); 

没有这些,这些线路不能

int rand = (int) (Math.random()*theList.size()); 
String chosenOne = theList.get(rand); 
return chosenOne; 

因为theList.size()0,因此theList.get(0)会引发异常,因为列表中没有任何内容可以获取。

+0

嗯,是的,修正了它。我完全忘了那些。我只是将这三个函数移动到了actionPerformed中,因为现在我不需要它了,还有ReadList的对象引用。 谢谢! – pandasticus 2014-11-03 18:16:53

0

你的问题是在这里:

public void actionPerformed(ActionEvent event){ 
    ReadList random = new ReadList(); 

    //This doesn't work 
    display.setText(random.getRandom()); 
} 

你没有打开readlist,装载数据和关闭文件,就像你在主