Java 从另一个类获取选定的组合框

标签 java swing combobox

这里是新手。首先,如果这篇文章不遵守 stackoverflow 的规则,我很抱歉。我想从三年前的来源问同样的问题(我认为它有错误的答案): stackoverflow source

如何从一个类中获取 ComboBox 的选定项并在新类中使用该选定项的值。

比方说,源类和其他类。我想从其他类的源类中打印项目 3(组合框中的第三个项目)。

我已经使用了上述来源的答案。然而,它只返回第一项。因为我认为每次从源类调用构造函数时,它都会将所选项目重新启动到第一项。

当我使用 javax.swing.JFrame(我使用 Netbeans)时该怎么做?

public class Source extends javax.swing.JFrame{

final JComboBox test = new JComboBox();
test.setModel(new DefaultComboBoxModel(new String[] {"Item 1", "Item 2", "Item 3"}));

...

public String getSelectedItem() {
   return (String) test.getSelectedItem();
}

另一类:

public class Other extends javax.swing.JFrame{

public Other(){

Source sc = new Source();
String var = sc.getSelectedItem();

System.out.println(var);
}
}

假设我在源类中选择了项目 3。那么它会在其他类别中获得第 3 项吗?或者我做错了构造函数?很抱歉给您带来不便。

最佳答案

I want to ask the same question (it has wrong answer) from 3 years ago ...

不,这个答案完全正确。

How to get the selected item of ComboBox from one class and use the value of that selected item in new class.

Reimeus 再次告诉您如何正确执行此操作。

Let's say, source class and other class. I want to print item 3 (third item in a ComboBox) from source class at other class.

不确定“项目 3” 的含义,但如果它是另一个选定的项目,则您引用的答案再次是正确的

I already used the answer from above source. Yet, it only return the first item. Because I think each time I call the constructor from the source class, it will restarted the selected item to the first item.

这正是你的问题——你不应该重新调用构造函数,因为这会给你错误的引用。它将为您提供一个全新的 GUI 引用,一个关于未显示的 GUI 的引用。您需要当前查看的兴趣类别的引用。如何执行此操作将取决于程序的结构 - 请显示更多信息。

例如:请注意以下代码有两个 JButton,一个在其 ActionListener(实际上是一个 AbstractAction,但结构类似)内正确执行操作,另一个执行错误:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class GetCombo extends JFrame {
    // the displayed ClassWithCombo object
    private ClassWithCombo classWithCombo = new ClassWithCombo(this);;
    private int columns = 10;
    private JTextField textField1 = new JTextField(columns);
    private JTextField textField2 = new JTextField(columns);

    public GetCombo() {
        classWithCombo.pack();
        classWithCombo.setLocationByPlatform(true);
        classWithCombo.setVisible(true);

        setLayout(new FlowLayout());

        add(textField1);
        add(new JButton(new AbstractAction("Doing It Right") {

            @Override
            public void actionPerformed(ActionEvent e) {
                // use the ClassWithCombo reference that is already displayed
                String selectedString = classWithCombo.getSelectedItem();
                textField1.setText(selectedString);
            }
        }));
        add(textField2);
        add(new JButton(new AbstractAction("Doing It Wrong") {

            @Override
            public void actionPerformed(ActionEvent e) {
                // create a new non-displayed ClassWithCombo reference.
                ClassWithCombo classWithCombo = new ClassWithCombo(GetCombo.this);
                String selectedString = classWithCombo.getSelectedItem();
                textField2.setText(selectedString);
            }
        }));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GetCombo getCombo = new GetCombo();
            getCombo.setTitle("Get Combo Example");
            getCombo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getCombo.pack();
            getCombo.setLocationRelativeTo(null);
            getCombo.setVisible(true);
        });
    }
}

@SuppressWarnings("serial")
class ClassWithCombo extends JDialog {
    private static final String[] DATA = { "Mon", "Tues", "Wed", "Thurs", "Fri" };
    private JComboBox<String> combo = new JComboBox<>(DATA);

    public ClassWithCombo(JFrame frame) {
        super(frame, "Holds Combo Dialog", ModalityType.MODELESS);
        setLayout(new FlowLayout());
        setPreferredSize(new Dimension(300, 250));
        add(combo);
    }

    public String getSelectedItem() {
        return (String) combo.getSelectedItem();
    }

}
<小时/> <小时/>

编辑
阅读您的最新帖子后,我现在看到您正在尝试打开包含窗口的组合作为呈现给用户的窗口,以获取主程序运行时使用的信息。在这种情况下,最好的选择是使用模态对话框,该对话框在打开对话框后会卡住主窗口中的程序流,但不会允许用户在对话框打开时与主窗口交互,然后在对话框窗口关闭时恢复程序流程和用户交互。

请查看下面我的示例程序的更改。在这里,我更改了用于 JDialog 的 super 构造函数,使其成为 APPLICATION_MODAL,具有上述行为。然后该对话框在主窗口按钮的 ActionListener 内打开。由于组合窗口是一个模式对话框——程序在关闭组合窗口之前不会从组合窗口中提取信息——这一点非常非常重要。这样,您的主程序就会获得用户的选择,而不总是组合框中的第一项。我添加了一个名为“submitButton”的新 JButton,它所做的就是关闭当前窗口。如果需要,您可以将 ActionListener 添加到 JComboBox,以便在做出选择时关闭其窗口,但这不允许用户改变主意,所以我更喜欢使用提交按钮。

请注意更改由 \\!! 注释标记。

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class GetCombo2 extends JFrame {
    // the displayed ClassWithCombo object
    private ClassWithCombo classWithCombo = new ClassWithCombo(this);;
    private int columns = 10;
    private JTextField textField1 = new JTextField(columns);

    public GetCombo2() {
        classWithCombo.pack();
        classWithCombo.setLocationByPlatform(true);

        // !! don't do this here
        // classWithCombo.setVisible(true);

        setLayout(new FlowLayout());

        textField1.setFocusable(false);
        add(textField1);
        add(new JButton(new AbstractAction("Open Combo as a Dialog") {

            @Override
            public void actionPerformed(ActionEvent e) {
                // open combo dialog as a **modal** dialog:
                classWithCombo.setVisible(true);

                // this won't run until the dialog has been closed
                String selectedString = classWithCombo.getSelectedItem();
                textField1.setText(selectedString);
            }
        }));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GetCombo2 getCombo = new GetCombo2();
            getCombo.setTitle("Get Combo Example");
            getCombo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            getCombo.pack();
            getCombo.setLocationRelativeTo(null);
            getCombo.setVisible(true);
        });
    }
}

@SuppressWarnings("serial")
class ClassWithCombo extends JDialog {
    private static final String[] DATA = { "Mon", "Tues", "Wed", "Thurs", "Fri" };
    private JComboBox<String> combo = new JComboBox<>(DATA);

    public ClassWithCombo(JFrame frame) {
        // !! don't make it MODELESS
        // !! super(frame, "Holds Combo Dialog", ModalityType.MODELESS);
        // !! note the change. Made it APPLICATION_MODAL
        super(frame, "Holds Combo Dialog", ModalityType.APPLICATION_MODAL);

        JButton submitButton = new JButton(new AbstractAction("Submit") {
            // !! add an ActionListener to close window when the submit button
            // has been pressed.

            @Override
            public void actionPerformed(ActionEvent e) {
                ClassWithCombo.this.setVisible(false);
            }
        });

        setLayout(new FlowLayout());
        setPreferredSize(new Dimension(300, 250));
        add(combo);
        add(submitButton);
    }

    public String getSelectedItem() {
        return (String) combo.getSelectedItem();
    }

}

关于Java 从另一个类获取选定的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553324/

相关文章:

java - EclipseLink JPA 2.1 用户提供的连接

java模式匹配对空格不敏感

java - 使用 gif 显示自定义加载对话框

java - 将产品存储在 TreeSet 中并将内容打印在 JTable 中

java - spring Pageable getTotalElements() 有多重?

java - 如何在运行时从 java 程序编译并运行 scala 代码?

java - 从另一个 JFrame 调用 JFrame 方法

Java 8 DatePicker 和可编辑的 ComboBox 行为在 8u51 和 8u60 之间发生变化

combobox - Kendo ComboBox - 如何根据其 text() 而不是 value() 选择选项?

silverlight-4.0 - Silverlight MVVM,停止 SelectionChanged 触发以响应 ItemsSource 重置