jTable单元格背景色 [英] jTable Cell background color

查看:82
本文介绍了jTable单元格背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有人告诉我要在Google上进行搜索之前,我已经做到了,到目前为止,每种方法都无效.

Before anybody tells me to go and search it on google, I've done that and every single method so far didn't worked.

我尝试使用渲染器为jTable的单元格着色,但是它们没有用,因为它们滞后于表格并使其看不到.这是我的代码:

I've tried to color a cell of a jTable using the renderers, but they are useless, as they lag the table and make it impossible to see. here's my code:

            TableCellRenderer Tcr = jTable1.getCellRenderer(x, y);
            Component c = Tcr.getTableCellRendererComponent(jTable1, jTable1.getValueAt(x, y), false, false, x, y);


            if(x > 0 && x < (jTable1.getRowCount()-1) && y > 1 && y < (jTable1.getColumnCount()-1)){
                if(!jTable1.getValueAt(x, y).equals(null) && !jTable1.getValueAt(x, y).equals("F") && !jTable1.getValueAt(x, y).equals(" ")){
                    if(!jTable1.getValueAt(x, y).toString().contains("/P") && !jTable1.getValueAt(x, y).toString().equals("P")){                            
                        if(Double.parseDouble(jTable1.getValueAt(x, y).toString()) > 24){
                            setBackground(java.awt.Color.red);

                        }
                    }
                }    
            }

我没有将其放入rendererclass中,因为它滞后了,我将其放入cicle的双精度中,具体地说,放入了第二个cicle.我希望它为超过24的单元格上色,如果现在我写

I haven't put it into a rendererclass because it lags, I've put it in a double for cicle, specifically, into the second cicle. I want it to color the cell that goes over 24, as it is now, it doesn't work, if i write

c.setBackground(Color.red);

它完全为桌子着色

编辑

根据要求,我创建了一个描述我的问题的小示例,我不知道是否存在发布可运行示例的特定方法,但是以下代码(netbeans中的代码)代表了完整的程序:

As asked, I created a small example that describes my problem, I don't know if there's a specific way to post a runnable example, but the following code( in netbeans) represents the complete program:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fatturazione;

import ObjectModel.Timesheet;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.table.TableCellRenderer;


/**
 *
 * @author xtphere
 */
public class Example extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Example() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        CheckButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        CheckButton.setText("Check the table");
        CheckButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckButtonActionPerformed(evt);
            }
        });

        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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(CheckButton))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(CheckButton)
                .addGap(0, 35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void CheckButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
        int x, y, i = 1;


        for(x = 0; x < jTable1.getRowCount(); x++){

            for(y = 0;  y < jTable1.getColumnCount(); y++){

                TableCellRenderer Tcr = jTable1.getCellRenderer(x, y);
                Component c = Tcr.getTableCellRendererComponent(jTable1, jTable1.getValueAt(x, y), false, false, x, y);

                if(jTable1.getValueAt(x, y) == null)
                {
                    jTable1.setValueAt("P", x, y);
                }

                if(jTable1.getValueAt(x, y) != null && !jTable1.getValueAt(x, y).equals("F") && !jTable1.getValueAt(x, y).equals(" ")){
                        System.out.print(jTable1.getValueAt(x, y)+"\n");                          
                        if(!jTable1.getValueAt(x, y).toString().contains("/P") && !jTable1.getValueAt(x, y).toString().equals("P")){                            
                            System.out.print("prima del maggiore di 24");
                            if(Double.parseDouble(jTable1.getValueAt(x, y).toString()) > 24){
                                System.out.print("leggi il 25, almeno?");
                                c.setBackground(java.awt.Color.red);                                
                            }
                        }
                    }    


            }          
        } 


    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Example.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Example().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton CheckButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   
}

推荐答案

首先,变量名称不应以大写字母开头.您的某些变量正确,而其他变量则不正确.保持一致!

First of all variable names should NOT start with an upper case character. Some of your variables are correct, others are not. Be consistent!!!

我尝试使用渲染器为jTable的单元格着色,但是它们滞后于表格并使其看不到是没有用的.

I've tried to color a cell of a jTable using the renderers, but they are useless they lag the table and make it impossible to see.

仅仅因为您不了解该概念并不会使其失效.问题出在您的代码上,而不是渲染器的概念上.

Just because you don't understand the concept does not make it useless. The problem is with your code, not the concept of renderers.

您发布的代码没有任何意义.您无法设置单个单元格的颜色.颜色是在单元格为渲染器时确定的,这就是为什么需要使用渲染器的原因.

Your posted code makes no sense. You can't set the color of an individual cell. The color is determined when the cell is renderer, which is why you need to use a renderer.

它完全为桌子上色

it colors the table completely

是的,一旦您设置了渲染器的背景,以后所有单元格都将使用该颜色.您需要在渲染每个单元格之前将颜色重置为其默认值

Yes, once you set the background of the renderer all cells in the future will use that color. You need to reset the color to its default before rendering each cell

背景必须为红色,以防万一,它是一个数字并且大于24,

the background must be red just in case it's a number AND it's higher than 24,

然后做一个积极的检查,而忘记所有那些消极的检查.

Then do a positive check and forget about all those negative checks.

使用以上所有建议,您可能需要一个渲染器,例如:

Using all the above suggestions you might have a renderer something like:

class ColorRenderer extends DefaultTableCellRenderer
{
    @Override
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        if (isSelected)
            setBackground( table.getSelectionBackground() );
        else
        {
            setBackground( table.getBackground() );

            try
            {
                int number = Integer.parseInt( value.toString() );

                if (number > 24)
                    setBackground( Color.RED );
            }
            catch(Exception e) {}
        }

        return this;
    }
}

这篇关于jTable单元格背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆