单击按钮后重复重复显示面板

时间:2015-08-15 19:30:23

标签: java graphics2d

我正在尝试编写一个有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);



}
}}

1 个答案:

答案 0 :(得分:2)

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

e.equals(button1)永远不会变为真,因为event不等于buttonrepaint会运行一次,因为它会循环播放。

你应该使用

e.getSource().equals(button1);

检查点击按钮是否为button1

但即使您使用e.getSource().equals(button1),也不会像预期的那样看到颜色变化。如果您在EDT内循环运行这段时间,则会阻止EDT线程。的颜色没有改变但是如果你放一个sout,你会看到循环不断运行。你可以使用swing timer。摆动计时器不会阻止EDT。

使用Swing计时器....

您应该导入swing timer // import javax.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