最小化/重新打开窗口后重绘Java JFrame

时间:2014-03-29 19:48:55

标签: java jframe

我有一个程序使用paint方法将Vehicle Objects(例如Car Shapes)绘制到JFrame上。然而,每当我点击屏幕绘制车辆时,我必须刷新窗口,以便显示,即使添加了repaint()方法


第一张图片显示了我点击的位置。没啥事儿。

enter image description here

最小化并打开窗口后。

enter image description here

    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()会不合需要地闪烁。我不想要这个。

1 个答案:

答案 0 :(得分:4)

repaint()方法的最后一行添加对mouseClicked的调用已经解决了这个问题。

但是,还有其他几点:

  • 不要展开JFrame(尤其是,不要覆盖paint的{​​{1}}方法。相反,请使用JFrame进行痛苦,并覆盖其JPanel方法。
  • 不要让顶级类实现paintComponent接口
  • 不要将您的列表声明为MouseListener,而只能将LinkedListWhat does it mean to "program to an interface"?)声明为
  • 应在Event-Dispatch-Thread
  • 上创建GUI
  • 字段应为私有(如果可能,最终

所以一些清理:

List