我正在開發一個程序,它需要一個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;
}
}
嗯,是的,修正了它。我完全忘了那些。我只是將這三個函數移動到了actionPerformed中,因爲現在我不需要它了,還有ReadList的對象引用。 謝謝! – pandasticus 2014-11-03 18:16:53