初始化后JTable的着色行

时间:2012-08-07 15:17:48

标签: java swing netbeans jtable renderer

我通过提供一些示例代码来澄清我之前的问题

import java.awt.Color;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class TestTable extends javax.swing.JFrame
{
private JButton jButton1;
private JScrollPane jScrollPane1;
private JTable jTable1;

public TestTable()
{
    initComponents();
}

private void initComponents(){

    ///////////////////////////////////////////////
    //Initializing components
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    String data[][] = { {"A","B","C"},
                        {"R","S","T"},
                        {"U","V","W"}
                      };
    String col[] = {"X","Y","Z"};
    jTable1 = new JTable(new DefaultTableModel(data, col));
    jScrollPane1.setViewportView(jTable1);

    jButton1.setText("jButton1");

    ///////////////////////////////////////////////
    //positioning button and table
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(15, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375,     javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jButton1)
                    .addGap(160, 160, 160))))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117,     javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(47, 47, 47)
            .addComponent(jButton1)
            .addContainerGap(102, Short.MAX_VALUE))
    );

    ///////////////////////////////////////////////
    //create event callback for the button
    jButton1.setText("Change data & color");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    ///////////////////////////////////////////////
    pack();
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    //change the data in the table
    String data[][] = { {"a","b","c"},
                        {"r","s","t"},
                        {"u","v","w"}  };
    String col[] = {"x","y","z"};
    DefaultTableModel model= new DefaultTableModel(data,col);
    jTable1.setModel(model);

    //change the header in the table
    jTable1.getTableHeader().setBackground(Color.red);

    // IS IT POSSIBLE TO INSERT CODE HERE, WITHOUT REINITIALIZING jTable1,
    // SO THAT CLICKING THE BUTTON WILL TURN THE MIDDLE ROW GREEN?


    //change button text
    jButton1.setText("Changed");
}


public static void main(String[] args) 
{
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            new TestTable().setVisible(true);
        }
    });

}

}

当我在main中运行TestTable时,我能够更改行的颜色,但是我在回调中更改行颜色时遇到了问题(如上所述)。我的猜测是插入像

这样的代码
jTable1.getCellRenderer(0, 0).getTableCellRendererComponent(jTable1, String.class, false,false,     0,0).setBackground(Color.green);

因为我在这段代码中指定了表的入口(0,0),所以我希望这段代码会变成入口(0,0),但是,这会把整个表变成绿色!注意,我可以毫无问题地更改模型中的数据和标题的颜色。

任何帮助真诚地感谢。 谢谢 克里斯

4 个答案:

答案 0 :(得分:4)

以下是如何组合列颜色和行颜色的示例。您基本上在TableCellRenderer中执行测试,以查看背景是否应该是一种颜色。

import java.awt.Color;
import java.awt.Component;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class TestTable {

    public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        setBackground(null);
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        setText(String.valueOf(value));
        boolean interestingRow = row % 5 == 2;
        boolean secondColumn = column == 1;
        if (interestingRow && secondColumn) {
            setBackground(Color.ORANGE);
        } else if (interestingRow) {
            setBackground(Color.YELLOW);
        } else if (secondColumn) {
            setBackground(Color.RED);
        }
        return this;
    }

}

private JFrame f;
private JTable table;

protected void initUI() {
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    Vector<String> columNames = new Vector<String>();
    columNames.add("Col 0");
    columNames.add("Col 1");
    columNames.add("Col 2");
    for (int i = 0; i < 20; i++) {
        Vector<Object> v = new Vector<Object>();
        v.add(i % 3 == 0 ? "Hello" : "World");
        v.add("Some data in row " + (i + 1));
        v.add("Some other data in row " + (i + 1));
        data.add(v);
    }
    table = new JTable(new DefaultTableModel(data, columNames));
    Enumeration<TableColumn> en = table.getColumnModel().getColumns();
    while (en.hasMoreElements()) {
        TableColumn tc = en.nextElement();
        tc.setCellRenderer(new MyTableCellRenderer());
    }
    f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLocationRelativeTo(null);
    f.add(new JScrollPane(table));
    f.pack();
    f.setVisible(true);

}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new TestTable().initUI();
        }
    });
}

}

答案 1 :(得分:2)

  • 更新TableModel,请勿创建新的JTable,然后您必须将Renderer添加到新的JTable

  • 必须在Event Dispatch Thread上进行更新,否则任何更改都不会在GUI中显示,或者您从Exception获得RepaintManager

  • DefaultTableModelJTables view的所有更改都会自动完成,并且使用prepareRenderer也应重新绘制所有行,

答案 2 :(得分:0)

使用TableCellRenderer仍然是您想要的更新问题(如@Ryan所说)。您只是想要输入一些特殊代码来指示您想要特别着色的行。这是一个例子(使用您的测试代码):

import java.awt.Color;
import java.awt.Component;
import java.util.HashMap;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TestTable extends javax.swing.JFrame
{
    private JButton jButton1;
    private JScrollPane jScrollPane1;
    private JTable jTable1;
    private CustomRenderer renderer;

    public TestTable()
    {
        initComponents();
    }

    private void initComponents(){

        ///////////////////////////////////////////////
        //Initializing components
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        String data[][] = { {"A","B","C"},
                {"R","S","T"},
                {"U","V","W"}
        };
        String col[] = {"X","Y","Z"};
        jTable1 = new JTable(new DefaultTableModel(data, col));
        //Setup Renderer
        renderer = new CustomRenderer();
        //Add Renderer to table
        jTable1.getColumnModel().getColumn(0).setCellRenderer(renderer);
        jTable1.getColumnModel().getColumn(1).setCellRenderer(renderer);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(renderer);

        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("jButton1");

        ///////////////////////////////////////////////
        //positioning button and table
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap(15, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375,     javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addContainerGap())
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addComponent(jButton1)
                                                .addGap(160, 160, 160))))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117,     javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(47, 47, 47)
                        .addComponent(jButton1)
                        .addContainerGap(102, Short.MAX_VALUE))
        );

        ///////////////////////////////////////////////
        //create event callback for the button
        jButton1.setText("Change data & color");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        ///////////////////////////////////////////////
        pack();
    }


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {



        DefaultTableModel model= (DefaultTableModel)jTable1.getModel();
        //change the data in the table
        String data[][] = { {"a","b","c"},
                {"r","s","t"},
                {"u","v","w"}  };
        String col[] = {"x","y","z"};
        model.setDataVector(data, col);

        // Necessary to re-add listener (because we're creating new columns) 
        jTable1.getColumnModel().getColumn(0).setCellRenderer(renderer);
        jTable1.getColumnModel().getColumn(1).setCellRenderer(renderer);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(renderer);

        //change the header in the table
        jTable1.getTableHeader().setBackground(Color.red);


        // IS IT POSSIBLE TO INSERT CODE HERE, WITHOUT REINITIALIZING jTable1,
        // SO THAT CLICKING THE BUTTON WILL TURN THE MIDDLE ROW GREEN?
        renderer.colorModel.put(1, Color.green); //Yes

        //change button text
        jButton1.setText("Changed");
    }


    public static void main(String[] args) 
    {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestTable().setVisible(true);
            }
        });

    }

    //Custom Renderer - does the default rendering except if told the row should be a different color
    public static class CustomRenderer extends DefaultTableCellRenderer{

        //Stores what color you want for rows
        public HashMap<Integer, Color> colorModel = new HashMap<Integer, Color>();

        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean hasFocus, int row,
                int column) {
            //Default Rendering
            Component result = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            //Change color of background (If necessary)
            if(colorModel.get(row) != null){
                setBackground(colorModel.get(row));
            } else if(!isSelected){
                setBackground(null);
            }
            return result;
        }

    }
}

答案 3 :(得分:0)

谢谢尼克。

在扫描完这些方法之后,我找到了一种简单的方法来突出显示我想要的行,方法是选择它们然后为选择着色

    jTable1.setRowSelectionInterval(0, 1);
    jTable1.setSelectionBackground(Color.black);