簡體   English   中英

Java從另一個類獲取選定的組合框

[英]Java Get Selected Combobox from Another Class

新手在這里。 首先,很抱歉,如果這篇文章不遵守stackoverflow的規則。 我想從這個來源詢問3年前的同一個問題(我認為答案有誤): stackoverflow源

如何從一個類中獲取ComboBox的選定項目,以及如何在新類中使用該選定項目的值。

假設是源類和其他類。 我想從其他類的源類中打印項目3(ComboBox中的第三項)。

我已經使用了以上來源的答案。 但是,它僅返回第一項。 因為我認為每次我從源類調用構造函數時,它都會將選定的項重新啟動到第一項。

當我使用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);
}
}

假設我在Source類中選擇了Item 3。 那么它將在其他班級獲得第3項嗎? 還是我做錯構造函數? 抱歉給你帶來不便。

我想問3年前的同一個問題(答案有誤)...

不,這個答案是完全正確的。

如何從一個類中獲取ComboBox的選定項目,以及如何在新類中使用該選定項目的值。

同樣,Reimeus會告訴您如何正確進行操作。

假設是源類和其他類。 我想從其他類的源類中打印項目3(ComboBox中的第三項)。

不知道"item 3"是什么意思,但是如果它是另一個選擇的項目,那么您所指的答案也是正確的

我已經使用了以上來源的答案。 但是,它僅返回第一項。 因為我認為每次我從源類調用構造函數時,它都會將選定的項重新啟動到第一項。

這正是您的問題-您不應該重新調用構造函數,因為這會給您錯誤的引用。 它將為您提供一個全新的GUI參考,一個未顯示的 GUI參考。 您需要參考當前查看的興趣類別。 如何執行此操作將取決於程序的結構-請顯示更多內容。

例如:請注意,以下代碼具有兩個JButton,一個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的超級構造函數,使其具有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();
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM