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 JComboBox
selection. When the user selects a book from the list and press "OK", it will take them to another specific frame depending on their selection.
How can I achieve this?
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) {
String value = (String) myBooks.getSelectedItem(); // get the selected item in the combobox
switch(value){
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.