📄 listexample.java
字号:
//ListExample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListExample
{
public static void main(String[] args)
{
ListFrame frame = new ListFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class ListFrame extends JFrame
{
public ListFrame()
{
setTitle("ListExample");
setSize(WIDTH, HEIGHT);
Container contentPane = getContentPane();
//建立容纳文本区的面板
JPanel textPanel = new JPanel();
//新建文本区
myTextArea = new JTextArea(checkedLabel, 5, 20);
JScrollPane textScrollPane = new JScrollPane(myTextArea);
textPanel.add(textScrollPane);
contentPane.add(textPanel);
//建立容纳列表的面板
listPanel = new JPanel();
//新建列表框
String[] courses = {"Math", "English", "Physics", "Chemic",
"Biology", "Politics"};
courseList = new JList(courses);
//设置列表中想显示的行数
courseList.setVisibleRowCount(4);
//增加事件监听器
courseList.addListSelectionListener(new courseListener());
JScrollPane listScrollPane = new JScrollPane(courseList);
listPanel.add(listScrollPane);
contentPane.add(listPanel, BorderLayout.SOUTH);
}
//事件监听器
private class courseListener
implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent event)
{
Object[] selectedCourses = courseList.getSelectedValues();
int[] selectedIndexCourses = courseList.getSelectedIndices();
StringBuffer tempSeletedText = new StringBuffer(checkedLabel);
for (int i = 0; i < selectedCourses.length; i++)
{
String str1 = new String(selectedIndexCourses[i] + ", ");
String str2 = (String)selectedCourses[i];
tempSeletedText.append(str1);
tempSeletedText.append(str2);
tempSeletedText.append("\n");
}
myTextArea.setText(tempSeletedText.toString());
}
}
public static final int WIDTH = 300;
public static final int HEIGHT = 250;
public static final String checkedLabel="You choosed: \nIndex, Course\n";
private JTextArea myTextArea;
private JList courseList;
private JPanel listPanel;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -