I am working on a program that takes a txt file which is a list of movies and selects a random movie from it. Everything is working normally but there is a GUI problem. I can't make a JLabel change text to that selected movie when I press a button.
In fact, whatever I put in the actionPerformed method refuses to work and throws a bunch of exceptions.
I do not know how to fix this since everything should be working fine(at least to me).
You can see that in the main method I called System.out.println to print out that movie from the list and it works that way. And I tried putting that same System.out.println command in actionPerformed, but it didn't work.
Here's the code: 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;
}
}