2012-12-11 86 views
1

有人可以看看我的代碼,並告訴我爲什麼,當我更改以下兩條語句時,我沒有看到矩形被繪的改變。所以,如果我改變:paintComponent不會改變形狀

g.setColor(Color.black); 
g.fillRect(l, w, 100, 100); 

程序還是打印黑色矩形具有相同尺寸和我第一次開始即使我改變顏色爲黃色或試圖更改尺寸或位置相同的位置。我是BlueJ。以下是我的完整代碼:

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

public class SwingPaintDemo2 extends JComponent { 

public static boolean isWall = true; 

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 


private static void createAndShowGUI() { 
    //System.out.println("Created GUI on EDT? "+ 
    //SwingUtilities.isEventDispatchThread()); 
    JFrame f = new JFrame("Swing Paint Demo"); 
    JPanel MyPanel = new JPanel(); 
    MyPanel.setBorder(BorderFactory.createEmptyBorder(1000, 1000, 1000, 1000)); 
    MyPanel.setPreferredSize(new Dimension(250, 200)); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(new MyPanel()); 
    f.pack(); 
    f.setVisible(true); 

} 


public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    int l = 10; 
    int w = 10; 

    g.setColor(Color.black); 
    g.fillRect(l, w, 100, 100); 

     } 

} 

任何意見,將不勝感激。

回答

5

您的SSCCE不會編譯MyPanel類,或者您的意思是new SwingPaintDemo2()

在你的意思new SwingPaintDemo2()假設:

的代碼不工作得很好,但在JFrame是規模非常小:

enter image description here

,因爲你不給它的組件的任何尺寸和無有一個尺寸,因爲他們沒有任何組件添加到他們,因此我們必須使JComponent返回一個正確的大小,所以當我們打電話pack()我們JFrame大小正確

倍率JComponentgetPreferredSize()返回的寬度和高度,其適合所有附圖。

雖然一些建議:

  • 不要延長JComponent而延長JPanel

這裏是(與上述修正你的代碼中實現)的例子:

enter image description here

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

public class SwingPaintDemo2 extends JPanel { 

    public static boolean isWall = true; 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 

    private static void createAndShowGUI() { 
     //System.out.println("Created GUI on EDT? "+ 
     //SwingUtilities.isEventDispatchThread()); 
     JFrame f = new JFrame("Swing Paint Demo"); 
     JPanel MyPanel = new JPanel(); 
     MyPanel.setBorder(BorderFactory.createEmptyBorder(1000, 1000, 1000, 1000)); 
     MyPanel.setPreferredSize(new Dimension(250, 200)); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.add(new SwingPaintDemo2()); 
     f.pack(); 
     f.setVisible(true); 

    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     int l = 10; 
     int w = 10; 

     g.setColor(Color.black); 
     g.fillRect(l, w, 100, 100); 

    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(150, 150); 
    } 
} 
+1

非常感謝你先生,那是做的。有趣的是,我第一次發佈的代碼並沒有給我一個編譯錯誤,也許這個類被損壞,因爲我正在移動的東西?但是當我用相同的代碼創建一個新類時,我看到了編譯錯誤。但無論如何,感謝您花時間幫助我。如果我可以讓你高興,我會(仍在努力我的名聲 - 新手)。 – user1894469

+0

@ user1894469至少現在工作。這不是一個問題,不要忘記檢查旁邊的勾號,如果它的答案。 –

+1

我剛要問你關於那個:)再次。 – user1894469