Java从另一个类中获取选定的组合框 [英] Java Get Selected Combobox from Another Class

查看:210
本文介绍了Java从另一个类中获取选定的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

newbie here. First I'm sorry if this post doesn't abide the rules of stackoverflow. I want to ask the same question (I think it has wrong answer) from 3 years ago from this source: stackoverflow source

如何从一个类中获取所选的ComboBox项,请在新类中使用所选项目的值。

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

让我们说,源类和其他类。我想从其他类的源类打印项目3(ComboBox中的第三个项目)。

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.

我已经使用了上面的源代码。然而,它只返回第一项。因为我认为每次我从源类调用构造函数,它将重新启动选择的项目到第一个项目。

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.

如何做,当我使用javax .swing.JFrame(我使用Netbeans)?

How to do it when I'm using javax.swing.JFrame (I use 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);
}
}

假设我在Source类中选择了Item 3。那么它会得到3类在其他类吗?或者我做错构造函数?

Let's say I chose Item 3 at Source class. So will it get item 3 at Other class? Or I do wrong constructor? Sorry for the inconvenience.

推荐答案


我想提出同样的问题从3年前...

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

不,答案完全正确。


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

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

再次,Reimeus告诉你如何正确地做。

Again, Reimeus tells you how to do it correctly.


让我们说,源类和其他类。我想从其他类的源类打印项目3(ComboBox中的第三个项目)。

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.

不确定你的意思是item 3,但如果是另一个选定的项目,您再次指向正确的答案

Not sure what you mean by "item 3", but if it's another selected item, again the answer you refer to is correct.


我已经使用了上面的源代码。然而,它只返回第一项。因为我认为每次我从源类调用构造函数,它将重新启动所选项目到第一个项目。

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 。你需要参考当前观看的兴趣类。

And that's exactly your problem -- you shouldn't be re-calling constructors as that will give you the wrong reference. It will give you a completely new GUI reference, one to a GUI that is not displayed. You need the reference to the currently viewed class of interest. How you do this will depend on the structure of your program -- please show more.

例如:注意下面的代码有两个JButton,一个是正确的它的ActionListener(实际上是一个AbstractAction,但是一个类似的结构)和一个不正确的事情:

For example: note the following code has two JButtons, one that does thing correctly within its ActionListener (actually, an AbstractAction, but a similar construct), and one that does things incorrectly:

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();
    }

}





$ b b


编辑

阅读您的最新帖子之后,我现在看到您正在尝试打开包含组合框的窗口一个窗口,显示给用户以获取信息,以便在主程序运行时使用。在这种情况下,最好的办法是使用 模式 对话框,即在对话框打开后冻结主窗口中的程序流的对话框允许用户在对话框打开时与主窗口交互,然后在对话框窗口关闭时恢复程序流和用户交互。



Edit
After reading your latest post, I now see that you are trying to open the combo containing window as a window that is presented to the user to get information from to be used by the main program as it's running. In this situation your best bet is to use a modal dialog, that is a dialog that freezes program flow in the main window after the dialog has been opened, that doesn't allow user interaction with the main window while the dialog has been open, and that then resumes program flow and user interaction when the dialog window has been closed.

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

Please look at the changes to my example program below. Here I change the super constructor used for the JDialog to make it APPLICATION_MODAL, with the behaviors described above. The dialog is then opened inside the main window's butotn's ActionListener. Since the combo window is a modal dialog -- the program doesn't extract information from the combo window until it has been closed -- this bit is very important. And this way your main program gets the user's selection and not always the first item in the combobox. I've added a new JButton called the submitButton, that all it does is close the current window. If desired you could instead add the ActionListener to the JComboBox so that it closes its window when a selection has been made, but this doesn't allow the user to change his mind, so I prefer using a submit button.

请注意变更标有 \\ !! 注释。

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从另一个类中获取选定的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆