好的,所以我从JList切换到List,因为
1。)它与我绘制的图像不重叠 2.)它可以禁用焦点但跟踪选择的内容
无论如何,这是我尝试编译时遇到的错误:
C:\Users\Dan\Documents\DanJavaGen\inventory.java:30: cannot find symbol
symbol : constructor List(java.lang.Object[])
location: class java.awt.List
list = new List(arr.toArray());
^
C:\Users\Dan\Documents\DanJavaGen\inventory.java:50: cannot find symbol
symbol : method getSelectedValue()
location: class java.awt.List
Object index = list.getSelectedValue();
^
代码:
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.awt.List;
public class inventory extends JApplet implements MouseListener {
public static String newline;
public static List list;
int gold = 123;
public void init() {
ArrayList<String> arr = new ArrayList<String>();
arr.add("Hatchet");
arr.add("Sword");
arr.add("Shield");
arr.add(gold + " Gold");
System.out.println("You have " + arr.size() + " items in your inventory.");
showInventory(arr);
list = new List(arr.toArray());
add(list);
list.addMouseListener(this);
list.setVisible(true);
}
public static void showInventory (ArrayList<String> theList) {
for (int i = 0; i < theList.size(); i++) {
System.out.println(theList.get(i));
}
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {
Object index = list.getSelectedValue();
System.out.println("You have selected: " + index);
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void paint(Graphics g) {
}
}
答案 0 :(得分:5)
这里有两个问题:
java.awt.List 没有带 Object [] 的构造函数:
list = new List();
for (String item : arr) {
list.add(item);
}
java.awt.List 有 getSelectedItem()而非 getSelectedValue():
你的ArrayList和List可以如下:
public void mouseReleased(MouseEvent e) {
Object index = list.getSelectedItem();
System.out.println("You have selected: " + index);
}
答案 1 :(得分:2)
您要同时导入java.util.List
和java.awt.List
。 现在编译器对你想要哪一个感到困惑。可能存在混淆。
与javax.swing.JList不同,java.awt.List没有将数组作为参数的构造函数。
此外,您仍然使用空paint()
方法。那是非常错误的。