【问题标题】:How can I open another JFrame through a JComboBox selection?如何通过 JComboBox 选择打开另一个 JFrame?
【发布时间】:2021-06-23 23:00:27
【问题描述】:

我是 Java 的初学者,我正在尝试创建一个简单的虚拟图书馆,用户可以在其中通过 JComboBox 选择浏览书籍(书籍将包含在 JFrame 中)。当用户从列表中选择一本书并按“确定”时,它将根据他们的选择将他们带到另一个特定的框架。

我怎样才能做到这一点?

【问题讨论】:

标签: java swing jcombobox


【解决方案1】:

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

希望我能帮上忙。

【讨论】:

  • 它显示了 switch case 的错误,即“不兼容的类型:JComboBox 无法转换为 int”
  • (1-) 1) 类名不应以大写字符开头。遵循 Java 约定。从 API 中的类名中通过示例学习。 2) 一个应用程序应该只有一个 JFrame。子窗口应该是一个 JDialog。
  • @camickr 抱歉。我知道类名应该以我没有注意到的小写字母开头。 2. 我在回答他的“问题”,他说书在 jframe 中。
  • @Schwiro 我忘了。您需要获取所选项目。 String value = (String) myBooks.getSelectedItem(); 在开关盒中使用它们之前
  • @GeromeTahud,回答问题的一部分是在可用时建议一种更好的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2014-12-22
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
相关资源
最近更新 更多