0
我正在嘗試編寫一個有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);
}
}}
它是有用的,TNX – mlh