下面是我在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);
}
}
答案 0 :(得分:0)
我认为以下代码段会产生所需的效果。您应该放大框架以查看效果。
contentpane.add(new JLabel(listColorNames[list.getSelectedIndex()]),BorderLayout.WEST);
您可以添加JPanel以查看更灵活的结果。