2012-03-19 34 views
0

我的问题是,如何通过再次运行OtherPanel,使用动作侦听器清除图形并创建一组新图形?使用ActionListener从JPanel清除图形

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) 
     { 
      } 
     } 

    } 
+0

这看起来真的很微不足道。你有什么尝试?它以什么方式失败? – John3136 2012-03-19 02:09:54

+0

我现在想通了。但我不知道为什么我需要updateUI(); – chief 2012-03-19 02:18:39

+4

不要为此使用'updateUI()'; 'panel.repaint()'应该就足够了。如果不是,请编辑您的问题以包含一个[sscce](http://sscce.org/),其中包含您所描述的问题。 – trashgod 2012-03-19 04:26:10

回答

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

    } 

    public MainFrame newPic() 
    { 

     return new MainFrame(); 
    } 
} 
+1

错误:应用程序代码不调用updateUI - 该方法专用于可插拔LAF机制 – kleopatra 2012-03-19 10:22:18

4
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)