📄 listdemo.java
字号:
// ListDemo.java: Use list to select a country and display the selected country's flag
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListDemo extends JFrame implements ListSelectionListener
{
// 声明引用图像数组的变量,并初始化变量
private ImageIcon[] imageIcon = new ImageIcon[9];
// 声明引用标签数组的变量
private JLabel[] jlblImageViewer = new JLabel[9];
// 声明列表框变量
JList jlst;
// 主方法
public static void main(String[] args)
{
ListDemo frame = new ListDemo();
frame.setSize(650, 500);
frame.setTitle("List Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// Default Constructor
public ListDemo()
{
// 对图像数组元素初始化
imageIcon[0] = new ImageIcon("images/us.gif");
imageIcon[1] = new ImageIcon("images/ca.gif");
imageIcon[2] = new ImageIcon("images/uk.gif");
imageIcon[3] = new ImageIcon("images/germany.gif");
imageIcon[4] = new ImageIcon("images/fr.gif");
imageIcon[5] = new ImageIcon("images/denmark.gif");
imageIcon[6] = new ImageIcon("images/norway.gif");
imageIcon[7] = new ImageIcon("images/china.gif");
imageIcon[8] = new ImageIcon("images/india.gif");
// 声明引用字符串数组的变量 country, 并对字符串数组元素初始化
String[] countries = {"United States of America", "Canada", "United Kingdom", "Germany", "France", "Denmark", "Norway", "China", "India"};
// 用字符串数组为参数,创建一个列表框
jlst = new JList(countries);
//创建一个容纳9个标签的面板
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 3));
//对标签数组元素初始化
for (int i=0; i<9; i++)
{
p.add(jlblImageViewer[i] = new JLabel());
jlblImageViewer[i].setHorizontalAlignment(SwingConstants.CENTER);
}
//把面板和列表框加入框架
getContentPane().add(p, BorderLayout.CENTER);
getContentPane().add(new JScrollPane(jlst), BorderLayout.WEST);
// 为列表框注册监听器
jlst.addListSelectionListener(this);
}
//处理列表框事件的处理器
public void valueChanged(ListSelectionEvent e)
{
// 获取列表框中,被选择的选项的索引号,保存在数组 indices中
int[] indices = jlst.getSelectedIndices();
int i;
// 为对应索引号的标签设置图像对象
for (i=0; i<indices.length; i++)
{
jlblImageViewer[i].setIcon(imageIcon[indices[i]]);
}
// Remove icons from the rest of the labels
for (; i<9; i++)
{
jlblImageViewer[i].setIcon(null);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -