为了账号安全,请及时绑定邮箱和手机立即绑定

如何从另一个类的 JComboBox 获取内容

如何从另一个类的 JComboBox 获取内容

米脂 2023-06-28 15:56:03
我正在开发一些应用程序。在主页(注册页面)上有一个组合框,其中有几个选项可供选择。根据选择的内容,具体内容将出现在下一个窗口中。问题是如何从其他类中的组合框获取内容。我假设需要添加一些 if 控制指令,但是每次我添加一些东西时它都会返回一个错误。有人可以帮助一下代码应该是什么样子吗?例如,如果选择选项“1”,则将背景设置为黑色,如果选择“2”,则将背景设置为粉色等。注册窗口:public Main() throws Exception {        registerWindowFrame = new JFrame("xxx");                                                            //registerWindowFrame.setSize(1440,2960);                                                                                registerWindowFrame.setSize(500, 750);        registerWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                                      registerWindowFrame.setLayout(null);        registerWindowFrame.getContentPane().setBackground(Color.RED);BloodList bloodList = new BloodList();        bloodList.setSize(bloodList.getPreferredSize());        bloodList.setLocation(10, 365);        registerWindowFrame.add(bloodList);组合框类:public class BloodList extends JComboBox <String> {    int i;    public String[] bloodList =            {                    "1",                    "2",                    "3",            };    public BloodList() {        for (i=0; i < bloodList.length; i++)        {            this.addItem(bloodList[i]);        };    }}重新调整窗口后的窗口:public mainWindowBplus() {        super();        bloodBplusFrame = new JFrame("SETTINGS");        bloodBplusFrame.setSize(500, 750);        bloodBplusFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        bloodBplusFrame.setLayout(null);        bloodBplusFrame.getContentPane().setBackground(Color.BLUE);    bloodBplusFrame.setVisible(true);
查看完整描述

1 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

您应该添加一个action listener来jcombobox获取所选值String,然后在另一个类中使用该值,试试这个:


public class BloodList extends JComboBox <String> {

    private String s="";


    private String[] bloodList =

            {

                    "1",

                    "2",

                    "3",


            };


    public BloodList() {

        for (int i=0; i < bloodList.length; i++)

        {

            this.addItem(bloodList[i]);

        };

    }


    ActionListener cbActionListener = new ActionListener() {//add actionlistner to listen for change

            @Override

            public void actionPerformed(ActionEvent e) {


                s = (String) BloodList.this.getSelectedItem();//get the selected string

            }

    };


    this.addActionListener(cbActionListener);


    public String getS(){return s;}


}

现在您可以String通过使用该getS()方法在另一个类中使用它。


查看完整回答
反对 回复 2023-06-28
  • 1 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信