如果使用java满足某些条件,如何将颜色设置为某一行?

时间:2012-03-16 09:50:13

标签: java swing netbeans jtable

我有一个jtable。 (tablesummary)。其中一个专栏是EXPIRY。我想突出显示当前日期已经过期的客户的行..

我已经得到了逻辑,但我不能让行变成红色或任何其他颜色。 这是我的代码:

         int count = (tableSummary.getRowCount());
         NumberFormat formatter = new DecimalFormat("###,###");          
         String no = formatter.format(count);
         txtNo.setText(no);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");     
            Calendar cal  = Calendar.getInstance();           
            String expDateString = sdf.format(cal.getTime()).toString();

            for(int i=0; i<=tableSummary.getRowCount()-1; i++){
                String nnn= tableSummary.getModel().getValueAt(i, 6).toString();   
                System.out.println(nnn);
                int res = nnn.compareTo(expDateString); 
                    if(res>=0){
                        System.out.println("if ni " + (res>=0));
                    }
                    else{ 
                        System.out.println("else ni" + (res>=0));
                        rowrenderer.setBackground(Color.RED);


                    }                        
            }

任何人都可以帮我这个吗?因为它是我界面的主要亮点之一。 提前致谢 !! :)

3 个答案:

答案 0 :(得分:8)

...在前面的主题和答案中描述,仅为示例

enter image description here

来自代码

import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.*;

public class TablePrepareRenderer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;
    private Date maturityDate = new Date();
    private Date todayDate = new Date();
    private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    private Date tableDate = new Date();
    private String strDate = "";
    private Date modifDate = new Date();
    private Calendar cal;

    public TablePrepareRenderer() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Date"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), new Date()},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), new Date()},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), new Date()},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), new Date()}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                Component c = super.prepareRenderer(renderer, row, column);
                /*int firstRow = 0;
                int lastRow = table.getRowCount() - 1;
                if (row == lastRow) {
                ((JComponent) c).setBackground(Color.red);
                } else if (row == firstRow) {
                ((JComponent) c).setBackground(Color.blue);
                } else {
                ((JComponent) c).setBackground(table.getBackground());
                }*/
                if (!isRowSelected(row)) {
                    if (table.getColumnCount() >= 0) {
                        String type = (String) getModel().getValueAt(row, 0);
                        c.setBackground("Buy".equals(type) ? Color.YELLOW : Color.GREEN);
//
                        maturityDate = new Date();
                        todayDate = new Date();
                        strDate = sdf.format(todayDate);
                        try {
                            todayDate = sdf.parse(strDate);
                        } catch (ParseException ex) {
                            Logger.getLogger(TablePrepareRenderer.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        tableDate = (Date) table.getValueAt(row, 4);
                        strDate = sdf.format(tableDate);
                        if (strDate != null) {
                            if (!strDate.isEmpty()) {
                                try {
                                    maturityDate = sdf.parse(strDate);
                                } catch (ParseException ex) {
                                    Logger.getLogger(TablePrepareRenderer.class.getName()).log(Level.SEVERE, null, ex);
                                }
                                if (maturityDate != null) {
                                    int mmDiffDealToValue = (maturityDate).compareTo(todayDate);
                                    if (((mmDiffDealToValue < 0))) {
                                        c.setBackground(Color.orange);
                                        c.setFont(new Font("Serif", Font.BOLD, 12));
                                    }
                                }
                            }
                        }
//
                    }
                }
                if (isRowSelected(row) && isColumnSelected(column)) {
                    ((JComponent) c).setBorder(new LineBorder(Color.red));
                }
                return c;
            }
        };
        modifyDateInTable();
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    private void modifyDateInTable() {
        Calendar c = Calendar.getInstance();
        c.setTime(modifDate);
        c.add(Calendar.DATE, - 1);
        modifDate = c.getTime();
        table.setValueAt(modifDate, 0, 4);
        c.setTime(modifDate);
        c.add(Calendar.DATE, +5);
        modifDate = c.getTime();
        table.setValueAt(modifDate, 1, 4);
        c.setTime(modifDate);
        c.add(Calendar.DATE, +1);
        modifDate = c.getTime();
        table.setValueAt(modifDate, 1, 4);
        c.setTime(modifDate);
        c.add(Calendar.DATE, - 16);
        modifDate = c.getTime();
        table.setValueAt(modifDate, 3, 4);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TablePrepareRenderer frame = new TablePrepareRenderer();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

答案 1 :(得分:4)

在以下链接中,您可以找到您要执行的操作的示例:http://www.roseindia.net/java/example/java/swing/SadingRows.shtml

您必须覆盖prepareRenderer()上的JTable,并在返回的Component上添加backgroundColor。

PS:为了将来参考,如果你要包含更多代码会更容易。您rowrenderer =)

的定义

修改

使用以下代码(而不是正常的JTable table = new JTable(model)声明(如果您想要的不是交替颜色,请更改prepareRenderer方法中的逻辑):

JTable table = new JTable(model) {
    public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
        // get the current row
        Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
        // even index, not selected
        if (Index_row % 2 == 0 && !isCellSelected(Index_row, Index_col)) {
            comp.setBackground(Color.lightGray);
        } else {
            comp.setBackground(Color.white);
        }
        return comp;
    }
};

答案 2 :(得分:0)

enter image description here

public class TablePrepareRenderer extends JFrame {

    private JTable table;

    public TablePrepareRenderer() {
        Object[] columnNames = { "Type", "Company", "Name", "Salery", "Designation" };
        Object[][] data =
        { { "Probation", "Digital Research Lab", "Kamran Ali", "500,000", "Java Developer" }, { "Permenent", "Netsole",
                                                                                                "Farhan Khan",
                                                                                                "80,000",
                                                                                                "System Administaror" },
          { "Contract", "System Limited", "Danyal", "100,000", "Network Administrator" },
          { "Probation", "TeraData", "Ali Raza", "45,000", "IT Officer" },
          { "Contract", "MicroSoft", "Sikandar Hayat", "450,000", "Team Lead" },
          { "Permenent", "MicroSoft", "Adnan", "30,000", "Driver" }, };
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {


            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table = new JTable(model) {
                @Override
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
                    Component c = super.prepareRenderer(renderer, row, column);

                    if (!isRowSelected(row)) {
                        if (table.getColumnCount() >= 0) {
                            String type = (String)getModel().getValueAt(row, 0);
                            if (type.equalsIgnoreCase("Probation")) {
                                c.setBackground(new Color(198, 190, 255));

                            }
                            if (type.equalsIgnoreCase("Permenent")) {
                                c.setBackground(new Color(14, 255, 190));

                            }
                            if (type.equalsIgnoreCase("Contract")) {
                                c.setBackground(Color.green);

                            }

                        }
                    }
                    if (isRowSelected(row) && isColumnSelected(column)) {
                        ((JComponent)c).setBorder(new LineBorder(Color.red));
                    }
                    return c;
                }
            };

        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TablePrepareRenderer frame = new TablePrepareRenderer();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setSize(800, 500);
                frame.setVisible(true);


            }
        });
    }
}