JTable:显示包含列表

时间:2015-07-22 09:56:50

标签: java swing jtable

我有一个名为“个人资料”的对象列表,每个个人资料都有一个功能列表(个人资料可以执行的操作)以及与该个人资料相关联的用户列表。

我想在JTable中显示这些信息。首先,显示具有le功能的配置文件,然后是该配置文件中的用户。像这样:

------------------------------------
|Profile | Operation1 | Operation 2|
------------------------------------
P1       |     X      |            | <- users1 in P1 can do only Operation1
 --user1 |            |            | 
 --user2 |            |            | 
P2       |     X      |     X      |
 --user2 |            |            | 
 --user3 |            |            |
 --user4 |            |            | 
------------------------------------  

首先,我实现了一个更智能的getRowCount()方法,然后是一个getValueAt方法,它在JTable中打印一个配置文件,在其行下打印与之关联的所有用户。 事情似乎有效,但是当点击一行时,JTable完成修改,即使isCellEditor()总是返回false并且方法setValueAt(..)没有实现(行被更改,最后一个Profile添加到JTable中) 。 谁能告诉我为什么会这样?我想,也许,每次单击一行时都会调用getValueAt(...)方法,这会让我的数据结构出现问题! 接下来,有一种方法可以告诉JTable列只包含布尔值,该行是否与配置文件相关?提前谢谢

接下来,代码: JFrame中:

import it.Profile.Operation;
import java.awt.BorderLayout;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;

public class JTableTest extends JFrame {

List<Profile> list_profiles = new LinkedList<Profile>();
List<User> list_users = new LinkedList<User>();

public JTableTest() {
    super();

    Profile admin = new Profile("P1");
    admin.addOp(Operation.OPERATION1);
    admin.addOp(Operation.OPERATION2);
    admin.addUser(new User("User 1"));
    list_profiles.add(admin);

    Profile p1 = new Profile("P2");
    p1.addOp(Operation.OPERATION2);
    p1.addUser(new User("User 2"));
    list_profiles.add(p1);

    Profile p2 = new Profile("P3");
    p2.addOp(Operation.OPERATION1);
    p2.addOp(Operation.OPERATION3);
    p2.addUser(new User("User 1"));
    list_profiles.add(p2);

    create_jframe();
}

private void create_jframe() {

    JTable profile_jtable = new JTable(new ProfileTableModel());
    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) profile_jtable
            .getTableHeader().getDefaultRenderer();
    renderer.setHorizontalAlignment(0);

    this.getContentPane().add(new JScrollPane(profile_jtable),
            BorderLayout.CENTER);

}

public static void main(String[] args) {
    JFrame jframe = new JTableTest();
    jframe.pack();
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.setVisible(true);
}

private class ProfileTableModel extends AbstractTableModel {

    /**
     * 
     */
    int riga = 0;
    private int users_number = 0;
    private Profile profilo = list_profiles.get(riga);
    private boolean show_profile = true;

    private static final long serialVersionUID = 7525220824319997602L;
    private String[] columns_name = { "User", "OPERATION 1", "OPERATION 2",
            "OPERATION 3" };

    public ProfileTableModel() {
        super();
    }

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

    @Override
    public int getRowCount() {
        int count = list_profiles.size();
        for (int i = 0; i < list_profiles.size(); i++) {
            count += list_profiles.get(i).getListUsers().size();
        }
        return count;
    }

    /*
     * @Override public Class<?> getColumnClass(int c) { if (c == 0) return
     * String.class; return Boolean.class; }
     */

    @Override
    public Object getValueAt(int row, int column) {

        if (show_profile) {
            if (column == 0)
                return profilo.getName();
            Operation f = null;
            switch (column) {
            case 1:
                f = Operation.OPERATION1;
                break;

            case 2:
                f = Operation.OPERATION2;
                break;

            case 3:
                f = Operation.OPERATION3;
                users_number = profilo.getListUsers().size();
                if (users_number != 0)
                    show_profile = false;
                break;
            }
            return list_profiles.get(riga).getOperations().contains(f);
        } else {

            if (column == 0) {
                users_number--;
                String nome = profilo.getListUsers().get(users_number)
                        .getName();
                if (users_number == 0 && riga < list_profiles.size() - 1) {
                    riga++;
                    profilo = list_profiles.get(riga);
                }
                return "---" + nome;
            }
            if (column == 3)
                show_profile = true;

        }
        return null;
    }

    @Override
    public String getColumnName(int i) {
        return columns_name[i];
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        if (row == 0 || row == 1)
            return false;
        return true;
    }

   }
}

资料:

import java.util.LinkedList;
import java.util.List;

public class Profile {

public enum Operation {
    OPERATION1, OPERATION2, OPERATION3 
}

private List<Operation> list_operations;
private String name;
private List<User> list_users;

public Profile (String name) {
    this.name=name;
    this.list_operations=new LinkedList<Operation>();
    this.list_users=new LinkedList<User>();
}

public Profile (String name, List<Operation> list_operation) {
    this.name=name;
    this.list_operations=list_operations;
}

public void addOp(Operation new_function) {
    this.list_operations.add(new_function);
}

public void removeOp(Operation op) {
    this.list_operations.remove(op);
}

public String getName() {
    return name;
}

public List<Operation> getOperations() {
    return this.list_operations;
}

public void setName(String name) {
    this.name=name;
}

public void addUser(User user) {
    this.list_users.add(user);
}

public List<User> getListUsers() {
    return list_users;
}
}

用户:     公共类用户{

public String getName() {
    return name;
}

private String name;


public User (String name) {
    this.name=name;
}
}

Upolad图片让您了解我的问题: 点击之前,事情似乎有效

enter image description here

点击后,当我的梦想崩溃时:P

enter image description here

您可以看到点击后jTable结构被修改。

编辑:getValueAt根据Eric先生的提示修改

@Override
    public Object getValueAt(int row, int column) {
        int cpt = 0;
        int profile = 0;
        int user = 0;
        for (Profile p : list_profiles) {
            if (cpt++ == row) {
                if (column == 0)
                    return list_profiles.get(profile).getName();
                Operation f = null;
                switch (column) {
                case 1:
                    f = Operation.OPERATION1;
                    break;

                case 2:
                    f = Operation.OPERATION2;
                    break;

                case 3:
                    f = Operation.OPERATION3;
                    profile++;
                    break;
                }
                return list_profiles.get(profile).getOperations()
                        .contains(f);
            } else {
                String nome;
                for (User u : p.getListUsers()) {
                    if (cpt++ == row) {
                        if (column == 0) {
                            return list_profiles.get(profile)
                                    .getListUsers().get(user).getName();
                        }
                    }
                }
            }
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

问题来自您在getValueAt()方法中所做的事情。基本上,您正在使用字段rigashow_profileprofilousers_number更改表格模型的状态。

您认为Swing始终以正确的顺序调用getValueAt()(第1行,第1列,第1行,第2列,依此类推)。这是第一次使用,但是在您点击表格后,Swing可能需要再次为特定单元格调用getValueAt(),这会使您的模型完全混乱。 相反,您应该假设Swing会在感觉到它时以及以任何顺序调用getValueAt()

所以你应该摆脱这些领域,并应用无状态逻辑。例如,要知道在给定行显示什么,您可以浏览列表并停在右侧行:

int cpt = 0
for(Profile p : list_profiles){
   if(cpt++ == row){
      // return value corresponding to profile      
   }else{
      for(User u: p.getListUsers()){
         if(cpt++ == row)
             // return value corresponding to user     
      }
   }
}
  

接下来,有一种方法可以告诉JTable列中只包含布尔值,该行是否与配置文件相关?

我认为如果您在Boolean中返回String而不是getValueAt(),则Swing会正确显示JTable。您还需要覆盖getColumnClass()方法并返回String.class column==0Boolean.class。 (返回null将显示一个空单元格,就像目前的情况一样)

注意:也许考虑使用TreeTable作为用例(这将使您的模型实现起来更简单,因为您的数据自然具有树结构)。 SwingX有really good implementation