简体   繁体   English

如何在JTable中渲染JTable?

[英]How do I render a JTable inside of a JTable?

I am trying to nest a JTable inside of another JTable's column (using a CellRenderer). 我试图将JTable嵌套在另一个JTable的列中(使用CellRenderer)。

Example (erroneous) output: 示例(错误)输出:

在此输入图像描述

Why does the following example not output a table within a table? 为什么以下示例不在表中输出表?

import java.awt.Component;

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

public class Test {

    public static void main(String[] args) {
        JTable table = new JTable(new CustomTableModel());
        table.setDefaultRenderer(Person.class, new CustomRenderer());
        JPanel panel = new JPanel();
        panel.add(new JScrollPane(table));
        JFrame frame = new JFrame();
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

@SuppressWarnings("serial")
class CustomTableModel extends AbstractTableModel {

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public int getRowCount() {
        return 1;
    }

    @Override
    public Object getValueAt(int row, int col) {
        if (col == 0) {
            return new Person("Bob");
        } else {
            return "is awesome!";
        }
    }
}

@SuppressWarnings("serial")
class CustomRenderer extends JPanel implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int col) {
        JTable t = new JTable(new CustomTableModel());
        add(new JScrollPane(t));
        return this;
    }
}

class Person {

    public String name = "";

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

Don't add the sub table to a scroll pane. 不要将子表添加到滚动窗格。 Instead, try adding the table to the center position of a JPanel with a BorderLayout, then add the tables header to the NORTH position 相反,尝试将表格添加到带有BorderLayout的JPanel的中心位置,然后将表格标题添加到NORTH位置

The main reason for this is the scroll pane will not be interactive and may hide data 主要原因是滚动窗格不是交互式的,可能会隐藏数据

Updated 更新

I'm on phone, so it's hard to read the code :P 我在打电话,所以很难看到代码:P

In your main table model, you need to override the getColumnClass method and make sure you are retuning Person.class for the required column (and the correct class types for the other columns to) 在主表模型中,您需要覆盖getColumnClass方法并确保为所需列重新调整Person.class(以及其他列的正确类类型)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM