2015-08-15 109 views
0

我正在尝试编写一个有2个按钮的程序,每当我按第一个按钮时,广场都应该重复地重新绘制,并在按第二个按钮时更改它的颜色。 但只要重新粉刷一次:( 如果有人能帮助我将不胜感激。单击按钮后重复重画面板

class Squre { 
JFrame frame; 
JButton button1; 
JButton button2; 
MyPanel panel; 

public static void main(String[] args){ 
    Squre s= new Squre(); 
    s.go(); 

} 
public void go(){ 
    frame = new JFrame(); 
    panel= new MyPanel(); 
    button1= new JButton(); 
    button2= new JButton(); 

    button1.setText("START"); 
    //button1.setSize(30, 20); 
    frame.setVisible(true); 
    frame.setSize(700,700); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().add(BorderLayout.CENTER ,panel);// add panel 
    frame .getContentPane().add(BorderLayout.WEST, button1);// add the west button 
    frame .getContentPane().add(BorderLayout.EAST, button2);//ADD THE EAST BUTTON 
    button1.addActionListener(new StrListener()); 
    button2.setText("EXPLOSION"); 
    button2.addActionListener(new ExpListener()); 
} 
private class StrListener implements ActionListener{ 

    public void actionPerformed(ActionEvent e){ 
     do{ 
      frame.repaint(); 

     } 
     while(e.equals(button2)==true); 
} 
} 
private class ExpListener implements ActionListener{ 
    // @Override 
    public void actionPerformed(ActionEvent e) { 
     System.exit(0); 
    } 
}class MyPanel extends JPanel{ 
public void paintComponent(Graphics g){ 
    g.fillRect(0,0,this.getWidth(),this.getHeight()); 

    int red = (int) (Math.random() * 255); 
    int green = (int) (Math.random() * 255); 
    int blue = (int) (Math.random() * 255); 
    Color rn=new Color(red, green, blue); 
    g.setColor(rn); 
    g.fillRect(250, 250, 50, 50); 



} 
}} 

回答

2
e.equals(button1) // event not equal to a button 

e.equals(button1)永远不会成为真正的,因为event不等于button。但repaint运行一次,因为它是一个做while循环。

你应该使用

e.getSource().equals(button1); 

检查点击按钮是否为button1

但即使你使用e.getSource().equals(button1)你不会看到颜色变化如你预期。如果你运行这个耗时而里面EDT循环,你将阻止EDT线程.hence颜色不得到改变,但如果你把一个sout你会看到该循环正在不断运行。您可以使用swing timer来实现此目的。摆动计时器不会阻止EDT。

使用Swing的计时器....

你应该导入swing timer //

private class StrListener implements ActionListener { 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource().equals(button1)) { 
      Timer t = new Timer(100, new ActionListener() { 

       @Override 
       public void actionPerformed(ActionEvent ae) { 
        frame.repaint(); 
       } 
      }); 
      t.start(); 
     } 
    } 
} 

enter image description here

+0

它是有用的,TNX – mlh