2012-08-04 57 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