gpt4 book ai didi

Java DefaultTableModel 从多个表收集数据

转载 作者:行者123 更新时间:2023-12-01 12:06:36 25 4
gpt4 key购买 nike

我有数据关系

Person-Attends-Course

Person
-------
id: integer primary key
name: string
prename: string
age: integer

Course
-------
courseName: string primary key
hours: integer

Attends
--------
id: integer primary key references Person
courseName: string primary key references Course

我需要进行数据验证。在网上查了很久,决定通过扩展DefaultTableModel来实现。到目前为止,我创建了下面的代码,但我有一些问题:

类(class)人物

class Person{
private String name, prename,id;
private int age;

public Person(){}

public String getName(){return this.name;}
public String getPrename(){return this.prename;}
public int getAge(){return this.age;}
public String getId(){return this.id;}

public void setName(String name){
try{
if(name.equals(""))
JOptionPane.showMessageDialog(null, "Must insert name");
else
this.name = name;
}
catch(NullPointerException e){
this.name = "";
}
}

public void setPrename(String prename){
if(prename.equals(""))
JOptionPane.showMessageDialog(null, "Must insert prename");
else
this.prename = prename;
}

public void setAge(int age){
try{
if(age <0 || age >=100)
JOptionPane.showMessageDialog(null, "Must insert valid age");
else
this.age = age;
}
catch(Exception e){
this.age = 0;
}
}

public void setId(String id){
this.id = id;
}
}

Class PersonTM

class PersonTM extends DefaultTableModel{
private final List<Person> personlist;
private final String[] columnNames = {"id", "name", "prename","age"};
private final Class[] columnClass = {String.class, String.class, String.class, Integer.class};

public PersonTM(){this.personlist = new ArrayList<>();}

@Override
public Class<?> getColumnClass(int columnIndex){
return columnClass[columnIndex];
}

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

public String[] getColumnNames(){return this.columnNames;}

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

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person row = personlist.get(rowIndex);
switch(columnIndex){
case 0:
return row.getId();
case 1:
return row.getName();
case 2:
return row.getPrename();
case 3:
return row.getAge();
default:
return null;
}
}

@Override
public void setValueAt(Object obj, int rowIndex, int columnIndex){
Person row = personlist.get(rowIndex);
switch(columnIndex){
case 0:
row.setId((String)obj);
break;
case 1:
row.setName((String)obj);
break;
case 2:
row.setPrename((String)obj);
break;
case 3:
row.setAge((Integer)obj);
break;
}
}
}

类类(class)

class Courses{
private String courseName;
private int hours;

public Courses(){}

public String getCourseName(){return this.courseName;}
public int getHours() {return this.hours;}

public void setCourseName(String courseName){
if(courseName.equals(""))
JOptionPane.showMessageDialog(null, "Must insert courseName");
else
this.courseName = courseName;
}

public void setHours(int hours){
if(hours <=0 || hours >=50)
JOptionPane.showMessageDialog(null, "Must insert valid hours");
else
this.hours = hours;
}
}

类类(class)TM

class CoursesTM extends DefaultTableModel{
private final List<Courses> courseslist;
private final String[] columnNames = {"course name","hours"};
private final Class[] columnClass = {String.class,Integer.class};

public CoursesTM(){this.courseslist = new ArrayList<>();}

@Override
public Class<?> getColumnClass(int columnIndex){
return columnClass[columnIndex];
}

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

public String[] getColumnNames(){return this.columnNames;}

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

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Courses row = courseslist.get(rowIndex);
switch(columnIndex){
case 0:
return row.getCourseName();
case 1:
return row.getHours();
default:
return null;
}
}

@Override
public void setValueAt(Object obj, int rowIndex, int columnIndex){
Courses row = courseslist.get(rowIndex);
switch(columnIndex){
case 0:
row.setCourseName((String)obj);
break;
case 1:
row.setHours((Integer)obj);
break;
}
}
}

上课

//here I am a little confused

class Attends{
private final Person p;
private final Course c;

public Attends(Person p,Course c){
this.p = p;
this.c = c;
}

public Person getPerson(){return this.p;}
public Course getCourse(){return this.c;}
}

类出勤TM

class AttendsTM extends DefaultTableModel{
private final PersonTM p;
private final CoursesTM c;
private final Map<Person,List<Course>> attendslist;
private String[] columnNames;
private final Class[] columnClass = {Person.class,Courses.class};

public AttendsTM(Map<Person,List<Courses>> attendslist){
this.attendslist = attendslist;
this.p = new PersonTM();
this.c = new CoursesTM();
}

public void setColumnNames(){
for (int i = 0; i < p.getColumnCount(); i++)
columnNames[i] = p.getColumnName(i);
for (int i = p.getColumnCount(); i < c.getColumnCount(); i++)
columnNames[i] = c.getColumnName(i);
}
}

类(class)查看器

class viewer extends JFrame{
private final JScrollPane scrollPane;
private final AttendsTM model;
private final JTable table;

public viewer(){
//collect data from db
Person p1 = new Person();
p1.setId("00001");
p1.setName("John");
p1.setPrename("Johnson");
p1.setAge(30);

Person p2 = new Person();
p2.setId("00002");
p2.setName("Jack");
p2.setPrename("Jackson");
p2.setAge(30);

Courses c1 = new Courses();
c1.setCourseName("History of art");
c1.setHours(25);

Courses c2 = new Courses();
c2.setCourseName("Music");
c2.setHours(15);

List<Courses> coursesList = new ArrayList<>();
coursesList.add(c1);
coursesList.add(c2);

Map<Person,List<Courses>> attendsMap = new LinkedHashMap<>();
attendsMap.put(p1, coursesList);
attendsMap.put(p2, coursesList);

model = new AttendsTM(attendsMap);
table = new JTable(model);
//add a blank row at the end of Jtable
model.addRow(new Object[model.getColumnCount()]);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(false);
table.setRowSelectionAllowed(true);
//resize columns and use horizontal scroll bar to view data
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//disable column dragging
table.getTableHeader().setReorderingAllowed(false);
scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}

public void initializeUI(){
add(scrollPane);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(300,300);
setVisible(true);
}
}

类TableModelExample

public class TableModelExample {
public static void main(String[] af){
Runnable runnable = new Runnable(){
@Override
public void run() {
new viewer().initializeUI();
}
};
EventQueue.invokeLater(runnable);
}
}

所以我的问题是:

  1. 我应该如何显示包含人员和类(class)中所有列的 JTable?我应该通过 attends 执行此操作以及如何执行此操作?

  2. 我如何从 attendsTM 中的人员和类(class)收集数据?我这样做对吗?

任何建议都将非常受欢迎。预先感谢您。

最佳答案

我没有彻底阅读你的代码(相当多),但基本上你会执行以下操作:

如果您使用DefaultTableModel,您很可能会使用构造函数DefaultTableModel(Object[][] data, Object[] columnNames)。在这种情况下,您将加载人员和类(class)并构建需要显示的数据的二维数组。此外,您只需根据需要传递列名称,例如如果 2D 数组中每行的第一个元素包含人名,您将传递类似“name”的内容作为列名称数组中的第一个元素。

二维数组的布局取决于您想要如何显示数据。行的每个元素对应于表中的一个单元格。如果您希望每个类(class)和每个人都有一行,您只需生成多行,很可能会获得冗余/重复的单元格。当然,您可以只填充第一个单元格并清空所有多余元素,以便在需要时呈现空单元格,但在这种情况下,您不应允许排序。

如果您想将一个人参加的所有类(class)放入一个单元格中,您可以使用预先格式化的字符串(据我所知,默认渲染器可以显示 html 格式的文本)或提供您自己的渲染器。

使用重复单元格的简单方法示例:

Object[][] data = new Object[numrows][];
int curRow = 0;
for( Person p : persons ) { //assuming you have loaded the persons already
for( Course c : p.getCourses() ) { //loop over all courses a person has taken
Object[] row = new Object[numcols]; //create a new row array

//just an example of how to fill the elements
row[0] = p.getName(); //column 1 will contain the person's name
row[1] = c.getCourseName(); //column 2 will contain the course name
...

data[curRow] = row;
curRow++;
}
}

然后您只需将该数组传递给 DefaultTableModel 构造函数即可。结果可能如下所示:

+-------------+------------------------+
| Person name | Course |
+=============+========================+
| Vassilis De | Java Programming |
+-------------+------------------------+
| Thomas | Java Programming |
+-------------+------------------------+
| Thomas | How to answer in SO |
+-------------+------------------------+
| Thomas | Writing good examples |
+-------------+------------------------+
| Thomas | Being polite |
+-------------+------------------------+

请注意,这仅涵盖如何从已加载的数据构建表模型。如何加载数据取决于您的应用程序,但在示例中我假设您使用的是 JPA 或类似的东西。

更新:

如果我正确理解您的评论,有两个基本问题:

  1. 在哪里加载数据
  2. 如何添加新列

我会在 Controller 类中执行这两项操作,然后将数据传递到表模型,即您甚至可能不需要 AttendsTM 等。请查看 MVC 模式以获取更多信息如何创建和使用 Controller 。

保存输入的数据时, Controller 将从表模型中读取数据并以允许您向数据库添加新条目的方式进行解释。同样,如何完成此操作取决于您的应用程序。

使用自定义表模型(例如,作为 DefaultTableModel 的子类)可能有一个原因:如果您想向模型添加一些允许您识别实体但不应该识别实体的键显示在表格中,然后您可以覆盖 getValueAt() 等以隐藏某些列。

关于Java DefaultTableModel 从多个表收集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27545658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com