亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從另一個類的 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 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號