在Java中为网格创建绘制矩形(用黑色填充)function

我在程序中创建了一个网格。 下面是用于创建网格的代码。

import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; class Grid extends JComponent { public void paint(Graphics g) { g.drawRect (10, 10, 800, 500); for (int i = 10; i <= 800; i+= 10) g.drawLine (i, 10, i, 510); for (int i = 10; i <= 500; i+= 10) g.drawLine (10, i, 810, i); } } public class CoreControl { public static void main(String[] a) { JFrame window = new JFrame(); window.setSize(840,560); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().add(new Grid()); window.setVisible(true); } } 

我想要做的是创建一个函数,它将根据我给它的坐标绘制一个矩形(填充黑色)。 基本上我想用黑色填充网格的某些单元格,我的想法是在单元格坐标上绘制黑色填充的矩形。 我该如何使用此function?

我尝试创建另一个名为drawRectangle的类,并在main函数中调用它,如window.getContentPane()。add(new drawRectangle()); 但是没有用(只有drawRectangle显示而不是网格)。

我还希望能够重复使用此function来继续创建矩形。

我该如何创建此function?

另外,如果您知道我应该构建这个程序的更好方法,请告诉我(我是Java的新手,所以我愿意接受任何建议)。

  1. 不要使用paint ,使用paintComponent并且不要忘记调用super.paintComponent
  2. JComponent可能不是最佳选择, JPanel可能是更好的选择
  3. Graphics#fillRect(int, int, int, int)什么问题?

您可以查看执行自定义 绘图和2D图形以获取更多详细信息。

我建议不要试图让第二个组件进行填充。 只需在网格类中提供一个方法,该方法提供单元格的x / y位置(以网格术语)并填充paintComponent方法中的单元格

更新了示例

在此处输入图像描述

 import java.awt.Color; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class CoreControl { public static class Grid extends JPanel { private List fillCells; public Grid() { fillCells = new ArrayList<>(25); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Point fillCell : fillCells) { int cellX = 10 + (fillCell.x * 10); int cellY = 10 + (fillCell.y * 10); g.setColor(Color.RED); g.fillRect(cellX, cellY, 10, 10); } g.setColor(Color.BLACK); g.drawRect(10, 10, 800, 500); for (int i = 10; i <= 800; i += 10) { g.drawLine(i, 10, i, 510); } for (int i = 10; i <= 500; i += 10) { g.drawLine(10, i, 810, i); } } public void fillCell(int x, int y) { fillCells.add(new Point(x, y)); repaint(); } } public static void main(String[] a) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } Grid grid = new Grid(); JFrame window = new JFrame(); window.setSize(840, 560); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.add(grid); window.setVisible(true); grid.fillCell(0, 0); grid.fillCell(79, 0); grid.fillCell(0, 49); grid.fillCell(79, 49); grid.fillCell(39, 24); } }); } }