2012-03-29 42 views
2
public class TerrisView extends JFrame { 
    public Canvas canvas; 

    public TerrisView(String title) { 
     super(title); 
     canvas = new Canvas(); 
     canvas.setSize(300, 400); 
     canvas.setBackground(Color.WHITE); 
     // setSize(300, 400); 
     this.add(canvas, BorderLayout.CENTER); 
     pack(); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setVisible(true); 
     paint(); 

    } 

    public void paint() { 

     // this.createBufferStrategy(2); 
     // Graphics gp=getBufferStrategy().getDrawGraphics(); 
     // gp.setColor(Color.RED); 
     // gp.fillRect(100, 100, 50, 50); 
     // getBufferStrategy().show(); 
     Graphics gp = canvas.getGraphics(); 
     gp.setColor(Color.BLACK); 
     gp.fillRect(0, 0, 10, 10); 

    } 

} 

爲什麼它在畫布上繪製Rect失敗?代碼有什麼問題?搖擺畫布沒有按預期繪畫(或根本沒有畫)

+1

發佈代碼或代碼片段時,請使用代碼格式。 – 2012-03-30 04:00:56

回答

3
  • 請勿在沒有充分理由的情況下將Swing與AWT組件混合使用。
  • 在這種情況下:
    1. 延長JComponent代替Canvas
    2. 覆蓋的paintComponent(Graphics)代替paint(Graphics)

之前我格式化代碼,我沒有注意到,paint()不一個覆蓋,而這款經典..

Graphics gp = canvas.getGraphics(); 

不要做,與組件。使用傳遞到第2點中提到的方法Graphics對象,當被告知這樣做油漆。


這個答案已經被接受,但我無法抗拒審查和清理源作出SSCCE,以及​​添加一些更多的調整。請參閱代碼提示進一步評論。

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

public class TerrisView { 

    public JComponent canvas; 

    public TerrisView(String title) { 
     // Don't extend frame, just use one 
     JFrame f = new JFrame(title); 
     canvas = new JComponent() { 
      @Override // check this is a real method 
      public void paintComponent(Graphics g) { 
       super.paintComponent(g); 
       // paint the BG - automatic for a JPanel 
       g.setColor(getBackground()); 
       g.fillRect(0,0,getWidth(),getHeight()); 

       g.setColor(Color.BLACK); 
       // make it dynamic, changing with the size 
       int pad = 10; 
       g.fillRect(pad, pad, getWidth()-(2*pad), getHeight()-(2*pad)); 
      } 
     }; 
     // layout managers are more likely to respect the preferred size 
     canvas.setPreferredSize(new Dimension(300, 400)); 
     canvas.setBackground(Color.ORANGE); 
     f.add(canvas, BorderLayout.CENTER); 
     f.pack(); 
     // nice tweak 
     f.setMinimumSize(f.getSize()); 
     // see http://stackoverflow.com/a/7143398/418556 
     f.setLocationByPlatform(true); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 
    } 

    public static void main(String[] args) { 
     // start/alter Swing GUIs on the EDT 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new TerrisView("Terris View"); 
      } 
     }); 
    } 
} 
+0

又見編輯SSCCE。 – 2012-03-30 04:52:00