2012-08-04 79 views
1

我目前正在爲Java遊戲創建一些自定義用戶界面。我現在正在創建一個窗口。無論如何,當我創建窗口(作爲JPanel)並在該窗口的頂部添加另一個主面板時,對於主要內容,主面板在兩個不同位置被繪製兩次,正確的一次,並且一次在左上角。喜歡的圖片顯示:JPanel中的JPanel在不同位置獲取兩次

Image of the JPanel drawn twice in different locations
中間的按鈕是正確的,並正確定位,而左上方是沒有的。黑色是主面板的背景。

這裏就是我試圖創建窗口的代碼:

package gui.elements; 

import graphic.CutSprite; 
import graphic.SpriteStorage; 
import gui.CFont; 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 

import javax.swing.JPanel; 

public class CWindow extends JPanel { 
    private static final long serialVersionUID = 1L; 

    // The main panel, on which components in the window are to be placed 
    private JPanel panel; 

    private String title; 

    public CWindow(String title) { 
     this(title, 380, 380); 
    } 

    public CWindow(String title, int width, int height) { 
     this.title = title; 

     // Place the main panel of the window 
     panel = new JPanel(); 
     panel.setBackground(Color.BLACK); 
     add(panel); 
    } 

    @Override 
    public void paintComponent(Graphics graphics) { 
     super.paintComponents(graphics); 
    } 

    public JPanel getPanel() { 
     return panel; 
    } 

} 

這裏的地方CWindow被實例化並加入框架:

package gui; 

import java.awt.Color; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

import gui.elements.CWindow; 

public class Screen { 

    private static Screen single = new Screen(); 
    public static Screen get() { return single; } 

    private JFrame frame; 
    private PanelManager panelManager; 
    private ScreenCanvas screenCanvas; 

    /** 
    * Constructor, set the window, and initialize the game. 
    */ 
    public Screen() { 
     frame = new JFrame("Game"); 

     // Frame (window) settings 
     frame.setSize(860, 540); 
     frame.setLocationRelativeTo(null); //Open window in center of screen 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     CWindow w = new CWindow("This is a window!"); 
     frame.add(w); 

     JButton tf9 = new JButton("Dunno?"); 
     w.getPanel().add(tf9); 

     // Display the window 
     frame.setVisible(true); 
    } 


    /** 
    * @return the height of the screen 
    */ 
    public static int getHeight() { 
     return get().frame.getHeight(); 
    } 

    /** 
    * @return the width of the screen 
    */ 
    public static int getWidth() { 
     return get().frame.getWidth(); 
    } 


    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     Screen.get(); 
    } 

} 

回答

3

好吧,發現和回答,怪異足夠。發佈xD後6分鐘令人尷尬。

好,所以這個問題是在下面的代碼super.paintComponents(graphics);在CWindow的類

@Override 
public void paintComponent(Graphics graphics) { 
    super.paintComponents(graphics); 
} 

不知道爲什麼,但它的工作,當我刪除了該行。

+0

即將寫出自己:D – 2012-08-04 22:14:54

+2

我敢打賭,如果你調用'super.paintComponent(graphics);',它會正常工作。 (注意.paintComponent中缺少's')。 :) – 2012-08-06 04:39:34

+0

美麗,就像分號錯誤;)謝謝:-) – 2012-08-12 19:32:07