I\'m making a pixel art maker in java. I\'ve made a grid that looks like this:
public void paint(Graphics g) {
int rows = 20;
int cols = 20;
int width = g
A painting method should paint only, not set properties of the class. For example you should set the rows/columns as properties and then have a "gridSize" property as well.
Then the preferred size of the panel would be:
@Override
public Dimension getPreferredSize()
{
return new Dimension(columns * gridSize, rows * gridSize);
}
This is important because you don't want the rowHeight and columnWidth to dynamically change if the size of the frame is resized.
Now that you have a fixed size grid you can add a MouseListener to the panel and use an ArrayList to track cells that should be filled. In a simple implementation you can use an ArrayList of Point objects. The Point would represent the cell you clicked on.
So for example if the point from your MouseEvent is (33, 56) and your gridSize is 10 then the Point object would be:
Point cell = new Point(event.getX() / gridSize, event.getY() / gridSize);
add this "cell" object to your ArrayList.
Then in the paintComponent() method you iterate through the Array to get each point object and you now calculate the x/y/width/height values to be used in the fillRect(...) painting method:
int x = cell.x * gridSize;
int y = cell.y * gridSize;
graphics.fillRect(x, y, gridSize, gridSize);
First, you should be using paintComponent()
and drawing in something that extends Component
like a JPanel
So your first two statements should be:
public void paintComponent(Graphics g) {
super.paintComponent(g);
As far as clicking to fill a particular grid area, your design does not lend itself to that. What you should do is create class
that uses an instance of Rectangle
to house the grid location
and size
.
Your class should also have a color
attribute (field).
Then put those in an array and have the paint routine paint the array. When the mouse is clicked you on the window, you can retrieve the coordinates and do some math to calculate the index of the array that matches the grid location.
Another option is to use a grid of JPanels
and have them listen for mouse events and then change their color.
This requires them being laid out using a Layout Manager
.
None of this is hard if you have done it before, but they both have their specific difficulties. I recommend you check the Java Tutorials on painting
,event handling
, and layout mangers
. And practice on some simple examples.