2015-05-04 63 views
1
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
public class SimpleGui3C implements ActionListener{ 
    JFrame frame; 

    public static void main (String[] args){ 
     SimpleGui3C gui = new SimpleGui3C(); 
     gui.go(); 
    } 

    public void go() { 
     frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JButton button = new JButton("Change colours"); 
     button.addActionListener(this); 

     MyDrawPanel drawPanel = new MyDrawPanel(); 

     frame.getContentPane().add(BorderLayout.SOUTH, button); 
     frame.getContentPane().add(BorderLayout.CENTER, drawPanel); 
     frame.setSize(300,300); 
     frame.setVisible(true); 
    } 

    public void actionPerformed(ActionEvent event){ 
     frame.repaint(); 
    } 

} 

drawpanel圖形用戶界面沒有繪製在drawpanel上?

import java.awt.*; 
import javax.swing.*; 

public class MyDrawPanel extends JPanel{ 
    protected void paintComponenet(Graphics g){ 
     g.fillRect(0,0,this.getWidth(),this.getHeight()) 


     Graphics2D g2d = (Graphics2D) g; 

     int red = (int) Math.random() * 256; 
     int green = (int) Math.random() * 256; 
     int blue = (int) Math.random() * 256; 
     Color startColour = new Color(red,green,blue); 

     red = (int) Math.random() * 256; 
     green = (int) Math.random() * 256; 
     blue = (int) Math.random() * 256; 
     Color endColour = new Color(red,green,blue); 


     GradientPaint gradient = new GradientPaint(70,70,startColour,150,150,endColour); 
     g2d.setPaint(gradient); 
     g2d.fillOval(70,70,100,100); 
    } 


} 

我想了解GUI和我有一些代碼,應制定一個隨機顏色的圓圈每次按下按鈕時。

但此刻的drawpanel始終保持灰色,像這樣http://i.imgur.com/Kz84rKR.png

有什麼明顯的是,在停止從工作像它預期的代碼?

現在這個圓圈總是黑色的,並且永遠不會變成隨機的顏色。

回答

4

您拼寫paintComponent錯誤。總是先此方法@Override

所以改變這樣的:

public void paintComponenet(Graphics g) { 
    g.fillRect(0, 0, this.getWidth(),this.getHeight()); 

這樣:

@Override // add so the compiler will warn you if you spell it wrong 
protected void paintComponent(Graphics g) { // should be protected, not public 
    super.paintComponent(g); // so that you erase old images 
    g.fillRect(0, 0, this.getWidth(),this.getHeight()); 

編輯
你需要做的雙重數學括號所以右值被轉換爲int,因爲:

red = (int) Math.random() * 256; 

相當於該

red = ((int) (Math.random())) * 256; 

相當於此:

red = 0 * 256; 

所以取而代之,這樣做:

red = (int) (Math.random() * 256); 

但更重要的是,你需要學會調試。用printlns打印出你的顏色值,或者使用調試器來嘗試隔離你的錯誤。在來這裏之前先做這件事。例如:

red = (int) Math.random() * 256; 
    green = (int) Math.random() * 256; 
    blue = (int) Math.random() * 256; 

    // this will show you what your values are 
    // and key you in to where you should look: 
    System.out.printf("Colors: [%d, %d, %d]%n", red, green, blue); 

    Color endColour = new Color(red,green,blue); 
+0

我已經將我的代碼更新爲您所說的內容,但圓圈始終保持黑色,並且不會更改爲隨機顏色。 –

+0

@JohnSumner:請參閱編輯回答。 –

+0

耶謝謝所有的幫助抱歉不知道編輯原始帖子到目前的情況是壞的 –