簡體   English   中英

jTable 單元格背景顏色

[英]jTable Cell background color

我正在嘗試使用渲染器為 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);

                        }
                    }
                }    
            }

我沒有把它放到渲染器類中,因為它滯后,我已經把它放在一個雙循環中,特別是第二個循環。 我希望它為超過 24 的單元格着色,就像現在一樣,如果我寫,它不起作用

c.setBackground(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                   
}

首先,變量名不應以大寫字符開頭。 你的一些變量是正確的,有些則不是。 始終如一!!!

我嘗試使用渲染器為 jTable 的單元格着色,但它們是無用的,它們滯后於表格並使其無法看到。

僅僅因為你不理解這個概念並不會使它變得毫無用處。 問題在於您的代碼,而不是渲染器的概念。

您發布的代碼毫無意義。 您無法設置單個單元格的顏色。 顏色是在單元格是渲染器時確定的,這就是您需要使用渲染器的原因。

它完全給桌子上色

是的,一旦您設置了渲染器的背景,以后所有單元格都將使用該顏色。 您需要在渲染每個單元格之前將顏色重置為其默認值

背景必須是紅色的,以防它是一個數字並且它高於 24,

然后做一個積極的檢查,忘記所有那些消極的檢查。

使用上述所有建議,您可能會擁有類似以下內容的渲染器:

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

在查看討論線程后,我來到了這個解決方案......

...不要嘗試獲取渲染的Component本身 - 告訴渲染器以您希望的方式繪制所需的組件...

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

自衛隊

在您的第一個代碼示例中,您有一系列檢查以將背景顏色設置為紅色。 在所有其他情況下,您應該將背景設置為默認背景顏色。 您可以通過table.getBackground();查找此背景顏色table.getBackground(); .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM