How can I open another jFrame through a comboBox selection?

I’m a beginner to Java and I’m trying to make a simple virtual library where the user can browse for books (the books will be contained in a jFrame) through a comboBox selection. When the user selects a book from the list and press “OK”, it will take them to another specific jFrame depending on their selection. How can I achieve this? I am using Netbeans IDE 12.2

Answer

If your books are separate classes you can just call them respectively. Assuming that these separates classes are inside a JFrame

class book1 extends JFrame{
  //book contents
}

class book2 extends JFrame{
  //book contents
}

class book3 extends JFrame{
  //book contents
}

public class Main { //this class can also be in a GUI
   public static void main(String args[]){
     String booklist[] = { "Book1", "Book2", "Book3"};

     JComboBox myBooks = new JComboBox(booklist);
     
     //Add an event listener based on your preference. Code below is just for example im not sure if its the right syntax but you get the point.
     mybook.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
          
        switch(myBooks){
        case "Book1":
            book1 b1 = new book1(); // call the class
            b1.setVisible(true);    // set the jframe to visible 
            break;
        case "Book2":
            book2 b2 = new book2();
            b2.setVisible(true);
            break;
        case "Book3":
            book3 b3 = new book3();
            b3.setVisible(true);
            break;
        }          
      }
    });
  }
}

Hope I helped.

Leave a Reply

Your email address will not be published. Required fields are marked *