Search code examples
javaeclipseswingjtableswingbuilder

Use DefaultTableModel to color specific cell of the JTable based on their specific value


How to color a particular cell data or cell using defaulttablemodel concept? The array consist of string values. So if we have "1" in last row the cell should turn red and if '0" then green. Is that possible? I am using eclipse IDE

If possible, what changes are beneficial for the code?

package mywork;

import java.awt.EventQueue;

import javax.swing.JFrame;

import javax.swing.JLabel;
import java.awt.Font;

import java.awt.Color;


import javax.swing.JPanel;
import javax.swing.JTextField;

import javax.swing.JButton;

import java.util.ArrayList;

import javax.swing.SwingConstants;

import javax.swing.table.DefaultTableModel;

import javax.swing.JTable;
import javax.swing.JScrollPane;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;

import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Rectangle;
import java.awt.Dimension;


public class lru extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 8974257654196993862L;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    lru window = new lru();
                    window.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     
     */
    
    public lru() {

        setMinimumSize(new Dimension(1080, 1080));
        
        JPanel panel = new JPanel();
        panel.setBackground(new Color(19, 40, 60));
        panel.setAlignmentY(0.0f);
        panel.setAlignmentX(0.0f);
        
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(lru.class.getResource("/images/simulator.png")));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        
        JLabel label_1 = new JLabel();
        label_1.setIcon(new ImageIcon(lru.class.getResource("/images/algorithm.png")));
        label_1.setHorizontalAlignment(SwingConstants.CENTER);
        
        JLabel label_2 = new JLabel();
        label_2.setIcon(new ImageIcon(lru.class.getResource("/images/home.png")));
        label_2.setHorizontalAlignment(SwingConstants.CENTER);
        
        JPanel panel_1 = new JPanel();
        panel_1.setBorder(null);
        
        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setFont(new Font("Century Schoolbook", Font.BOLD, 20));
        scrollPane_1.setBounds(new Rectangle(500, 400, 150, 200));
        scrollPane_1.setBorder(null);
        
        JLabel lblNewLabel_7 = new JLabel("\"1\" \r\n Page fault");
        lblNewLabel_7.setFocusable(false);
        lblNewLabel_7.setFocusTraversalKeysEnabled(false);
        lblNewLabel_7.setInheritsPopupMenu(false);
        lblNewLabel_7.setRequestFocusEnabled(false);
        lblNewLabel_7.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel_7.setFont(new Font("Century Schoolbook", Font.BOLD, 20));
        
        JLabel lblPageHit = new JLabel("\"0\" \r\n Page Hit");
        lblPageHit.setVerifyInputWhenFocusTarget(false);
        lblPageHit.setFocusable(false);
        lblPageHit.setFocusTraversalKeysEnabled(false);
        lblPageHit.setInheritsPopupMenu(false);
        lblPageHit.setHorizontalAlignment(SwingConstants.CENTER);
        lblPageHit.setFont(new Font("Century Schoolbook", Font.BOLD, 20));
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addGroup(groupLayout.createSequentialGroup()
                                    .addPreferredGap(ComponentPlacement.RELATED)
                                    .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 932, GroupLayout.PREFERRED_SIZE))
                                .addGroup(groupLayout.createSequentialGroup()
                                    .addGap(55)
                                    .addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 854, GroupLayout.PREFERRED_SIZE)))
                            .addContainerGap(32, Short.MAX_VALUE))
                        .addGroup(groupLayout.createSequentialGroup()
                            .addGap(111)
                            .addComponent(lblNewLabel_7, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(ComponentPlacement.RELATED, 389, Short.MAX_VALUE)
                            .addComponent(lblPageHit, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
                            .addGap(160))))
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout.createSequentialGroup()
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                        .addComponent(panel, GroupLayout.PREFERRED_SIZE, 845, GroupLayout.PREFERRED_SIZE)
                        .addGroup(groupLayout.createSequentialGroup()
                            .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 423, GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(ComponentPlacement.UNRELATED)
                            .addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 256, GroupLayout.PREFERRED_SIZE)
                            .addGap(18)
                            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                .addComponent(lblPageHit, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblNewLabel_7))))
                    .addContainerGap(198, Short.MAX_VALUE))
        );
        
        JLabel lblNewLabel = new JLabel("Least Recently Used");
        lblNewLabel.setFont(new Font("Century Schoolbook", Font.BOLD, 36));
        
        JLabel lblNewLabel_1 = new JLabel("No.of Frame:");
        lblNewLabel_1.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        JLabel lblNewLabel_2 = new JLabel("Input Page No.:");
        lblNewLabel_2.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        JLabel lblNewLabel_3 = new JLabel("Total Page Fault:");
        lblNewLabel_3.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        textField = new JTextField();
        textField.setFont(new Font("Century Schoolbook", Font.PLAIN, 20));
        textField.setColumns(10);
        
        textField_1 = new JTextField();
        textField_1.setFont(new Font("Century Schoolbook", Font.PLAIN, 20));
        textField_1.setColumns(10);
        
        JLabel lblNewLabel_4 = new JLabel("0");
        lblNewLabel_4.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        
        
        JLabel lblNewLabel_5 = new JLabel("Hit Rate:");
        lblNewLabel_5.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        JLabel lblNewLabel_6 = new JLabel("0%");
        lblNewLabel_6.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        
        JButton btnNewButton = new JButton("Implement");
        btnNewButton.addMouseListener(new MouseAdapter() {
            

            @Override
            public void mouseClicked(MouseEvent e) {
                capacity = Integer.parseInt(textField.getText());
                n = capacity + 1;
                //System.out.println(capacity);
                String getInput = textField_1.getText();
                int i=0,ct=0;
                float hr1;
                String hr ="";
                String tempstr="";
                ArrayList<Integer> arrl = new ArrayList<>();
                while(i<getInput.length()) {
                    if(!Character.isWhitespace(getInput.charAt(i))) {
                        tempstr+=getInput.charAt(i);
                    }   
                    else {
                        arrl.add(ct, Integer.parseInt(tempstr));
                        ct++;
                        tempstr = "";
                    }
                    if(i == getInput.length()-1)
                        arrl.add(ct, Integer.parseInt(tempstr));
                    i++;
                }
                //System.out.println(arrl);
                len = arrl.size();
                System.out.println(len);
                array = new int[len];
                for(i=0;i<len;i++) {
                    array[i]=arrl.get(i);
                }
                int[][] process = new int[n][len];
                ArrayList<Integer> temp= new ArrayList<>();
                ct = 0;
                
                for(i=0;i<len;i++) {
                    if(!temp.contains(array[i])) {
                        if(temp.size()== capacity ) {
                            temp.remove(0);
                            temp.add(capacity-1, array[i]);
                        }
                        else {
                            temp.add(ct, array[i]);
                        }
                        page_fault = true;
                        ct++;
                    }
                    else {
                        temp.remove((Object)array[i]);
                        temp.add(temp.size(), array[i]);
                        page_fault = false;
                    }
                    for(int j=0;j<n;j++) {
                        if(temp.size()<n) {
                            if(j==temp.size())
                                break;
                        }
                        process[j][i] = temp.get(j);
                        if(page_fault == true)
                        {
                            process[n-1][i] = 1;
                        }
                        else
                        {
                            process[n-1][i] = 0;
                        }
                    }
                }
                 hr1 = (float)ct/len;
                 hr1 = 1 - hr1;
                 System.out.println(ct);
                 System.out.println(hr1);
                 hr1 = hr1*100;
                 hr = Float.toString(hr1);
                 hr = hr+"%";
                lblNewLabel_4.setText(String.valueOf(ct));
                lblNewLabel_6.setText(hr);
                String[][] processstr = new String[n][len];
                String[] arraystr = new String[len];
                for(int j=0;j<n;j++) {
                    for(i=0;i<len;i++) {
                        processstr[j][i] = String.valueOf(process[j][i]);
                    }
                }
                for(i=0;i<len;i++) {
                    arraystr[i] = String.valueOf(array[i]);
                }
               for(i=0;i<len;i++)
               {
                   if(processstr[n-1][len] != "0") {
                       
                   }
               }
                
            
                
                DefaultTableModel dtm = new DefaultTableModel(processstr, arraystr);
                 table_1 = new JTable(dtm);
                
                
                table_1.setFont(new Font("Century Schoolbook", Font.BOLD, 20));
               
                int width = 50*len;
                int height = 50*capacity;
                table_1.setRowHeight(50-(25/capacity));
                
                scrollPane_1.setBounds(500, 400, width, height);
                //table_1.setBounds(50, 397, width, height);
                scrollPane_1.setViewportView(table_1);
                
            }
            
        });
        btnNewButton.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        JButton btnNewButton_1 = new JButton("Reset");
        btnNewButton_1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                textField.setText("0");
                textField_1.setText("0");
                lblNewLabel_4.setText("0");
                lblNewLabel_6.setText("0%");
                table_1.setVisible(false);
                table_1.setTableHeader(null);
                
            }
        });
        btnNewButton_1.setFont(new Font("Century Schoolbook", Font.BOLD, 30));
        
        GroupLayout gl_panel_1 = new GroupLayout(panel_1);
        gl_panel_1.setHorizontalGroup(
            gl_panel_1.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addGap(346)
                    .addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
                    .addGap(204))
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addGap(281)
                    .addComponent(lblNewLabel_1, GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(textField, GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                    .addGap(280))
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addGap(242)
                    .addComponent(lblNewLabel_2, GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(textField_1, GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
                    .addGap(82))
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
                        .addGroup(gl_panel_1.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(lblNewLabel_3)
                            .addGap(43))
                        .addGroup(gl_panel_1.createSequentialGroup()
                            .addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
                                .addGroup(gl_panel_1.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 251, GroupLayout.PREFERRED_SIZE))
                                .addGroup(gl_panel_1.createSequentialGroup()
                                    .addGap(217)
                                    .addComponent(lblNewLabel_5, GroupLayout.PREFERRED_SIZE, 168, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(lblNewLabel_6, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)))
                            .addPreferredGap(ComponentPlacement.RELATED)))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel_1.createSequentialGroup()
                            .addComponent(lblNewLabel_4, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGap(402))
                        .addGroup(gl_panel_1.createSequentialGroup()
                            .addGap(11)
                            .addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())))
        );
        gl_panel_1.setVerticalGroup(
            gl_panel_1.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_1.createSequentialGroup()
                    .addGap(33)
                    .addComponent(lblNewLabel)
                    .addGap(51)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
                        .addComponent(lblNewLabel_1)
                        .addComponent(textField, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE))
                    .addGap(8)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel_2)
                        .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnNewButton_1, GroupLayout.PREFERRED_SIZE, 54, GroupLayout.PREFERRED_SIZE))
                    .addGap(18)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel_3)
                        .addComponent(lblNewLabel_4))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                        .addComponent(lblNewLabel_5)
                        .addComponent(lblNewLabel_6))
                    .addGap(22))
        );
        panel_1.setLayout(gl_panel_1);
        GroupLayout groupLayout_1 = new GroupLayout(panel);
        groupLayout_1.setHorizontalGroup(
            groupLayout_1.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout_1.createSequentialGroup()
                    .addGap(10)
                    .addGroup(groupLayout_1.createParallelGroup(Alignment.LEADING)
                        .addComponent(label_2, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
                        .addComponent(label_1, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
                        .addComponent(label, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)))
        );
        groupLayout_1.setVerticalGroup(
            groupLayout_1.createParallelGroup(Alignment.LEADING)
                .addGroup(groupLayout_1.createSequentialGroup()
                    .addGap(106)
                    .addComponent(label_2, GroupLayout.PREFERRED_SIZE, 61, GroupLayout.PREFERRED_SIZE)
                    .addGap(34)
                    .addComponent(label_1, GroupLayout.PREFERRED_SIZE, 73, GroupLayout.PREFERRED_SIZE)
                    .addGap(36)
                    .addComponent(label, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE))
        );
        panel.setLayout(groupLayout_1);
        getContentPane().setLayout(groupLayout);
        
    }


    /**
     * Initialize the contents of the frame.
     */
    int capacity;
    int len=0;
    int n=0;
    int[] array;
    boolean page_fault = false;
    int[][] process;
    private JTextField textField;
    private JTextField textField_1;
    private JTable table_1;
}

Solution

  • To color specific cells in a JTable according to their value, you could override prepareRender() of JTable.

    Sample:

    public static void main(String[] args) {
        JFrame frame = new JFrame();
    
        String[] header = { "Content1", "Content2", "Content3" };
        Object[][] data = { { 1, 0, 1 }, { 0, 0, 1 } };
        JTable table = new JTable(data, header) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
                Component comp = super.prepareRenderer(renderer, row, col);
                int cellValue = (int) getModel().getValueAt(row, col); // get the value from the cell
                switch (cellValue) { // color the cell accordingly
                case 1:
                    comp.setBackground(Color.red);
                    break;
                case 0:
                    comp.setBackground(Color.green);
                    break;
                }
                return comp;
            }
        };
    
        frame.add(table);
        frame.pack();
        frame.setVisible(true);
    }
    

    Result:

    enter image description here