我对我的节目感到困惑。如果单击某个列表,如何在我的串联中获取整数数组?这是我正在尝试的代码。
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
public class JListDemo extends JFrame {
JList list;
String[] listColorNames = {"tres", "dos", "piso", "kwatro", "sais"};
int[] listColorValues = {3, 2, 1, 4, 6};
Container con;
public JListDemo() {
super("List Source Demo");
con = getContentPane();
con.setLayout(new FlowLayout());
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
con.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
con. (listColorValues[list.getSelectedIndex()]);
}
}
);
setSize(200, 200);
setVisible(true);
//setSizable(false);
}
public static void main(String[] args) {
JListDemo test = new JListDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:1)
如果我明白你想做什么:
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
JLabel price = new JLabel(listColorValues[list
.getSelectedIndex()] + "");
con.add(price);
con.revalidate();
}
});
但是,如果您希望文本显示在列表下方,则flowLayout不适合您的需要。
答案 1 :(得分:0)
如果它们相关,则不要制作两个不同的组件,而是将它们封装在如下的类中:
public class ColorVal {
private String colorValue;
private int colorIndex;
public String getColorValue() {
return colorValue;
}
public void setColorValue(String colorValue) {
this.colorValue = colorValue;
}
public int getColorIndex() {
return colorIndex;
}
public void setColorIndex(int colorIndex) {
this.colorIndex = colorIndex;
}
}
你可以这样做:
public class JavaApplication2 extends JFrame {
JList list;
String[] listColorNames = new String[10];
List<ColorVal> colorValList = new ArrayList<ColorVal>();
ColorVal colorVal = new ColorVal();
Container con;
public JavaApplication2() {
super("List Source Demo");
colorVal = new ColorVal();
colorVal.setColorIndex(2);
colorVal.setColorValue("dos");
colorValList.add(colorVal);
colorVal = new ColorVal();
colorVal.setColorIndex(1);
colorVal.setColorValue("piso");
colorValList.add(colorVal);
//add your other colors
con = getContentPane();
con.setLayout(new FlowLayout());
for (int i = 0; i < colorValList.size(); i++) {
listColorNames[i] = colorValList.get(i).getColorValue();
}
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
con.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
System.out.println(colorValList.get(list.getSelectedIndex()).getColorIndex()); //do what you want
}
});
setSize(200, 200);
setVisible(true);
//setSizable(false);
}
public static void main(String[] args) {
JavaApplication2 test = new JavaApplication2();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
使用java对象和类。