我正在嘗試製作一個Java應用程序,它在單擊一個按鈕時,在面板上顯示隨機顏色持續特定的時間。frame.repaint()無法正常工作
但我的問題是,點擊按鈕後,框架的顏色只改變一次,並且按鈕的標題也不會更改爲「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 --");
}
}
[使用睡眠()爲單個線程](http://stackoverflow.com/questions/14074329/using-sleep-for-a-single-線程) –