62,621
社区成员
发帖
与我相关
我的任务
分享package com.gloomyfish.swing.rounedpanel;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class JTableDemo extends JFrame
{
public JTableDemo()
{
super("Table Demo");
initComponents();
}
private void initComponents() {
Person pOne = new Person();
pOne.setName("Mike");
pOne.setAge(25);
pOne.setAddress("UK");
pOne.setCompany("IBM");
Person pTwo = new Person();
pTwo.setName("Johe");
pTwo.setAge(27);
pTwo.setAddress("US");
pTwo.setCompany("Oracle");
List<Person> list = new ArrayList<Person>();
list.add(pOne);
list.add(pTwo);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(new MyTableModel(list));
JScrollPane scrollPane = new JScrollPane(table);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
this.pack();
this.setVisible(true);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = new String[]{"Name", "Age", "Address", "Company"};
private List<Person> data = null;
public MyTableModel(List<Person> data)
{
this.data = data;
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
Person p = data.get(row);
if(col == 0)
{
return p.getName();
}
else if(col == 1)
{
return p.getAge();
}
else if(col == 2)
{
return p.getAddress();
}
else if(col == 3)
{
return p.getCompany();
}
else
{
return null;
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
return false;
}
}
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
private String name;
private int age;
private String address;
private String company;
}
public static void main(String[] args)
{
new JTableDemo();
}
}