11案例:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ResourceBundle.Control;
import java.awt.EventQueue;
import java.util.ResourceBundle.Control;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class Test extends JFrame {
private JPanel contentPane;
JList list;
JList list;
/**
* Launch the application.
*/
public static void main(String[] args) {
//MVC
// Model View Control
// 模型 (数据) 视图 控制
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
* Launch the application.
*/
public static void main(String[] args) {
//MVC
// Model View Control
// 模型 (数据) 视图 控制
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
list = new JList();
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
System.out.println(list.getSelectedValue());
}
});
list.setModel(new AbstractListModel() {
String[] values = new String[] {"A", "B", "C", "D", "E"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
contentPane.add(list, BorderLayout.CENTER);
}
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
list = new JList();
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
System.out.println(list.getSelectedValue());
}
});
list.setModel(new AbstractListModel() {
String[] values = new String[] {"A", "B", "C", "D", "E"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
contentPane.add(list, BorderLayout.CENTER);
}
}
结果 如下 :