2014-05-20 38 views
0

當我運行應用程序時,整個框架被塗成黑色。如何僅在點擊按鈕後才能製作JFrame繪畫?

我怎樣才能使它開始清晰,然後當我按下按鈕時它會被繪製?

package card; 

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; 

public class BdayCard extends JFrame { 

JButton button1, button2; 
JPanel panel; 

BdayCard() 
{ 
    panel = new JPanel(); 
    button1 = new JButton(); 

    button1.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
      { 
       repaint(); 
      } 
    }); 

    panel.add(button1); 

    this.add(panel); 
    this.setTitle("It's Your Birthday!"); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setSize(600, 450); 
    this.setLocationRelativeTo(null); 
    this.setVisible(true); 
} 

public void paint(Graphics g){ 
    g.fillRect(0, 0, 600, 450); 
} 

public static void main(String[] args){ 
    new BdayCard(); 
} 
} 
+2

作爲一般的提示,這是更好地做定製畫一個'JPanel'或其他'JComponent',然後添加到一個頂層容器,比如'JFrame'。對於'JComponent'中的自定義繪畫,重寫'paintComponent(Graphics)'而不是'paint(Graphics)',並立即調用'super'方法繪製BG和邊框等。 –

+1

對於問題1:使用布爾標誌if (shouldDraw){g.fill ...}'。更新按鈕上的標誌。然後,你也可以使用'setBackground()'來處理這個特殊情況;-) –

+3

@peeskillet我想這可以在沒有定製繪畫的情況下完成。在動作監聽器中對'mainPanel.setBackground(color)'的調用應該能夠實現。 –

回答

1

與blackscreen你的問題是因爲你在畫:

g.fillRect(0, 0, 600, 450); 

您使用的是默認的顏色是黑色 我想你的代碼,並使用此:

g.setColor(Color.WHITE); 

這將清除你的屏幕,然後使用布爾值並在按下按鈕時將其設置爲true:

public void actionPerformed(ActionEvent e) 
{ 
    button=true; 
    repaint(); 
} 

然後最後使用:

if(button){/*do stuff here*/} 

在paint方法

+0

感謝您的解答和解決方案 – zcarciu

+0

請[接受](http://meta.stackoverflow.com/a/65088/155831)答案,如果它有助於解決問題。 –