Gilad Mitrani Gilad Mitrani - 4 years ago 123
Java Question

Paint Points from array to JPanel

I am trying to write a simple GUI application that allows the user to click on a panel,

in this situation, to paint a dot. than save those dots to a file. And the ability to load dots from file and display them.

I have successfully made all the functions and methods needed to save and load an
from file and have made sure that the points loaded contain the coordinates that are needed to be re-painted

My problem is that I am unable to create a method that paints all the dots from an array

My main class is a
which has two
s added to it:

  • MainPanel
    which holds some stuff

  • BlackPanel
    which is used to paint on.

My Class has an
- points as a class member.

All Point objects are made using

private void paintPoint(Graphics g, Point p) {
g.fillOval(p.x, p.y, 5, 5);
} // this one is used to create a single dot called by MouseClicked event - works

private void paintPoints(Graphics g, ArrayList<Point> points) {
for (Point point : points) {
g.fillOval(point.x, point.y, 5, 5);
} // this one is called by LoadPointsDialog() which in turn is called by a button action

private void loadPointsDialog() {
FileDialog fd = new FileDialog(this, "Open XML file", FileDialog.LOAD);
fd.setFilenameFilter((File dir, String name) -> name.endsWith(".xml"));
String folder = fd.getDirectory();
String fileName = fd.getFile();
ArrayList<Point> aux;
try { // irrelevent for this question. works.
aux =;
} catch (IOException e) {
System.err.println("Error! Failed reading from file");
ItemClear.doClick(); // clears points class member and calls BlackPanel.updateUI();
points.addAll(aux); // works 100% i checked to see if the points exist.
paintPoints(PanelBlack.getGraphics(), points);

private void ItemOpenActionPerformed(java.awt.event.ActionEvent evt) {

private void PanelBlackMouseClicked(java.awt.event.MouseEvent evt) {
Point p = evt.getPoint();
paintPoint(PanelBlack.getGraphics(), p);
savePoint(p); // points.add(p);

private void ItemClearActionPerformed(java.awt.event.ActionEvent evt) {

i am using NetBeans designer tool to create this JFrame.

EDIT: Solution by @Berger

I have created a new nested class :

public class PaintPanel extends JPanel {

public void paintComponent(Graphics g) {
for (Point point : points) {
g.fillOval(point.x, point.y, 5, 5);

and defined
to be an object of this class.

Then I called
after loading the new point array - works like magic.

Answer Source

You have to override the paintComponent(Graphics) method of PanelBlack.

getGraphics() is not reliable to do your paintings, paintComponent(Graphics) is where you are supposed to customize the paintings.

Painting in Swing

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download