更新时间:2023-12-04 16:04:11
仅在移动表格或单击表格后才显示该值的原因是,这样做会强制重新绘制.
您可以通过在done[5] = 10;
The reason why the value shows only after you move the table or click on it, is that by doing so you force a repaint.
You can verify it by invoking frame.repaint()
after done[5] = 10;
以下是一个文件的MRE(将整个代码复制粘贴到FinalClass.java
中并运行):
The following is a one-file MRE (copy paste the entire code into FinalClass.java
and run):
import java.awt.Color;
import java.awt.Component;
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class FinalClass {
private final JFrame frame = new JFrame();
private final int[] done = new int[90]; //better avoid static
private final Integer[][] slip = new Integer[9][5];
private final String colHeader[] = {"1","2","3","4","5"};
private JTable table;
FinalClass() {
Arrays.fill(done, -1);
int cnt = 0;
for(int x = 0; x<9; x++ ) {
for(int y = 0; y <5; y++) {
slip[x][y] = cnt++;
}
}
DefaultTableModel tableModel = new DefaultTableModel(slip, colHeader) {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
table = new JTable(slip, colHeader);
table.setDefaultRenderer(Object.class, new MyRenderer());
table.setModel(tableModel);
frame.add(table);
frame.pack();
frame.setVisible(true);
}
private void refresh(){
frame.repaint();
}
void done(int index, int value){
done[index] = value;
refresh();
}
public static void main(String[] args) {
FinalClass f = new FinalClass();
try {
Thread.sleep(3000);
f.done(5, 10);
} catch(Exception e) { e.printStackTrace(); }
}
//follow java naming conventions
class MyRenderer extends JLabel implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyRenderer()
{
super.setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setHorizontalAlignment(SwingConstants.CENTER);
setText(value.toString());
Color myColor = new Color(255, 253, 117);
setBackground(myColor);
if((int)value == -1)
{
value = null;
setText("");
return this;
}
for(int i = 0; i < 90; i++) {
if((int)value == done[i]) //this value changes during the program.
{
setBackground(Color.cyan);
}
}
return this;
}
}
}
2.从多个线程修改done
需要同步.
3.建议遵循 Java命名约定
2.Modifying done
from more than one thread needs to be synchronized.
3.It is recommended to follow Java Naming Conventions