I am trying to write a program that has 2 buttons which whenever i press the first, the square should repaint over and over and changed it's color while pressing the second one. but it just repaint one time :( if anyone can help i'll appreciate it.
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);
}
}}
e.equals(button1) // event not equal to a button
e.equals(button1)
never become true because a event
not equal to a button
.but repaint
runs one time because it's a do while loop.
you should use
e.getSource().equals(button1);
to check if clicked button is button1
or not.
but even you use e.getSource().equals(button1)
you will not see color changing as you expected .if you run this time consuming while loop inside EDT , you will block the EDT
thread .hence colors not get changed but if you put a sout
you will see that loop is running continually .you can use swing timer for this. swing timer will not block the EDT.
using Swing timer....
you should import 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();
}
}
}