簡體   English   中英

Java Swing:如何使用JTable?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM