繁体   English   中英

Java-根据tablemodel中的值为JTable中的行着色

[英]Java - Coloring Row in JTable depending on value in the tablemodel

我正在尝试根据表中的列之一为表中的每一行着色。 我在理解渲染器的概念时遇到了麻烦,我尝试了几种不同的渲染器,但似乎不了解它们的作用。

我正在尝试将讲师给我们的特定API中的前十名赛车手加载到表格模型中,但根据赛车手的性别为每行上色(这是由Finisher / Racer的getCategory()方法返回的)宾语)。

仅供参考,DataTable是我们的讲师编写的对象。 它基本上是2D数组对象。

public void showRacers(DefaultTableModel tblModel,
        @SuppressWarnings("rawtypes") JList listOfRaces) {
    // Clear the model of any previous searches
    tblModel.setRowCount(0);
    // Initialize an object to the selected city
    CityNameAndKey city = (CityNameAndKey) listOfRaces.getSelectedValue();
    // Get the runners for this city
    DataTable runners = this.getRunners(city);
    // Set the column headers
    this.setColumnHeaders(tblModel);
    // Make an array list of object Finisher
    ArrayList<Finisher> finisherList = new ArrayList<Finisher>();
    // Make an array that holds the data of each finisher
    Object[] finisherData = new Object[6];
    // Make a finisher object
    Finisher f;
    for (int r = 0; r < 10; r++) {
        // Assign the data to the finisher object
        finisherList.add(f = new Finisher(runners.getCell(r, 0), runners
                .getCell(r, 1), runners.getCell(r, 2), runners
                .getCell(r, 3), runners.getCell(r, 4), runners
                .getCell(r, 5)));
        // Add the data into the array
        finisherData[0] = f.getPosition();
        finisherData[1] = f.getBibNo();
        finisherData[2] = f.getTime();
        finisherData[3] = f.getGender();
        finisherData[4] = f.getCategory();
        finisherData[5] = f.getRuns();
        // Put it into the table model
        tblModel.addRow(finisherData);
    }
}

我将不胜感激的是解释,而不仅仅是我的问题的答案。 答案的指导非常有用,有些代码将非常有帮助,但是请不要:“您应该写这篇文章: ten lines of code I don't get

非常感谢你! :)

使用TableCellRenderer仅允许您为一列着色。 您将必须为每一列使用一个。 一种更简单的方法是重写JTable中的prepareRenderer(...)为整个行着色。

在此处查看“ 垃圾桶”的答案或在“ camickr”的答案

暂无
暂无

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

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