Search code examples
javamultithreadingswingconcurrencyjcomponent

performing a thread using jcomponets


am back again!. i have a probrem here. am making uneditable jcombobox. i have a list of items in it("crus","davy","shawn") and i want if someone clicks on crus, a thread of images with a Thread.sleep of 2 seconds will appear at a jlabel called picturelabel. when i try to put method run() inside method actionperformed, i get "illegal start of expression". i also get an error "not a statement" when i try to create an array of imageicon.

public class Myjcombobox extends JFrame implements ActionListener,Runnable {
JComboBox job;
String[] items={"crus","shawn","davy","others"};
JLabel picturelabel;
public Myjcombobox(){
super("oh mymy");
setSize(1000,1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border=new BorderLayout();
setLayout(border);
job=new JComboBox(items);
job.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
JComboBox combo=(JComboBox)event.getSource();
String name=(String)combo.getSelectedItem();
if(name=="crus"){
 public void run(){//i get an error illegal start of expression//
 JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"}; //i get an error "not a statement","( or[ expected"//  
 }   
}
}

public static void main(String[] args) {
    Myjcombobox jcomb=new Myjcombobox();


}   

Solution

  • if(name=="crus"){
    
    {//i get an error illegal start of expression//
     public void run()
    
    //i get an error "not a statement","( or[ expected"//  
     JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"}; 
     } 
    

    Every statement in the above code has a problem:

     if(name=="crus"){
    

    Don't use "==" to compare strings. Instead you should be using the equals(...) method:

    if ("crus".equals(name));
    

    Next, you can't just define a run() method in the middle of your code.

    public void run()
    

    The run() method belongs to a Thread, so you need to create a Thread and override the run() method. Something like:

    Thread thread = new Thread()
    {
        @override
        public void run()
        {
            System.out.println("I'm a Thread");
        }
    };
    thread.start();
    

    Finallay you can't create an Array of Image Icons in one step like this:

    JImageIcon[] crusimages= new JImageIcon{"crus reading.jpg","crus playing.jpg","crus in class.jpg"};
    

    You need to create an empty Array and then add the Icons one at a time:

    ImageIcon[] crusImages = new new ImageIcon[3];
    crusImage[0] = new ImageIcon( "crus reading.jpg" );