如何通过JComboBox选择打开另一个JFrame



我是Java的初学者,我正在尝试制作一个简单的虚拟库,用户可以在其中通过JComboBox选项浏览书籍(书籍将包含在JFrame中(。当用户从列表中选择一本书;OK";,它将根据他们的选择将他们带到另一个特定的帧。

我怎样才能做到这一点?

如果你的书是单独的类,你可以分别调用它们。假设这些分离类在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;
}          
}
});
}
}

希望我能帮上忙。

最新更新