没有在jtable

时间:2017-07-12 12:29:33

标签: java swing jtable radio-group jradiobutton

我正在尝试添加类似于http://www.java2s.com/Code/Java/Swing-Components/RadioButtonTableExample2.htm的单选按钮组 在我的表单中,我按照上面的教程,但我使用AbstractTableModel而不是DefaultTableModel。 这是我的代码,它没有在colomun上显示任何错误:

StudentTableModel model = new StudentTableModel(studentList);

    // JScrollPane scrollPane = new JScrollPane(table);
    final JScrollPane scrollPane = new JScrollPane(
            table,
            JScrollPane.VERTICAL_SCROLLBAR_NEVER,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    Dimension d = table.getPreferredSize();
    scrollPane.setPreferredSize(
            new Dimension(d.width,table.getRowHeight()*rows));

    // code for radio buttons
    String[] answer = { "A", "B", "C" };
    TableColumnModel columnModel = table.getColumnModel();
    for (int tc = 7; tc < table.getColumnCount(); tc++)
    {
    columnModel.getColumn(tc).setCellRenderer(
            new MainClass().new RadioButtonRenderer(answer));
    columnModel.getColumn(tc).setCellEditor(
            new MainClass().new RadioButtonEditor(new JCheckBox(),  new MainClass().new RadioButtonPanel(
                    answer)));
    }
    table.setModel(model);

    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.getContentPane().add(navigation, BorderLayout.SOUTH);
    frame.pack();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

提前致谢!!

1 个答案:

答案 0 :(得分:1)

在设置模型之前,代码是尝试设置渲染器和编辑器。因此,没有列可以设置渲染器/编辑器。必须首先设置模型,然后才会创建列 - 只是创建模型不会将其链接到表,表不会事先知道它将具有多少列。

可能你想要像

这样的东西
StudentTableModel model = new StudentTableModel(studentList);
table.setModel(model);    // moved from below

// JScrollPane scrollPane = new JScrollPane(table);
...

您正在关注的示例是这样做的,实际上它创建的表格将模型作为参数...

提示:new MainClass()和其他人new MainClass().new RadioButtonRenderer(...中的原因是什么?你真的想要一个新的MainClass吗?将这些类声明为static并删除new MainClass()