如何在调整窗口大小后防止JFrame中的形状消失

问题描述 投票:1回答:1
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");}}    
}
java swing graphics jframe jpanel
1个回答
1
投票
    g= f.getGraphics();
    paintComponent(g);
  1. 不要使用getGraphics()。使用该方法完成的任何绘画都只是暂时的(您已经注意到)
  2. 不要直接调用paintComponent()。 Swing将根据需要调用paintComponent(...)方法,并传递适当的Graphics对象。

绘画方法只应进行绘画。它不应更改组件的状态。

因此,如果要动态添加要绘制的形状,则有两种方法:

  1. 保留要绘制的形状的ArrayList。创建类似addShape(..)的方法来更新ArrayLIst。然后,您的绘画代码将遍历ArrayList以绘制每个形状。

  2. 直接绘制到BufferedImage。然后绘制BufferedImage。

这两种方法的工作示例都可以在Custom Painting Approaches中找到

© www.soinside.com 2019 - 2024. All rights reserved.