简体   繁体   English

jList不返回所需的字符串值

[英]jList doesn't return desired string value

I am new in Java, and I've tried to write a simple GUI application that is supposed to return the selected value of a jList into a textfield . 我是Java的新手,我试图编写一个简单的GUI应用程序,该应用程序应该将jList的选定值返回到textfield

But instead of the selected text, it returns a memory address like [Ljava.lang.Object;@675b9599 to the textField . 但是,它代替选定的文本,向textField返回一个类似于[Ljava.lang.Object;@675b9599的内存地址。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    jTextField1.setText(Arsenal.getSelectedValues().toString()); 
} 
Arsenal.getSelectedValues()//Returns Array of Object and Deprecated as well
                   -------

Instead use jList.getSelectedValue() Value Not Values which returns selected element.So it should be 而是使用jList.getSelectedValue() Value Not Values返回选择的元素。

jTextField1.setText((String)Arsenal.getSelectedValue());

If you have added String to your JList you would even don't need to convert it to String as it will return value according to the type of JList element. 如果已将String添加到JList ,则甚至无需将其转换为String因为它将根据JList元素的类型返回值。

If you want to get all selected values use getSelectedValuesList() instead of getSelectedValues() because it's deprecated. 如果要获取所有选定的值,请使用getSelectedValuesList()而不是getSelectedValues()因为它已被弃用。

You are probably retrieving the text of the selected element in the JList wrong. 您可能错误地检索了JList所选元素的文本。 You must use the getSelectedValue() to retrieve it. 您必须使用getSelectedValue()来检索它。

String text = (String) myList.getSelectedValue();

There is no need to call the toString() method as in myList.getSelectedValue().toString() since that might cause you a NullPointerException if there is no selected value, and the JList instead returns a null` value. 无需像myList.getSelectedValue().toString()一样调用toString()方法,因为如果没有选定值,这可能会导致NullPointerException ,而JList instead returns a null值。

Java docs says: Java文档说:

Returns the value for the smallest selected cell index; 返回最小的选定单元格索引的值; the selected value when only a single item is selected in the list. 在列表中仅选择一个项目时的选定值。 When multiple items are selected, it is simply the value for the smallest selected index. 选择多个项目时,它只是所选索引最小的值。 Returns null if there is no selection. 如果没有选择,则返回null。

JList only returns the Object .So convert it to the String . JList仅返回Object 。因此将其转换为String

jList.getSelectedValue().toString();

It should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM