I have a program that draws Vehicle Objects (e.g. Car Shapes) onto a JFrame using a paint method. However whenever I click on the screen to draw the vehicles I have to refresh the window for them to be shown even with the repaint() method added.
The first picture shows where I clicked. Nothing happened.
After minimizing and opening the window.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JFrame;
/** Program specs: Draws shapes (Vehicles) that are contained within LinkedLists.
* When a shape is drawn over another shape it 'joins' its list. (not implemented yet, not my issue)
*/
/**
Creates JFrame
*/
public class FramePanel extends JFrame implements MouseListener
{
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 600;
Car car; // Car is a subclass of Vehicle. It only contains a draw method.
//Vehicle is an abstract class that only contains a draw method
LinkedList<LinkedList<Vehicle>> list = new LinkedList<LinkedList<Vehicle>>();
LinkedList<Vehicle> temp = new LinkedList <Vehicle>();
/**
Constructs the frame.
*/
public FramePanel()
{
addMouseListener(this);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
repaint();
}
@Override
public void mouseClicked(MouseEvent evt) {
car = new Car (evt.getX(), evt.getY());
temp.add(car); //Add Vehicle to LinkedList
list.add(temp); //Add LinkedList to Collection of LinkedLists
}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
public void paint(Graphics g) {
super.paintComponents(g) ;
Graphics2D g2 = (Graphics2D) g;
for (LinkedList<Vehicle> veh : list){ // list is collection of Linked Lists
Iterator<Vehicle> it = veh.iterator();
while (it.hasNext()){
it.next().draw(g2);
}
}
}
public static void main(String[] args)
{
JFrame frame = new FramePanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Viewer");
frame.setVisible(true);
}
}
NOTE: If I add a repaint() statement onto my paint(Graphic g) method the car will be draw but will flicker undesirably with/without the repaint() in the constructor. I do not want this.