我有一个程序使用paint方法将Vehicle Objects(例如Car Shapes)绘制到JFrame上。然而,每当我点击屏幕绘制车辆时,我必须刷新窗口,以便显示,即使添加了repaint()方法。
第一张图片显示了我点击的位置。没啥事儿。
最小化并打开窗口后。
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);
}
}
注意:如果我在我的paint(Graphic g)方法上添加一个repaint()语句,那么汽车将被绘制,但是在构造函数中使用/不使用repaint()会不合需要地闪烁。我不想要这个。
答案 0 :(得分:4)
在repaint()
方法的最后一行添加对mouseClicked
的调用已经解决了这个问题。
但是,还有其他几点:
JFrame
(尤其是,不要覆盖paint
的{{1}}方法。相反,请使用JFrame
进行痛苦,并覆盖其JPanel
方法。paintComponent
接口MouseListener
,而只能将LinkedList
(What does it mean to "program to an interface"?)声明为所以一些清理:
List