2015-09-03 33 views
0

在任何人告诉我去谷歌搜索它之前,我已经完成了,到目前为止,每一种方法都没有奏效。jTable单元格背景颜色

我试着使用渲染器为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); 

         } 
        } 
       }  
      } 

我还没有把它变成一个rendererclass因为它落后,我已经把它的两倍cicle,具体而言,进入第二cicle。我想它的颜色,越过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     
} 
+0

考虑提供一个[可运行示例](https://stackoverflow.com/help/mcve),这说明你的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将导致更少的混淆和更好的响应 – MadProgrammer

+2

使用和扩展DefaultTableCellRenderer不会滞后。它必须正确使用:单元格渲染器应该返回单个单元重用的同一个组件,并且工作应该是最小的。也许一个TableModel可以做更多的工作,比如拿着红色的布尔值。 –

+0

首先看看[Concepts:Editors and Renderers](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender)和[Using Custom Renderers](http:// docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer)。你提供的代码不可能工作,因为你得到的组件实际上并不附加任何东西,当渲染时,表只是使用渲染器将输出“橡皮戳”到桌面上,实际上并没有生命桌面上的组件(除编辑器外,当处于活动状态时) – MadProgrammer

回答

0

首先变量名不应该以大写字符开头。你的一些变量是正确的,其他变量是不正确的。始终如一!!!

我试着使用渲染器对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; 
    } 
} 
+0

我把jtable.setDefaultRenderer(Object.class,new ColorRenderer());进入它的工作构造函数,谢谢,但为什么它使用滞后表? – Malignus

2

OK,LO后在讨论主题中,我来解决这个问题...

...不要尝试获取渲染的组件本身 - 告诉渲染器以你想要的方式绘制你想要的组件...

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

SDF

1

在你的第一个代码示例,你有一整个一系列的检查,以结束与设置背景颜色为红色。在所有其他情况下,您应该将背景设置为默认背景颜色。您可以通过table.getBackground();查找此背景色。

+0

所有这些检查都需要,因为背景必须是红色的,以防万一它是一个数字,它高于24,但在我的表中可以出现一个P,一个F,一个空白空格,一个数字后跟/ P,当然还有一个空值,我试着放一些“elses”,但即使如此,整个桌子变成了白色 – Malignus

+0

@Malignus那么你的控制流程应该结束时将颜色设置为红色,或白色。也许有一个布尔值b默认为false,并且当您的颜色需要设置为红色时将其设置为true。最后做c.setBackground(b?red:table.getBackground()); –