package test;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.ListSelectionModel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JButton;
public class SelectionModelDemo implements ActionListener,ListSelectionListener{
JTable table = null;
ListSelectionModel selectionModel = null;
JLabel label = null;//顯示用戶選取表格的后的變化
public SelectionModelDemo(){
JFrame frame = new JFrame();
String[] name = {"字段1","字段2","字段3","字段4","字段5"};
String[][] data = new String[5][5];
int value = 1;
for(int i=0;i<data.length;i++){
for(int j=0;j<data[i].length;j++){
data[i][j] = String.valueOf(value++);
}
}
table = new JTable(data,name);
table.setDragEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(400,80));
table.setCellSelectionEnabled(true);
selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(this);
JScrollPane scrollPane = new JScrollPane(table);
JPanel panel = new JPanel();
JButton button = new JButton("單一選擇");
button.addActionListener(this);
panel.add(button);
button = new JButton("連續區間選擇");
button.addActionListener(this);
panel.add(button);
button = new JButton("多重選擇");
button.addActionListener(this);
panel.add(button);
label = new JLabel("您選取:");
Container contentPane = frame.getContentPane();
contentPane.add(panel,BorderLayout.NORTH);
contentPane.add(scrollPane,BorderLayout.CENTER);
contentPane.add(label,BorderLayout.SOUTH);
frame.setTitle("SelectionModelDemo");
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("單一選擇")){
label.setText("您選取了:" + "");
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
if(e.getActionCommand().equals("連續區間選擇")){
label.setText("您選取了:" + "");
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
}
if(e.getActionCommand().equals("多重選擇")){
label.setText("您選取了:" + "");
selectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
table.revalidate();
}
public void valueChanged(ListSelectionEvent e){
String tempString = "";
int[] rows = table.getSelectedRows();
int[] columns = table.getSelectedColumns();
for(int i=0;i<rows.length;i++){
for(int j=0;j<columns.length;j++){
tempString = tempString + "" + (String)table.getValueAt(rows[i],columns[j]);
}
}
label.setText("您選取了:" + tempString);
}
public static void main(String[] args){
new SelectionModelDemo();
}
}