Sunday 15 August 2010

swing - Java: actionPerformed throws exceptions and refuses to work -



swing - Java: actionPerformed throws exceptions and refuses to work -

i working on programme takes txt file list of movies , selects random film it. working there gui problem. can't create jlabel alter text selected film when press button.

in fact, whatever set in actionperformed method refuses work , throws bunch of exceptions.

i not know how prepare since should working fine(at to the lowest degree me).

you can see in main method called system.out.println print out film list , works way. , tried putting same system.out.println command in actionperformed, didn't work.

here's 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 film 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); homecoming chosenone; } }

the reason doesn't work because have these methods in main method, not in actionperformed one

list.openfile(); list.readfile(); list.closefile();

without those, these lines fail

int rand = (int) (math.random()*thelist.size()); string chosenone = thelist.get(rand); homecoming chosenone;

because thelist.size() 0, thelist.get(0) throws exception, since there nil in list get.

java swing exception actionevent

No comments:

Post a Comment