gpt4 book ai didi

java - JComboBox 获取项目

转载 作者:行者123 更新时间:2023-12-01 16:53:49 24 4
gpt4 key购买 nike

我有一个简单的问题。没看懂...

我有一个 JFrame,我在其中添加了一个 JComboBox:

            JComboBox<String> Team_ComboBox = new JComboBox<>();
Team_ComboBox_Handler ComboBox_Listener = new Team_ComboBox_Handler();
Team_ComboBox.addActionListener(ComboBox_Listener);
Team_ComboBox.addItem("Test 1");
Team_ComboBox.addItem("Test 2");

在此框架上,我有一个可打开另一个 JFrame 的按钮。

            Play = new JButton();
Play.setText("Play");
Play.setPreferredSize(dimension);
Play.addActionListener(menuhandler);
private class main_menuhandler implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Play){
teams Team = new teams();
Team.teams();

disposeMainMenue();
}
if(e.getSource()==Close) {
System.exit(DO_NOTHING_ON_CLOSE);
}
}
}

无论如何,我想将组合框的选定值传输到另一个类的方法。我知道如何在方法本身中获取组合框的项目值(使用 getselecteditem)但是如何在 ActionPerformed 方法中执行此操作,因为我无法访问 ActionPerformed 方法中的组合框....我创建了另一个 ActionListener ( comboBox_Listener),但我没有在其中添加任何代码...

有什么想法吗?提前非常感谢

最佳答案

我发现了几个问题:

您的主要问题:

But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method

您可能的最佳解决方案是更改代码和变量声明位置,以便您可以从 actionPerformed 方法访问 JComboBox。如果您从方法或构造函数中声明组合框,请更改它,使其成为该类的正确实例字段。

其他问题:

  • 您不应该创建多个 JFrame。如果您需要一个从属窗口,那么 JDialog 应该是其中之一。如果没有,请考虑使用 CardLayout 交换 View 。
  • 学习并遵循 Java 命名约定,以便其他人可以更好地理解您的代码。例如,类名以大写字母开头,而方法和变量名则不然。
  • 我不确定您为什么要这样做:System.exit(DO_NOTHING_ON_CLOSE);。为什么要将该常量传递到 exit 方法中?

关于java - JComboBox 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35523678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com