Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java jTable单元格背景色_Java_Swing_Jtable_Background Color_Tablecellrenderer - Fatal编程技术网

Java jTable单元格背景色

Java jTable单元格背景色,java,swing,jtable,background-color,tablecellrenderer,Java,Swing,Jtable,Background Color,Tablecellrenderer,我正试图使用渲染器给jTable的一个单元格上色,但效果不太好,因为它们使表格滞后,无法看到。这是我的密码: TableCellRenderer Tcr = jTable1.getCellRenderer(x, y); Component c = Tcr.getTableCellRendererComponent(jTable1, jTable1.getValueAt(x, y), false, false, x, y);

我正试图使用渲染器给jTable的一个单元格上色,但效果不太好,因为它们使表格滞后,无法看到。这是我的密码:

            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);

                        }
                    }
                }    
            }
它把桌子完全涂上了颜色

编辑

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

/*
 * 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                   
}
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
包装脂肪酰锡;
导入ObjectModel.Timesheet;
导入java.awt.Component;
导入javax.swing.JLabel;
导入javax.swing.table.TableCellRenderer;
/**
*
*@author xtphere
*/
公共类示例扩展了javax.swing.JFrame{
/**
*创建新窗体主窗体
*/
公共示例(){
初始化组件();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jScrollPane1=newjavax.swing.JScrollPane();
jTable1=newjavax.swing.JTable();
CheckButton=newjavax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(新的javax.swing.table.DefaultTableModel(
新对象[][]{
{null,null,null,null},
{null,null,null,null},
{null,null,null,null},
{null,null,null,null}
},
新字符串[]{
“标题1”、“标题2”、“标题3”、“标题4”
}
));
jScrollPane1.setViewportView(jTable1);
CheckButton.setText(“检查表格”);
CheckButton.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
执行检查按钮操作(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED\u SIZE,375,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addComponent(选中按钮))
.addContainerGap(15,简称最大值))
);
layout.setVerticalGroup(
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(选中按钮)
.addGap(0,35,短最大值))
);
包装();
}//                         
private void CheckButtonActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
int x,y,i=1;
对于(x=0;x24){
系统输出打印(“leggi il 25,almeno?”);
c、 挫折背景(java.awt.Color.red);
}
}
}    
}          
} 
}                                           
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
java.util.logging.Logger.getLogger(例如.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
java.util.logging.Logger.getLogger(例如.class.getName()).log(java.util.logging.Level.SEVERE,
/*
 * 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                   
}
CellRenderer renderer = new DefaultCellRenderer(){

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        JLabel label = (JLabel)c;

        if (yourAlgorithmToDetectTheProperCell){ //i can't insert your condition from above, it's overkill ^^
            label.setBackGround(Color.RED);
        }

        return label;
    }
};

table.setCellRenderer(renderer);
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;
    }
}