简体   繁体   中英

How to prevent shapes in a JFrame from disappearing after resizing the window

public void actionPerformed(ActionEvent e)
 {
     try 
    {
     //récupérer les coordonnées(x,y) du text area
     int x=Integer.parseInt(f.x.getText());
     int y=Integer.parseInt(f.y.getText());
     int puissance=Integer.parseInt(f.p.getText());

     f.APs.add(new AccessPoint (x,y,f.APs.size(),puissance));

     String ch="Point d'accés "+String.valueOf(f.APs.size())+" Center xc = "+String.valueOf(x)+" yc= "+String.valueOf(x);
     System.out.println(ch);
     f.t.add(ch);

        Graphics g ;
        g= f.getGraphics();
        paintComponent(g);
    }
     catch(Exception e1){System.out.println("Erreur");}
}

public void paintComponent(Graphics g)
{   
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    if(f.APs.size()!=0)
    {
    try { 

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        int currPoint =f.APs.size()-1;
        int puissance =f.APs.get(currPoint).p;
        Color C= new Color(128,puissance,puissance,puissance);
        Shape circle = new Ellipse2D.Float(f.APs.get(currPoint).x-(f.APs.get(currPoint).diametre/2), 
                                          f.APs.get(currPoint).y-(f.APs.get(currPoint).diametre/2),
                                          f.APs.get(currPoint).diametre,f.APs.get(currPoint).diametre);
        g2d.draw(circle);
        g2d.setPaint(C);
        g2d.fill(circle);

    }catch(Exception e2){System.out.println("Erreur");}}    
}
    g= f.getGraphics();
    paintComponent(g);
  1. Don't use getGraphics(). Any painting done using that approach will only be temporary (as you have noticed)
  2. Don't invoke paintComponent() directly. Swing will invoke the paintComponent(...) method as required and pass in the proper Graphics object.

The painting method should only ever do painting. It should not change the state of the component.

So if you want to dynamically add shapes to be painted you have two approaches:

  1. Keep an ArrayList of the shapes to be painted. Create a method like addShape(..) to update the ArrayLIst. Then your painting code will iterate through the ArrayList to paint each shape.

  2. Paint directlyl to a BufferedImage. Then paint the BufferedImage.

Working example of both approaches can be found in Custom Painting Approaches

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM