This question already has answers here:
JList selected item to String - Weird result: Donnees.Marques@3d5bac58
                                
                                    (4个答案)
                                
                        
                                4年前关闭。
            
                    
在listMarques.addMouseListener中,我想在selectedCategories中获取String。我在课堂上尝试过

Private selectedCategories = null


但它不起作用。

listCategories.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent arg0) {
                String selectedCategories = listMarques.getSelectedValue().toString();
                System.out.println(selectedCategories);
            }
        });

        listMarques.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                String selectedMarques = listMarques.getSelectedValue().toString();

                if(selectedMarques  != null && selectedCategories != null)
                {


                }
            }
        });

最佳答案

您正在用本地变量隐藏成员变量。

更换

String selectedCategories = listMarques.getSelectedValue().toString();




YourClassName.this.selectedCategories = listMarques.getSelectedValue().toString();


其中YourClassName将是您持有成员selectedCategories的类的名称,以及上面的代码。

祝好运。

关于java - 从addMouseListener中恢复getSelectedValue ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29878488/

10-10 11:26