java - 如何在JFrame上用java绘制1024交叉1024网格单元?

标签 java swing java-2d

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/

相关文章:

java - 如何刷新 JPanel?

java - 将文本与 Java Graphics 2d 对齐

JAVA - 图形不更新

Java 正则表达式不工作 - 为什么?

java - 在 Java 中使用 WEKA 分类器模型对实时文本进行分类

java - 为什么我的 Activity 无法启动?

java - 撤消 Document.Replace 后如何防止光标移动

Java:DefaultListModel 和数组

java - 程序应该显示整个图像只显示它的一部分

java - 如何告诉 Java 一个变量不可能为空?