Reputation: 1
I'm new to Java Swing and I'm writting a program, into which user types few X's and Y's and then the program shows on x/y grid those points. I drew the grid with Graphics2D, but now the problem is with drawing those points. I'm adding every X and Y to separate ArrayList and then after clicking the button 'Draw' it should draw all of them, but I don't really know how. I've searched few topics and tutorials, but still can't get into it.
Here is the code of my DrawPoints class
import javax.swing.*;
import java.awt.*;
public class DrawPoints extends JPanel {
private int x;
private int y;
public DrawPoints(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x*20, y*20, 5, 5); //20 is the difference between every point on my grid
}
}
And here is part of my actionListener function
if (event.getActionCommand().equals("Draw")) { //Button is called 'Draw'
for (int i = 0; i < dataX.size(); i++) { //dataX is an arrayList with all X's
DrawPoints drawPoints = new DrawPoints(dataX.get(i), dataY.get(i)); //dataY is an arrayList with all Y's
points.add(drawPoints); //points is a JPanel added in the main frame
}
}
Upvotes: 0
Views: 324
Reputation: 324088
I'm adding every X and Y to separate ArrayList and then after clicking the button 'Draw' it should draw all of them,
That approach is wrong.
All the data needed to paint the points should be part of the DrawPoints
class:
addPoint(...)
in the DrawPoints
class. This method would simply take the point and add it to the ArrayList and then invoke repaint()
to make sure the point is painted on the panel.paintComponent(…)
method would then be changed to iterate through all the pointes in the ArrayList and then paint each point.
I'm writting a program, into which user types few X's and Y's
So as the user type the x/y points you would invoke the addPoint(…)
method of your DrawPoints
class.
You will also need to override the getPreferredSize()
method of your DrawPaoints
class to give your panel a size so a layout manager can be used.
Check out the Draw On Component
example found in Custom Painting Approaches for a working example that uses this approach. The code presented there is more complicated then you will need because it allows the user to use the mouse to create the rectangles to be painted.
Upvotes: 1