I am trying to make a Java application which on Clicking a button, displays random colors in the Panel for a particular time duration.
But my problem is that after clicking the button the color of the frame changes only once and also the the title of the Button doesn't changes to "U Clicked me".
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyDrawPanel extends JPanel {
@Override
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 randomizecolor = new Color(red, green, blue);
g.setColor(randomizecolor);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
public class CustomWidget implements ActionListener {
JButton button;
JFrame frame;
public void Gui() {
frame = new JFrame();
MyDrawPanel pan = new MyDrawPanel();
button = new JButton("-- Click Me to Change Me --");
frame.add(BorderLayout.SOUTH, button);
frame.add(BorderLayout.CENTER, pan);
button.addActionListener(this);
frame.setSize(500, 500);
frame.setTitle("Random Color GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void asd() {
button.setText("U clicked Me");
for (int i = 0; i < 150; i++) {
frame.repaint();
try {
Thread.sleep(10);
} catch (Exception x) {
}
}
button.setText("Again Click me");
}
public static void main(String[] args) {
CustomWidget obj = new CustomWidget();
obj.Gui();
}
@Override
public void actionPerformed(ActionEvent e) {
this.asd();
// this.button.setText("-- Click Me to Change Me --");
}
}