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/