I had tried to add an if-else statement to change the color of the text. However, it does not work well. I hope to change only marks below 40 to become red, but I don't know why all my text changed to red. May I know what is the mistake I make?
In the if-else statement, I write the code to change the color of the text when mark is below 40. However, it changes all the text to red.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class testing{
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mark();
}
});
}
public static void mark() {
String[] columns = new String[] {"Name", "Marks(%)"};
Object[][] data= new Object[][] {
{"Aby", "100"},
{"Amy", "30"}
};
JFrame frame = new JFrame("Student Marks List");
frame.setVisible(true);
frame.setSize(600, 500);
frame.setLayout(new BorderLayout());
Panel details = new Panel(null);
details.setBounds(0,50, 1000, 125);
Panel contents = new Panel(null);
contents.setBounds(0,50, 1000, 600);
frame.add(details, BorderLayout.NORTH);
frame.add(contents, BorderLayout.CENTER);
JTable tb1;
tb1 = new JTable(data, columns);
JScrollPane sp = new JScrollPane(tb1);
tb1.getTableHeader().setOpaque(false);
tb1.getTableHeader().setFont(new Font("Barlow Condensed ExtraBold", Font.BOLD, 20));
tb1.getTableHeader().setPreferredSize(new Dimension(100, 30));
tb1.setFont(new Font("Barlow Condensed", Font.BOLD, 20));
tb1.setRowHeight(30);
for (int i = 0; i < tb1.getRowCount(); i ) {
Object x = tb1.getValueAt(i, 1);
String y = x.toString();
double z = Double.parseDouble(y);
if (z < 40) {
tb1.setForeground(Color.RED);
}
else {
tb1.setForeground(new Color(38, 120, 81));
}
}
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
tb1.setBounds(25,10,200,375);
sp.setBounds(25,10,200,375);
contents.add(sp);
}
}
CodePudding user response:
Create a cell renderer that takes a condition and colors for true and false. Assign this cell renderer to the column.
TableColumn col = tb1.getColumnModel().getColumn(1);
col.setCellRenderer(new CellRenderer(v -> v < 40d, Color.RED, new Color(38, 120, 81)));
The cell renderer
class CellRenderer extends DefaultTableCellRenderer {
DoublePredicate condition;
Color fgFalse;
Color fgTrue;
public CellRenderer(DoublePredicate condition, Color fgFalse, Color fgTrue) {
super();
this.condition = condition;
this.fgFalse = fgFalse;
this.fgTrue = fgTrue;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
cell.setForeground(condition.test((Double)value) ? fgTrue : fgFalse);
return cell;
}
}