简体   繁体   中英

Clear graphics from JPanel with ActionListener

My question is, how do I clear the graphics using my action listener and create a new set of graphics, by running through OtherPanel again?

public class MainFrame extends JFrame
  {

   private OtherPanel panel;

       public MainFrame()
   {

        panel = new OtherPanel();
       }

   class OtherPanel extends JPanel 
   {
      private OtherPanel()
      {
    ...

      }

      public void paintComponent(Graphics g) {
          super.paintComponent(g);

          Graphics2D g2d = (Graphics2D) g;            
              ....

          }

      private class ReloadListener implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {
           }
        }

    }
class OtherPanel extends JPanel 
{
    private boolean isReset;

    private OtherPanel()
    {
    ...
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(!isReset){
            //your painting code here
        }
    }

    public void setReset(boolean reset){
        isReset = reset;
    }

    private class ReloadListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            setReset(true);
            repaint();
        }

    }
}

All depends on how should a "reset" panel look like. I left just super.paintComponent() as the default looks, you might want to change that. Don't forget to add setReset(false) to your code somewhere when you want to paint something on the panel.

private class ReloadListener implements ActionListener
 {
    public void actionPerformed(ActionEvent e)
     {
       newPic();
       panel.updateUI();            

  }

   public MainFrame newPic()
   {

      return new MainFrame();
   }
 }

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