2013-07-13 132 views
0

这个简单的代码应该按下按钮后绘制矩形,但它不起作用。我不知道该怎么做,唯一让我想到的是一个布尔变量触发,但似乎并没有工作。任何建议?谢谢。Java-点击按钮后绘制矩形

public class testing extends JFrame implements ActionListener{ 
    public JButton button; 
    public boolean check; 

    public void paint(Graphics g){ 
     if(check==true){ 
      g.setColor(Color.red); 
      g.fillRect(30, 50, 50, 50); 
     } 
    } 

    public void start(){ 
     setLayout(new BorderLayout()); 
     button=new JButton(); 

     button.setPreferredSize(new Dimension(200,20)); 
     button.setText("ClickMe"); 
     button.addActionListener(this); 

     add(button, BorderLayout.SOUTH); 
     setSize(500,500); 
     setVisible(true); 
    }  

    public void actionPerformed(ActionEvent e) {  
     check=true; 
    } 

    public static void main(String args[]){ 
     testing x=new testing(); 
     x.start(); 
    } 
} 
+1

您需要在ActionListener中调用repaint。在Swing中使用'paintComponent'而不是'paint'来定制绘画。也调用'super.paintComponent(g)' – Reimeus

+0

@Reimeus'JFrame'没有'paintComponent'方法 – BackSlash

+0

是的我知道,这就是为什么我鼓励OP阅读[Performing Custom Painting](http:// docs。 oracle.com/javase/tutorial/uiswing/painting/)并找出需要的新类的位(提示) – Reimeus

回答

0

您可以在actionPerformed中调用repaint。

public void actionPerformed(ActionEvent e) {  
    check=true; 
    repaint(); 
}