2

我正在努力避免多个 JTable 的数据重复。基本上我有一个 TableModel,它有一个数据数组列表和一个 string[] 标头。

到目前为止没有什么新鲜事。现在我有另一个 TableModel,它具有相同的数据数组列表,但具有不同的 string[] 标头。

我无法让我的代码工作。我将不胜感激有关如何跨多个表模型共享数据数组列表的一些想法。

因此,当我更改数据时,所有模型都会更新并且没有数据重复。我想避免复制 arraylist 任何想法还是我对这个设置有误?我确实尝试过监听器,但我认为这样下去我们仍然有跨表模型的数据重复。

public class GymTableModel extends AbstractTableModel {
    private final ResourceBundle name = ResourceBundle.getBundle("labels/TableLabel", Locale.getDefault());
    private final String[] entete = {
        name.getString("LNAME"),
        name.getString("FNAME"),
        name.getString("CONTACT"),
        name.getString("TELFIX"),
        name.getString("TELGSM"),
        name.getString("EMAIL"),
        name.getString("BDATE"),
        name.getString("EDATE"),
        name.getString("LICENSE"),
        name.getString("AGE"),
        name.getString("ANCIEN")
    };

    @Override
    public Class<?> getColumnClass(int columnIndex){
        switch(columnIndex){
            case 6:
                return Date.class;
            case 7:
                return Date.class;
            case 9:
                return Integer.class;
            default:
                return Object.class;
        }
    }

    @Override
    public int getRowCount() {
        return gymList.size();
    }

    @Override
    public int getColumnCount() {
        return entete.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex){
            case 0:
                return gymList.get(rowIndex).getLastName();
            case 1:
                return gymList.get(rowIndex).getFirstName();
            case 2:
                return gymList.get(rowIndex).getContact();
            case 3:
                return gymList.get(rowIndex).getTelFix();
            case 4:
                return gymList.get(rowIndex).getTelGsm();
            case 5:
                return gymList.get(rowIndex).getEmail();
            case 6:
                return gymList.get(rowIndex).getDateBirth();
            case 7:
                return gymList.get(rowIndex).getDateClub();
            case 8:
                return gymList.get(rowIndex).getLicence();
            case 9:
                return gymList.get(rowIndex).getAge();
            case 10:
                return gymList.get(rowIndex).getAnciennete();
            default:
                return null; // should never happen;
        }
    }

    public String getColumnName(int columnIndex){
        return entete[columnIndex];
    }

}

现在我有另一个表,它具有相同的数据,但只有 3 列(LNAME、FNAME 和 AGE),所以 getColumnClass 不一样。问题是,我可以与另一个表模型共享我的 gymList 数据(这是一个 arrayList)吗?谢谢

4

4 回答 4

3

使用 Che 的答案作为包含四列的主表的基础,那么您的代码应该类似于:

AllTableModel model = new AllTableModel();
JTable mainTable = new JTable( model );

如果您想要另一个View模型,那么您将创建一个新视图而不是新模型。所以代码是:

JTable studentTable = new JTable( model );
studentTable.removeColumn( studentTable.getColumn("Subject") );
studentTable.removeColumn( studentTable.getColumn("Staff") );

现在 Student 表将只包含“Name”和“Grade”列。

这是 MVC 编程背后的基础。那就是你可以很容易地改变View. Model因此,您共享 1 个模型,而不是共享 3 个单独模型的数据。

于 2013-03-09T20:32:56.113 回答
2

您需要注册TableModelListenerTablemodel两者的.. 以便每当表的单元格值之一发生更改时,相同的值JTables都可以通过repaint(). JTable例如考虑下面给出的代码:
在此处输入图像描述

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.JScrollPane;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.ArrayList;
public class TablesHavingSameData extends JFrame implements TableModelListener
{
    MyTableModel model1;
    MyTableModel model2;
    JTable table1;
    JTable table2;
    ArrayList<ArrayList<String>> data;
    public void createAndShowGUI()
    {
        setTitle("JTables");
        Container c  = getContentPane();
        c.setLayout(new GridLayout(2,1));
        prepareData();
        model1 = new MyTableModel("table1");
        model2 = new MyTableModel("table2");
        table1 = new JTable(model1);
        table2 = new JTable(model2);
        model1.addTableModelListener(this);
        model2.addTableModelListener(this);
        JScrollPane jsTable1 = new JScrollPane(table1);
        JScrollPane jsTable2 = new JScrollPane(table2);
        c.add(jsTable1);
        c.add(jsTable2);
        setSize(500,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    @Override
    public void tableChanged(TableModelEvent evt)
    {
        AbstractTableModel model = (MyTableModel)evt.getSource();
        if (model == model1)
        {
            table2.repaint();
        }
        else
            table1.repaint();
    }
    private void prepareData()
    {
        data = new ArrayList<ArrayList<String>>();
        data.add(new ArrayList<String>(){{add("1");add("Michael");}});
        data.add(new ArrayList<String>(){{add("2");add("Derake");}});
        data.add(new ArrayList<String>(){{add("3");add("Archie");}});
    }
    private class MyTableModel extends AbstractTableModel
    {
        String columns[] ;
        String sTableName;
        public MyTableModel(String tableName)
        {
            sTableName = tableName;
            if ("table1".equals(sTableName))
            {
                columns = new String[] {"Roll No.","Name"};
            }
            else
            {
                columns = new String[] {"Emp ID.","Employee Name"};
            }
        }
        @Override
        public String getColumnName(int columnIndex)
        {
            return columns[columnIndex];
        }
        @Override
        public int getRowCount()
        {
            return data.size();
        }
        @Override 
        public int getColumnCount()
        {
            return columns.length;
        }
        @Override
        public Object getValueAt(int row, int col)
        {
            return data.get(row).get(col);
        }
        @Override
        public void setValueAt(Object aValue, int rowIndex, int colIndex)
        {
            data.get(rowIndex).set(colIndex,(String)aValue);
            fireTableCellUpdated(rowIndex,colIndex);
        }
        @Override
        public boolean isCellEditable(int row, int col)
        {
            return true;
        }
    }
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                TablesHavingSameData ths = new TablesHavingSameData();
                ths.createAndShowGUI();
            }
        });
    }
}
于 2013-03-09T18:25:17.000 回答
2

我使用了一个存储所有行的表模型,另一个只存储学生详细信息的表模型和存储员工详细信息的第三个表模型。他们都从同一来源获取数据,但每个表的列显示不同。

所有表模型

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;


public class AllTableExample {

    private JTabbedPane tabbedPane;
    private JTable allTable;
    private JTable studentTable;
    private JTable staffTable;

    public AllTableExample() {
        setData();

        allTable = new JTable();
        studentTable = new JTable();
        staffTable = new JTable();
    }

    public void createUI() {
        JFrame frame = new JFrame();

        tabbedPane = new JTabbedPane();

        tabbedPane.add("All", getAllTablePanel());
        tabbedPane.add("Student", getStudentTablePanel());
        tabbedPane.add("Staff", getStaffTablePanel());

        frame.add(tabbedPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Table Model Example.");
        frame.pack();
        frame.setVisible(true);
    }

    private void setData() {
        List<TableData> data = new ArrayList<TableData>();
        data.add(new TableData("John1", "A", "Maths", "Hellen1"));
        data.add(new TableData("John2", "A", "Maths", "Hellen2"));
        data.add(new TableData("John3", "A", "Maths", "Hellen3"));
        data.add(new TableData("John4", "A", "Maths", "Hellen4"));
        data.add(new TableData("John5", "A", "Maths", "Hellen5"));

        MainDataClass.getInstance().setData(data);
    }

    private JPanel getAllTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(new AllTableModel());
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    private JPanel getStudentTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(new StudentTableModel());
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    private JPanel getStaffTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(new StaffTableModel());
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new AllTableExample().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

}


class AllTableModel extends AbstractTableModel {

    List<TableData> tableData = new ArrayList<TableData>();

    Object[] columnNames = {"Name", "Grade", "Subject", "Staff"};

    public AllTableModel() {
        tableData = MainDataClass.getInstance().getData();
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column].toString();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        TableData data = tableData.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return data.getName();
        case 1:
            return data.getGrade();
        case 2:
            return data.getSubject();
        case 3:
            return data.getStaff();
        default:
            return null;
        }
    }

}

class StudentTableModel extends AbstractTableModel {

    List<TableData> tableData = new ArrayList<TableData>();

    Object[] columnNames = {"Name", "Grade"};

    public StudentTableModel() {
        tableData = MainDataClass.getInstance().getData();
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column].toString();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        TableData data = tableData.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return data.getName();
        case 1:
            return data.getGrade();
        default:
            return null;
        }
    }
}

class StaffTableModel extends AbstractTableModel {

    List<TableData> tableData = new ArrayList<TableData>();

    Object[] columnNames = {"Subject", "Staff"};

    public StaffTableModel() {
        tableData = MainDataClass.getInstance().getData();
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column].toString();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        TableData data = tableData.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return data.getSubject();
        case 1:
            return data.getStaff();
        default:
            return null;
        }
    }
}

class TableData {

    private String name;
    private String grade;
    private String subject;
    private String staff;

    public TableData(String name, String grade, String subject, String staff) {
        super();
        this.name = name;
        this.grade = grade;
        this.subject = subject;
        this.staff = staff;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getStaff() {
        return staff;
    }
    public void setStaff(String staff) {
        this.staff = staff;
    }
}

class MainDataClass {

    private static MainDataClass mainDataClass;
    private List<TableData> data;

    private MainDataClass() {

    }

    public static MainDataClass getInstance() {
        if(null == mainDataClass) {
            mainDataClass = new MainDataClass();
        }
        return mainDataClass;
    }

    public List<TableData> getData() {
        return data;
    }

    public void setData(List<TableData> data) {
        this.data = data;
    }
}

编辑-2:

参考@camickr 对仅使用一种模型的解释,我尝试了这个模型,它奏效了。使用removeColumn它的方法就像一个魅力。

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;


public class AllTableExample {


    private JTabbedPane tabbedPane;
    private JTable allTable;
    private JTable studentTable;
    private JTable staffTable;
    private AllTableModel allTableModel;

    public AllTableExample() {
        allTable = new JTable();
        studentTable = new JTable();
        staffTable = new JTable();

        allTableModel = new AllTableModel();
    }

    public void createUI() {
        JFrame frame = new JFrame();

        tabbedPane = new JTabbedPane();

        tabbedPane.add("All", getAllTablePanel());
        tabbedPane.add("Student", getStudentTablePanel());
        tabbedPane.add("Staff", getStaffTablePanel());

        frame.add(tabbedPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Table Model Example.");
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel getAllTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(allTableModel);
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    private JPanel getStudentTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(allTableModel);
        table.removeColumn(table.getColumn("Subject"));
        table.removeColumn(table.getColumn("Staff"));
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    private JPanel getStaffTablePanel() {
        JPanel panel = new JPanel();
        JTable table = new JTable(allTableModel);
        table.removeColumn(table.getColumn("Name"));
        table.removeColumn(table.getColumn("Grade"));
        JScrollPane scroll = new JScrollPane(table);
        panel.add(scroll);

        return panel;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                new AllTableExample().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

}


class AllTableModel extends AbstractTableModel {

    List<TableData> tableData = new ArrayList<TableData>();

    Object[] columnNames = {"Name", "Grade", "Subject", "Staff"};

    public AllTableModel() {
        List<TableData> data = new ArrayList<TableData>();
        data.add(new TableData("John1", "A", "Maths", "Hellen1"));
        data.add(new TableData("John2", "A", "Maths", "Hellen2"));
        data.add(new TableData("John3", "A", "Maths", "Hellen3"));
        data.add(new TableData("John4", "A", "Maths", "Hellen4"));
        data.add(new TableData("John5", "A", "Maths", "Hellen5"));
        tableData = data;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column].toString();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return tableData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        TableData data = tableData.get(rowIndex);
        switch (columnIndex) {
        case 0:
            return data.getName();
        case 1:
            return data.getGrade();
        case 2:
            return data.getSubject();
        case 3:
            return data.getStaff();
        default:
            return null;
        }
    }

}

class TableData {

    private String name;
    private String grade;
    private String subject;
    private String staff;

    public TableData(String name, String grade, String subject, String staff) {
        super();
        this.name = name;
        this.grade = grade;
        this.subject = subject;
        this.staff = staff;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getStaff() {
        return staff;
    }
    public void setStaff(String staff) {
        this.staff = staff;
    }
}

class MainDataClass {

    private static MainDataClass mainDataClass;
    private List<TableData> data;

    private MainDataClass() {

    }

    public static MainDataClass getInstance() {
        if(null == mainDataClass) {
            mainDataClass = new MainDataClass();
        }
        return mainDataClass;
    }

    public List<TableData> getData() {
        return data;
    }

    public void setData(List<TableData> data) {
        this.data = data;
    }
}
于 2013-03-09T18:08:23.687 回答
1

data具有不同列名的相同小示例:

import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class TestTable {

    public static class MyModel extends AbstractTableModel {

        private List<Object[]> data;
        private List<String> columnNames;

        public MyModel(List<String> columnNames, List<Object[]> data) {
            super();
            this.columnNames = columnNames;
            this.data = data;
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.size();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames.get(column);
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return data.get(rowIndex)[columnIndex];
        }

    }

    protected void initUI() {
        JFrame frame = new JFrame(TestTable.class.getSimpleName());
        List<String> columns = Arrays.asList("Name", "Age");
        List<String> columns2 = Arrays.asList("Label", "Price");
        List<Object[]> data = new ArrayList<Object[]>();
        for (int i = 0; i < 50; i++) {
            Object[] value = new Object[2];
            value[0] = "Something-" + i;
            value[1] = 12 + i;
            data.add(value);
        }
        JTable table = new JTable(new MyModel(columns, data));
        JTable table2 = new JTable(new MyModel(columns2, data));
        frame.add(new JScrollPane(table), BorderLayout.WEST);
        frame.add(new JScrollPane(table2), BorderLayout.EAST);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestTable().initUI();
            }
        });
    }
}
于 2013-03-09T17:42:57.093 回答