[英]Java Swing: JTable tableChanged does not work after model is updated
[英]Java Swing: How does using a JTable work?
我正在尝试建立一个小的表来显示约会。 这是我到目前为止所拥有的。 也许您可以向我提示我做错了什么,或者走哪条路。
public class AppointmentTable extends JFrame{
public static void main(String[] args) {
JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>()));
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
AppointmentTable frame = new AppointmentTable();
frame.add(scrollPane);
frame.setVisible(true);
}
public class AppointmentTable extends JFrame{
public static void main(String[] args) {
JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>()));
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
AppointmentTable frame = new AppointmentTable();
frame.add(scrollPane);
frame.setVisible(true);
}
}
public class AppointmentTableModel extends AbstractTableModel {
private int columns;
private int rows;
ArrayList<Appointment> appointments;
public AppointmentTableModel(int columns, int rows,
ArrayList<Appointment> appointments) {
this.columns = columns;
this.rows = rows;
this.appointments = appointments;
}
@Override
public int getColumnCount() {
return columns;
}
@Override
public int getRowCount() {
return rows;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return appointments.get(rowIndex).getByColumn(columnIndex);
}
}
public class Appointment {
private Date date;
private Sample sample;
private String comment;
private ArrayList<Action> history;
public Appointment(Date date, Sample sample, String comment) {
this.date = date;
this.sample = sample;
this.comment = comment;
this.history = new ArrayList<Action>();
}
public Object getByColumn(int columnIndex) {
switch (columnIndex) {
case 0: return date;
case 1: return date;
case 2: return sample;
case 3: return sample;
case 4: return history;
case 5: return comment;
}
return null;
}
}
public class Action {
String action;
public Action(String act){
this.action=act;
}
}
首先,您模型的getRowCount()
方法不正确,应该是
public int getRowCount() {
return appointments.size();
}
然后,您将一个空的约会列表传递给您的模型,因此该表不显示任何内容!
JTable table = new JTable(new AppointmentTableModel(10, 6, new ArrayList<Appointment>()));
在创建表之前,请使用一些数据初始化列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.