import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class Grid extends JComponent
{
public void paint(Graphics g){
super.paintComponent(g);
Graphics2D graphics = (Graphics2D) g;
int w = 1024*2;
int h = 1024*2;
for(int i=0; i<1024; i++)
{
graphics.drawLine(i, 0, i, 1024);
//graphics.setColor(Color.red);
}
for(int j=0; j<1024; j++)
{
graphics.drawLine(0, j, 1024, j);
}
}
}
我需要绘制1024个跨1024个单元格并为几个单元格上色。单元格应显示在JFrame上。用Java做到这一点的最好方法是什么?请发布一些代码...
最佳答案
您可以使用一些JTable功能:
class CellCoords{
public int x, y;
public CellCoords(x, y){
this.x = x; this.y = y;
}
}
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 1024; }
public int getRowCount() { return 1024;}
public Object getValueAt(int row, int col) { return new CellCoords(row, col); }
};
JTable table = new JTable(dataModel);
Swing Tutorials中的更多示例
public class ColorRenderer extends JLabel
implements TableCellRenderer {
...
public ColorRenderer(boolean isBordered) {
this.isBordered = isBordered;
setOpaque(true); //MUST do this for background to show up.
}
public Component getTableCellRendererComponent(
JTable table, Object color,
boolean isSelected, boolean hasFocus,
int row, int column) {
// Do things based on row and column to decide color
Color newColor = (Color)color;
setBackground(newColor);
return this;
}
}
通常,“如何使用表格”文档会有所帮助。
关于java - 如何在JFrame上的Java中绘制1024个交叉1024个网格单元?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10640953/