简体   繁体   English

使用ActionListener清除JPanel中的图形

[英]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? 我的问题是,如何通过再次运行OtherPanel来使用我的动作侦听器清除图形并创建一组新的图形?

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. 我只是将super.paintComponent()作为默认外观,你可能想要改变它。 Don't forget to add setReset(false) to your code somewhere when you want to paint something on the panel. 当你想在面板上绘制某些东西时,不要忘记在你的代码中添加setReset(false)

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

  }

   public MainFrame newPic()
   {

      return new MainFrame();
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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