我有下面的程序,當它運行時有一些非常奇怪和不想要的行爲。 。它應該有兩個按鈕,「開始」和「停止,但是當我點擊‘開始’另一個按鈕顯示了下方的‘開始’這裏是打印屏幕什麼我談論:奇怪的JFrame行爲
什麼我做錯了,我怎麼解決這個難看的問題
下面的代碼:?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class TwoButtonsTest {
JFrame frame;
Timer timer;
boolean isClicked;
public static void main(String[] args) {
TwoButtonsTest test = new TwoButtonsTest();
test.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JButton startButton = new JButton("Start");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
final DrawPanel myDraw = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, myDraw);
frame.getContentPane().add(BorderLayout.NORTH, startButton);
frame.getContentPane().add(BorderLayout.SOUTH, stopButton);
frame.setVisible(true);
timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
myDraw.repaint();
}
});
}
class StartListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//needs to be implemented
if(!isClicked) {
}
isClicked = true;
timer.start();
}
}
class StopListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//needs to be implemented
timer.stop();
isClicked = false;
}
}
class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int)(Math.random()*256);
int blue = (int)(Math.random()*256);
int green = (int)(Math.random()*256);
g.setColor(new Color(red, blue, green));
Random rand = new Random();
// following 4 lines make sure the rect stays within the frame
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth()-wd);
int y = rand.nextInt(getHeight()-ht);
g.fillRect(x,y,wd,ht);
}
} // close inner class
}
而且我試圖讓開始按鈕做兩件事情之一是的當然開始動畫,但是當按下停止按鈕時,我按下再次開始,我希望它能夠清理屏幕,然後再次開始動畫。任何提示呢?
如果我做super.paintComponent(g),每次調用paintComponent都不會刷新屏幕嗎?這不是我想要做的事情。或者我對我的理解錯了嗎? –
@nickecarlo當然你想要重畫屏幕,並且你可以看到如果你不叫它會發生什麼。唯一可能發生的問題是你的圖形將被擦除,通過使它們持久化,即將所有要繪製的矩形添加到一個ArrayList並迭代'paintComponent'上的數組,這樣它們將在每次屏幕顯示時重繪 –
感謝您的意見。我也贊同你的回答。我會嘗試兩種答案,並接受最好的作品。 –