java - 使用 ActionListener 清除 JPanel 中的图形

标签 java swing

我的问题是,如何使用 Action 监听器清除图形并通过再次运行 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();
        }

    }
}

一切都取决于“重置”面板的外观。我只留下了 super.paintComponent() 作为默认外观,您可能想要更改它。当您想在面板上绘制某些内容时,请不要忘记将 setReset(false) 添加到代码中的某个位置。

关于java - 使用 ActionListener 清除 JPanel 中的图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764156/

相关文章:

java - 当元素移动到下一行时如何使用 FlowLayout 自动调整 JFrame 大小

java - propertyChange Support 与 EventListenerList 的差异以及何时更喜欢它们?

java - JLabel 位置不起作用,无法选择位置

java - 安全套接字连接

java - 如何在java中获取用户的操作系统区域设置

java - Openshift MySQL UTF-8 编码

java - 在 Spring boot 中添加超过 65535 个条目 jar

java - 广告选择面板抛出 JCombobox

java - CORBA + IDL + Java : need help with writing servant

java - 简单的 clojure java interop (swing) 程序不能完全让它工作