1
下面是我的代码,它在Swing中创建一个列表。当我点击列表时,它会改变它的颜色,但我需要显示文本而不是背景中的颜色变化;或者当我点击列表项目时,它需要在单独的窗口/在该窗口内显示一些文本。请帮助我解决这个问题。下面是我的代码,它点击改变颜色。使用Swing创建列表项的列表和动作
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
public class JListDemo extends JFrame {
JList list;
String[] listColorNames = {"black", "blue", "green", "yellow",
"white"};
Color[] listColorValues = {Color.BLACK, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.WHITE};
Container contentpane;
public JListDemo() {
super("List Source Demo");
contentpane = getContentPane();
contentpane.setLayout(new FlowLayout());
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentpane.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
contentpane.setBackground(listColorValues[list
.getSelectedIndex()]);
}
});
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
JListDemo test = new JListDemo();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
您的代码有效。应该显示哪些文字?哪里? – trashgod 2013-03-14 10:32:05
如果你再准备一些问题,你会更容易得到答案。除了更准确地说明你想做什么之外,你应该让我们知道你已经阅读了Swing教程。我们不会为你做你的阅读,但是如果你在教程中有某些你不明白的地方,我们可以提供帮助。 – 2013-03-14 10:54:37