我曾嘗試添加一個 if-else 陳述句來更改文本的顏色。但是,它不能很好地作業。我希望只將低于 40 的標記更改為紅色,但我不知道為什么我的所有文字都變為紅色。我可以知道我犯了什么錯誤嗎?
在 if-else 陳述句中,我撰寫了代碼以在 mark 低于 40 時更改文本的顏色。但是,它將所有文本更改為紅色。
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);
}
}

uj5u.com熱心網友回復:
創建一個單元格渲染器,它采用條件和顏色來表示真偽。將此單元格渲染器分配給列。
TableColumn col = tb1.getColumnModel().getColumn(1);
col.setCellRenderer(new CellRenderer(v -> v < 40d, Color.RED, new Color(38, 120, 81), SwingConstants.CENTER));
單元格渲染器 編輯在建構式中添加了對齊引數
class CellRenderer extends DefaultTableCellRenderer {
DoublePredicate condition;
Color fgTrue;
Color fgFalse;
public CellRenderer(DoublePredicate condition, Color fgTrue, Color fgFalse, int alignment) {
super();
this.condition = condition;
this.fgTrue = fgTrue;
this.fgFalse = fgFalse;
setHorizontalAlignment(alignment);
}
@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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441216.html
