I’m making a drawing board, and I have a few questions.
- Whenever I try to draw on it, it doesn’t automatically update. Ad I usually have to resize the screen for it to update.
- How can I do something like a mouseDragged function, in which i can continually get the x and y coords?
Here is the code:
import java.awt.geom.*;
class griddedInput extends JComponent implements MouseListener
{
int SIZE = 10;
int scSize = 300;
int sSize = scSize/SIZE;
boolean [][] grid = new boolean[sSize][sSize];
public griddedInput(boolean grid[][])
{
grid=grid;
setPreferredSize(new Dimension(scSize,scSize));
addMouseListener(this);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
int x, y;
for(y = 0; y < sSize; y ++) {
for(x = 0; x < sSize; x ++) {
if(grid[y][x])
g2.setColor(Color.BLACK);
else
g2.setColor(Color.WHITE);
g2.fillRect((x * SIZE), (y * SIZE), sSize, sSize);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
int squareX = (int)e.getX() / SIZE;
int squareY = (int)e.getY() / SIZE;
grid[squareY][squareX] = !grid[squareY][squareX];
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
You’ll want to call
repaint()on the drawing component any time you want to suggest to the JVM that it be painted — most likely in your MouseListener method(s).e.g.,
To speed up repainting, you can also call the overload method that allows you to repaint a select rectangle of your GUI, but I’ll bet that you don’t need to do that for this GUI.
You’ll also want to be a little less “creative” with your code indentation if you want others to better be able to understand it and help you.
Edit
Regarding:
Also add a MouseMotionListener. It can be the same class, and in fact usually I use an anonymous inner class for this, one that extends MouseAdapter, and one whose single instance I use for both MouseListener and MouseMotionListener. I have examples of using this in several posts in this very forum.